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
giulio98/functional-diffusion-processes
src/functional_diffusion_processes/losses/mse_loss.py
[ { "identifier": "BaseMAML", "path": "src/functional_diffusion_processes/models/base_maml.py", "snippet": "class BaseMAML(nn.Module, abc.ABC):\n \"\"\"Abstract model class for implementing Model-Agnostic Meta-Learning (MAML).\n\n The Model-Agnostic Meta-Learning (MAML) algorithm is designed to trai...
import abc import jax import jax.numpy as jnp from functools import partial from typing import Any, Callable, TypeVar, Union from flax.core import FrozenDict from jax.random import PRNGKeyArray from omegaconf import DictConfig from ..models import BaseMAML, BaseViT from ..sdetools import SDE from ..utils.common import batch_mul
9,087
Params = FrozenDict[str, Any] T = TypeVar("T") class MSELoss(abc.ABC): """Abstract class for computing Mean Squared Error (MSE) Loss. Provides a structure for constructing a loss function to compute the MSE loss between model predictions and real data, with potential modifications for different domains (frequency or normal) and scheduling. Attributes: sde (SDE): An instance of stochastic differential equation to be used to calculate the weight factor in loss computation. loss_config (DictConfig): A configuration object holding parameters for loss computation. """ def __init__(self, sde: SDE, loss_config: DictConfig) -> None: """Initializes the MSELoss instance with SDE object and loss configuration. Args: sde (SDE): An object representing the stochastic differential equation. loss_config (DictConfig): A configuration object holding parameters for loss computation. """ self.sde = sde self.loss_config = loss_config
Params = FrozenDict[str, Any] T = TypeVar("T") class MSELoss(abc.ABC): """Abstract class for computing Mean Squared Error (MSE) Loss. Provides a structure for constructing a loss function to compute the MSE loss between model predictions and real data, with potential modifications for different domains (frequency or normal) and scheduling. Attributes: sde (SDE): An instance of stochastic differential equation to be used to calculate the weight factor in loss computation. loss_config (DictConfig): A configuration object holding parameters for loss computation. """ def __init__(self, sde: SDE, loss_config: DictConfig) -> None: """Initializes the MSELoss instance with SDE object and loss configuration. Args: sde (SDE): An object representing the stochastic differential equation. loss_config (DictConfig): A configuration object holding parameters for loss computation. """ self.sde = sde self.loss_config = loss_config
def construct_loss_fn(self, model: Union[BaseMAML, BaseViT]) -> Callable:
1
2023-10-24 22:01:35+00:00
12k
KosinskiLab/pyTME
tme/tests/test_matching_exhaustive.py
[ { "identifier": "scan", "path": "tme/matching_exhaustive.py", "snippet": "@device_memory_handler\ndef scan(\n matching_data: MatchingData,\n matching_setup: Callable,\n matching_score: Callable,\n n_jobs: int = 4,\n callback_class: CallbackClass = None,\n callback_class_args: Dict = {}...
import numpy as np import pytest from tme.matching_exhaustive import ( scan, scan_subsets, MATCHING_EXHAUSTIVE_REGISTER, register_matching_exhaustive, ) from tme.matching_data import MatchingData from tme.matching_utils import get_rotation_matrices from tme.matching_memory import MATCHING_MEMORY_REGISTRY
7,763
class TestMatchExhaustive: def setup_method(self): target = np.zeros((50, 50, 50)) target[20:30, 30:40, 12:17] = 1 self.target = target template = np.zeros((50, 50, 50)) template[15:25, 20:30, 2:7] = 1 self.template = template self.rotations = get_rotation_matrices(60)[0:2,] def teardown_method(self): self.target = None self.template = None self.coordinates = None self.coordinates_weights = None self.rotations = None @pytest.mark.parametrize("score", list(MATCHING_EXHAUSTIVE_REGISTER.keys())) def test_scan_single_core(self, score): matching_data = MatchingData(target=self.target, template=self.template) matching_data.target_mask = self.target matching_data.template_mask = self.template matching_data.rotations = self.rotations setup, process = MATCHING_EXHAUSTIVE_REGISTER[score] scan(matching_data=matching_data, matching_setup=setup, matching_score=process) @pytest.mark.parametrize("score", list(MATCHING_EXHAUSTIVE_REGISTER.keys())) def test_scan_single_multi_core(self, score): matching_data = MatchingData(target=self.target, template=self.template) matching_data.target_mask = self.target matching_data.template_mask = self.template matching_data.rotations = self.rotations setup, process = MATCHING_EXHAUSTIVE_REGISTER[score] scan( matching_data=matching_data, matching_setup=setup, matching_score=process, n_jobs=2, ) @pytest.mark.parametrize("score", list(MATCHING_EXHAUSTIVE_REGISTER.keys())) def test_scan_subsets_single_core(self, score): matching_data = MatchingData(target=self.target, template=self.template) matching_data.target_mask = self.target matching_data.template_mask = self.template matching_data.rotations = self.rotations setup, process = MATCHING_EXHAUSTIVE_REGISTER[score] target_splits = {i: 1 for i in range(self.target.ndim)} template_splits = {i: 1 for i in range(self.target.ndim)} target_splits[0], template_splits[1] = 2, 2 scan_subsets( matching_data=matching_data, matching_setup=setup, matching_score=process, target_splits=target_splits, template_splits=template_splits, job_schedule=(2, 1), ) @pytest.mark.parametrize("score", list(MATCHING_EXHAUSTIVE_REGISTER.keys())) def test_scan_subsets_single_multi_core(self, score): matching_data = MatchingData(target=self.target, template=self.template) matching_data.target_mask = self.target matching_data.template_mask = self.template matching_data.rotations = self.rotations setup, process = MATCHING_EXHAUSTIVE_REGISTER[score] target_splits = {i: 1 for i in range(self.target.ndim)} template_splits = {i: 1 for i in range(self.target.ndim)} target_splits[0], template_splits[1] = 2, 2 scan_subsets( matching_data=matching_data, matching_setup=setup, matching_score=process, target_splits=target_splits, template_splits=template_splits, job_schedule=(2, 1), ) @pytest.mark.parametrize("score", list(MATCHING_EXHAUSTIVE_REGISTER.keys())) def test_scan_subsets_single_multi_core_both(self, score): matching_data = MatchingData(target=self.target, template=self.template) matching_data.target_mask = self.target matching_data.template_mask = self.template matching_data.rotations = self.rotations setup, process = MATCHING_EXHAUSTIVE_REGISTER[score] target_splits = {i: 1 for i in range(self.target.ndim)} template_splits = {i: 1 for i in range(self.target.ndim)} target_splits[0], template_splits[1] = 2, 2 scan_subsets( matching_data=matching_data, matching_setup=setup, matching_score=process, target_splits=target_splits, template_splits=template_splits, job_schedule=(2, 2), ) def test_register_matching_exhaustive(self): setup, matching = MATCHING_EXHAUSTIVE_REGISTER[ list(MATCHING_EXHAUSTIVE_REGISTER.keys())[0] ] memory_class = MATCHING_MEMORY_REGISTRY[ list(MATCHING_EXHAUSTIVE_REGISTER.keys())[0] ]
class TestMatchExhaustive: def setup_method(self): target = np.zeros((50, 50, 50)) target[20:30, 30:40, 12:17] = 1 self.target = target template = np.zeros((50, 50, 50)) template[15:25, 20:30, 2:7] = 1 self.template = template self.rotations = get_rotation_matrices(60)[0:2,] def teardown_method(self): self.target = None self.template = None self.coordinates = None self.coordinates_weights = None self.rotations = None @pytest.mark.parametrize("score", list(MATCHING_EXHAUSTIVE_REGISTER.keys())) def test_scan_single_core(self, score): matching_data = MatchingData(target=self.target, template=self.template) matching_data.target_mask = self.target matching_data.template_mask = self.template matching_data.rotations = self.rotations setup, process = MATCHING_EXHAUSTIVE_REGISTER[score] scan(matching_data=matching_data, matching_setup=setup, matching_score=process) @pytest.mark.parametrize("score", list(MATCHING_EXHAUSTIVE_REGISTER.keys())) def test_scan_single_multi_core(self, score): matching_data = MatchingData(target=self.target, template=self.template) matching_data.target_mask = self.target matching_data.template_mask = self.template matching_data.rotations = self.rotations setup, process = MATCHING_EXHAUSTIVE_REGISTER[score] scan( matching_data=matching_data, matching_setup=setup, matching_score=process, n_jobs=2, ) @pytest.mark.parametrize("score", list(MATCHING_EXHAUSTIVE_REGISTER.keys())) def test_scan_subsets_single_core(self, score): matching_data = MatchingData(target=self.target, template=self.template) matching_data.target_mask = self.target matching_data.template_mask = self.template matching_data.rotations = self.rotations setup, process = MATCHING_EXHAUSTIVE_REGISTER[score] target_splits = {i: 1 for i in range(self.target.ndim)} template_splits = {i: 1 for i in range(self.target.ndim)} target_splits[0], template_splits[1] = 2, 2 scan_subsets( matching_data=matching_data, matching_setup=setup, matching_score=process, target_splits=target_splits, template_splits=template_splits, job_schedule=(2, 1), ) @pytest.mark.parametrize("score", list(MATCHING_EXHAUSTIVE_REGISTER.keys())) def test_scan_subsets_single_multi_core(self, score): matching_data = MatchingData(target=self.target, template=self.template) matching_data.target_mask = self.target matching_data.template_mask = self.template matching_data.rotations = self.rotations setup, process = MATCHING_EXHAUSTIVE_REGISTER[score] target_splits = {i: 1 for i in range(self.target.ndim)} template_splits = {i: 1 for i in range(self.target.ndim)} target_splits[0], template_splits[1] = 2, 2 scan_subsets( matching_data=matching_data, matching_setup=setup, matching_score=process, target_splits=target_splits, template_splits=template_splits, job_schedule=(2, 1), ) @pytest.mark.parametrize("score", list(MATCHING_EXHAUSTIVE_REGISTER.keys())) def test_scan_subsets_single_multi_core_both(self, score): matching_data = MatchingData(target=self.target, template=self.template) matching_data.target_mask = self.target matching_data.template_mask = self.template matching_data.rotations = self.rotations setup, process = MATCHING_EXHAUSTIVE_REGISTER[score] target_splits = {i: 1 for i in range(self.target.ndim)} template_splits = {i: 1 for i in range(self.target.ndim)} target_splits[0], template_splits[1] = 2, 2 scan_subsets( matching_data=matching_data, matching_setup=setup, matching_score=process, target_splits=target_splits, template_splits=template_splits, job_schedule=(2, 2), ) def test_register_matching_exhaustive(self): setup, matching = MATCHING_EXHAUSTIVE_REGISTER[ list(MATCHING_EXHAUSTIVE_REGISTER.keys())[0] ] memory_class = MATCHING_MEMORY_REGISTRY[ list(MATCHING_EXHAUSTIVE_REGISTER.keys())[0] ]
register_matching_exhaustive(
3
2023-10-20 13:46:01+00:00
12k
tonnetonne814/MB-iSTFT-BERT-VITS2-44100-Ja
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 audio files...
import os import torch import torch.distributed as dist import logging import commons import utils from torch.nn import functional as F from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from torch.nn.parallel import DistributedDataParallel as DDP from torch.cuda.amp import autocast, GradScaler from tqdm import tqdm from 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
9,084
# flake8: noqa: E402 logging.getLogger("numba").setLevel(logging.WARNING) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = ( True # If encontered training problem,please try to disable TF32. ) torch.set_float32_matmul_precision("medium") torch.backends.cudnn.benchmark = True torch.backends.cuda.sdp_kernel("flash") torch.backends.cuda.enable_flash_sdp(True) torch.backends.cuda.enable_mem_efficient_sdp( True ) # Not available if torch version is lower than 2.0 torch.backends.cuda.enable_math_sdp(True) global_step = 0 def run(): #dist.init_process_group( # backend="gloo", # init_method="env://", # Due to some training problem,we proposed to use gloo instead of nccl. #) # Use torchrun instead of mp.spawn #rank = dist.get_rank() #n_gpus = dist.get_world_size() rank = 0 n_gpus = 1 hps = utils.get_hparams() torch.manual_seed(hps.train.seed) torch.cuda.set_device(rank) global global_step if rank == 0: logger = utils.get_logger(hps.model_dir) logger.info(hps) utils.check_git_hash(hps.model_dir) writer = SummaryWriter(log_dir=hps.model_dir) writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval")) train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) train_sampler = DistributedBucketSampler( train_dataset, hps.train.batch_size, [32, 300, 400, 500, 600, 700, 800, 900, 1000], num_replicas=n_gpus, rank=rank, shuffle=True, )
# flake8: noqa: E402 logging.getLogger("numba").setLevel(logging.WARNING) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = ( True # If encontered training problem,please try to disable TF32. ) torch.set_float32_matmul_precision("medium") torch.backends.cudnn.benchmark = True torch.backends.cuda.sdp_kernel("flash") torch.backends.cuda.enable_flash_sdp(True) torch.backends.cuda.enable_mem_efficient_sdp( True ) # Not available if torch version is lower than 2.0 torch.backends.cuda.enable_math_sdp(True) global_step = 0 def run(): #dist.init_process_group( # backend="gloo", # init_method="env://", # Due to some training problem,we proposed to use gloo instead of nccl. #) # Use torchrun instead of mp.spawn #rank = dist.get_rank() #n_gpus = dist.get_world_size() rank = 0 n_gpus = 1 hps = utils.get_hparams() torch.manual_seed(hps.train.seed) torch.cuda.set_device(rank) global global_step if rank == 0: logger = utils.get_logger(hps.model_dir) logger.info(hps) utils.check_git_hash(hps.model_dir) writer = SummaryWriter(log_dir=hps.model_dir) writer_eval = SummaryWriter(log_dir=os.path.join(hps.model_dir, "eval")) train_dataset = TextAudioSpeakerLoader(hps.data.training_files, hps.data) train_sampler = DistributedBucketSampler( train_dataset, hps.train.batch_size, [32, 300, 400, 500, 600, 700, 800, 900, 1000], num_replicas=n_gpus, rank=rank, shuffle=True, )
collate_fn = TextAudioSpeakerCollate()
1
2023-10-16 10:04:32+00:00
12k
GXimingLu/IPA
main.py
[ { "identifier": "get_args", "path": "arguments.py", "snippet": "def get_args():\n parser = argparse.ArgumentParser(description='RL')\n\n # dataset\n parser.add_argument(\n '--output-dir', type=str, default=f'{HOME_PATH}/commonGen')\n parser.add_argument(\n '--dataset-train', ty...
import os import torch import json import time import logging import random import argparse import numpy as np import torch.nn.functional as F from typing import List from datetime import datetime from tqdm import tqdm from torch.utils.data import Dataset, DataLoader from torch.optim import Adam, Optimizer from torch.optim.lr_scheduler import LambdaLR from torch.utils.tensorboard import SummaryWriter from transformers import get_linear_schedule_with_warmup from arguments import get_args from policy import Policy from data_pool import DataPool from reward import Reward from utils.utils import ensure_dir, ceil_div, reduce_mean, reduce_sum from utils.generation_utils import decode
8,347
'loss/total': data['total_loss'].item(), 'loss/kl': data['kl_loss'].item(), 'loss/lm': data['lm_loss'].item(), 'loss/entropy': data['entropy'].item(), }) return stats def print_samples(self, queries, responses, lm_loss, logprobs, ref_logprobs, masks, step): if step % self.params.log_interval != 0: return # Log samples for i in range(min(3, len(queries))): sample_kl = torch.sum((logprobs[i] - ref_logprobs[i]) * masks[i]).item() print(queries[i] + responses[i]) print(f" lm_loss = {lm_loss[i].item():+.2f}") print(f" kl = {sample_kl:+.2f}") print(f" total = {lm_loss[i].item() + self.params.kl_coef * sample_kl:+.2f}") def save(self, step): if step < self.params.min_save_step or step > self.params.max_save_step or step % self.params.save_interval != 0: return torch.save({ 'step': step, 'value_model': self.policy.value_model.state_dict(), 'optimizer': self.optimizer.state_dict(), 'scheduler': self.scheduler.state_dict(), 'data_pool': self.data_pool.data_to_save(), }, f'{self.params.model_dir}/ckp_{step}.pth') log.info(f"[step {step}] model checkpoint saved") def eval(self, step): if step % self.params.eval_interval != 0: return log.info(f"[step {step}] evaluating ...") concepts, prompts, uncons_gens, cons_gens = [], [], [], [] for i, batch in enumerate(tqdm(self.val_dataloader)): input_ids, attention_mask, concept, constraints = batch with torch.no_grad(): uncons_rollouts = self.policy.sample(input_ids=input_ids, attention_mask=attention_mask, max_len=self.params.response_length, top_p=self.params.top_p, use_control_code=(step > 0)) cons_rollouts = self.policy.sample(input_ids=input_ids, attention_mask=attention_mask, constraints=constraints, max_len=self.params.response_length, top_p=self.params.top_p, use_control_code=(step > 0)) concepts.extend(concept) prompts.extend(uncons_rollouts['query/text']) uncons_gens.extend(uncons_rollouts['response/text']) cons_gens.extend(cons_rollouts['response/text']) for eval_name, gens in [('unconstrained', uncons_gens), ('constrained', cons_gens)]: print(f" {eval_name.capitalize()} evaluation: ") score_dict = self.score_model.get_reward(prompts, gens, concepts, f'step{step}_eval_{eval_name}') for name, scores in score_dict.items(): metric_score = np.mean(scores) print(f" {name} = {metric_score:+.2f}") self.writer.add_scalar(f'{eval_name.capitalize()}_eval/{name}', metric_score, step) def main(): args = get_args() random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) if args.cuda and torch.cuda.is_available() and args.cuda_deterministic: torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False num_gpus = torch.cuda.device_count() log.info(f'Detect {num_gpus} GPUS') device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') if args.resume is None: date_time = datetime.now().strftime("%m-%d-%Y_%H:%M:%S") args.save_dir = os.path.join(args.output_dir, date_time) else: sub_dirs = args.resume.split(os.sep) date_time, args.output_dir, args.save_dir = sub_dirs[-3], os.sep.join(sub_dirs[:-3]), os.sep.join(sub_dirs[:-2]) args.reward_dir = os.path.join(args.save_dir, 'reward') args.model_dir = os.path.join(args.save_dir, 'model') args.tensorboard_dir = os.path.join(args.output_dir, 'tensorboard', date_time) log.info(f'Write to output directory: {args.save_dir}') if args.resume is None: for d in [args.output_dir, args.save_dir, args.reward_dir, args.model_dir, args.tensorboard_dir]: ensure_dir(d) with open(os.path.join(args.save_dir, 'args.json'), 'w') as f: json.dump(args.__dict__, f, indent=2) tree_tokens = [' _TREE_TOKEN_{}'.format(str(idx).zfill(5)) for idx in range(args.n_extra_tokens)] log.info(f'Initializing models ...') policy_checkpoint = torch.load(args.base_model_checkpoint, map_location='cpu')['policy_model'] policy = Policy(base_model_name=args.base_model_name, base_model_checkpoint=policy_checkpoint, value_model_name=args.value_model_name, device=device, tree_tokens=tree_tokens, alpha=args.alpha, calibrate=args.gpt3_calibrate, force_eos=args.force_eos) reward = Reward(save_path=args.reward_dir, batch_size=args.reward_batch_size, device=num_gpus - 1, params=args) data_pool = DataPool(tree_tokens=tree_tokens, n_extra_tokens=args.n_extra_tokens) log.info(f'Initialization done!') prompt_collator = PromptCollator(tokenizer=policy.tokenizer) train_dataset = PromptDataset(path=args.dataset_train, tokenizer=policy.tokenizer) train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, drop_last=True, collate_fn=prompt_collator) log.info(f'Load train set with {len(train_dataset)} examples') val_dataset = PromptDataset(path=args.dataset_val, tokenizer=policy.tokenizer) val_dataloader = DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False, collate_fn=prompt_collator) log.info(f'Load val set with {len(val_dataset)} examples') # set up optimizer and scheduler optimizer = Adam(policy.value_model.parameters(), lr=args.lr, eps=1e-5)
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO")) log = logging.getLogger(__name__) class PromptDataset(Dataset): def __init__(self, path, tokenizer): data = json.load(open(path, 'r')) self.items = [v for k, v in data.items() if v['human_order']] self.tokenizer = tokenizer def __len__(self): return len(self.items) def __getitem__(self, idx): item = self.items[idx] order_words = random.choice(item['human_order']) constraint = json.dumps([list(map(lambda x: self.tokenizer.encode(f' {x}'), item['inflection'][w])) for w in order_words.split('-')]) prompt = 'Generate a sentence including the following keywords in the same order as listed: %s\n\nAnswer:' prompt = prompt % ' '.join(order_words.split('-')) return { 'order': order_words, 'constraint': constraint, 'prompt': prompt, } class PromptCollator(object): def __init__(self, tokenizer): self.tokenizer = tokenizer def __call__(self, sequences): concepts = [sequence['order'] for sequence in sequences] prompts = [sequence['prompt'] for sequence in sequences] constraints = [sequence['constraint'] for sequence in sequences] encodings_dict = self.tokenizer(prompts, return_tensors="pt", padding=True) input_ids = encodings_dict['input_ids'] attention_mask = encodings_dict['attention_mask'] return input_ids, attention_mask, concepts, constraints class SequenceDataset(Dataset): def __init__(self, data_pool: DataPool): self.queries, self.responses, self.cat_tokens = data_pool.get_data() def __len__(self): return len(self.queries) def __getitem__(self, idx): return {'query': self.queries[idx], 'response': self.responses[idx], 'cat_tokens': self.cat_tokens[idx] } class SequenceCollator(object): def __init__(self, tokenizer): self.tokenizer = tokenizer def __call__(self, sequences): queries = [sequence['query'] for sequence in sequences] responses = [sequence['response'] + self.tokenizer.eos_token for sequence in sequences] cat_ids = [self.tokenizer.convert_tokens_to_ids(sequence['cat_tokens']) for sequence in sequences] query_encodings_dict = self.tokenizer(queries, return_tensors="pt", padding=True) query_input_ids = query_encodings_dict['input_ids'] query_mask = query_encodings_dict['attention_mask'] query_input_ids = torch.cat([query_input_ids.new(cat_ids)[:, None], query_input_ids], dim=1) query_mask = torch.cat([query_mask.new([1] * len(query_mask))[:, None], query_mask], dim=1) response_encodings_dict = self.tokenizer(responses, return_tensors="pt", padding=True) response_input_ids = response_encodings_dict['input_ids'] response_mask = response_encodings_dict['attention_mask'] return query_input_ids, query_mask, response_input_ids, response_mask class FixedController: def __init__(self, coef): self.value = coef def update(self, current, n_steps, lower_bound): pass class AdaptiveController: def __init__(self, init_coef, target, horizon): self.value = init_coef self.target = target self.horizon = horizon def update(self, current, n_steps, lower_bound): proportional_error = np.clip(current / self.target - 1, -0.2, 0.2) if lower_bound: mult = 1 + proportional_error * n_steps / self.horizon else: mult = 1 - proportional_error * n_steps / self.horizon self.value *= mult class ConditionTrainer: def __init__(self, params: argparse.Namespace, policy: Policy, data_pool: DataPool, score_model: Reward, tree_tokens: List[str], train_dataloader: DataLoader, val_dataloader: DataLoader, optimizer: Optimizer, scheduler: LambdaLR, resume: bool): self.params = params self.policy = policy self.data_pool = data_pool self.score_model = score_model self.optimizer = optimizer self.scheduler = scheduler self.train_dataloader = train_dataloader self.val_dataloader = val_dataloader self.writer = SummaryWriter(log_dir=params.tensorboard_dir) if self.params.adaptive_kl: self.kl_ctl = AdaptiveController(self.params.kl_coef, self.params.target_kl, self.params.horizon) else: self.kl_ctl = FixedController(self.params.kl_coef) self.kl_loss = torch.nn.KLDivLoss(reduction="none") if self.params.adaptive_entropy: self.entropy_ctl = AdaptiveController(self.params.entropy_coef, self.params.target_entropy, self.params.horizon) else: self.entropy_ctl = FixedController(self.params.entropy_coef) self.tree_tokens = tree_tokens self.best_cat = self.tree_tokens[0] self.best_cat_id = self.policy.tokenizer.convert_tokens_to_ids(self.best_cat) self.sample_dataloader, self.sampler = None, None self.seq_collator = SequenceCollator(tokenizer=policy.tokenizer) if resume: sample_dataset = SequenceDataset(data_pool=self.data_pool) self.sample_dataloader = DataLoader(sample_dataset, batch_size=self.params.batch_size, shuffle=True, drop_last=True, collate_fn=self.seq_collator) self.sampler = iter(self.sample_dataloader) def sample(self, step): if step % self.params.sample_interval != 0: return log.info(f"[step {step}] Sampling ...") concepts, prompts, responses = [], [], [] for i, batch in enumerate(tqdm(self.train_dataloader, total=len(self.train_dataloader), desc='Sampling from current policy')): input_ids, attention_mask, concept, constraints = batch use_constraint = random.choices([1, 0], weights=[self.params.hard_prob, 1 - self.params.hard_prob], k=1)[0] rollouts = self.policy.sample(input_ids=input_ids, attention_mask=attention_mask, constraints=constraints if use_constraint else None, max_len=self.params.response_length, top_p=self.params.top_p, use_control_code=(step > 0)) prompt, response = rollouts['query/text'], rollouts['response/text'] concepts.extend(concept) prompts.extend(prompt) responses.extend(response) scores = self.score_model.get_reward(prompts, responses, concepts, f'step{step}') self.data_pool.add(prompts=prompts, responses=responses, scores=scores['reward']) sample_dataset = SequenceDataset(data_pool=self.data_pool) self.sample_dataloader = DataLoader(sample_dataset, batch_size=self.params.batch_size, shuffle=True, drop_last=True, collate_fn=self.seq_collator) self.sampler = iter(self.sample_dataloader) def step(self, step_num): step_started_at = time.time() self.save(step=step_num) self.eval(step=step_num) self.sample(step=step_num) try: batch = next(self.sampler) assert len(batch[0]) == self.params.batch_size, 'insufficient batch' except (StopIteration, AssertionError): self.sampler = iter(self.sample_dataloader) batch = next(self.sampler) self.policy.value_model.train() ppo_loss, stats = self.loss(step_num, *batch) ppo_loss = ppo_loss / self.params.grad_accum ppo_loss.backward() if self.params.clip_grad: torch.nn.utils.clip_grad_norm_(self.policy.value_model.parameters(), self.params.max_grad_norm) if (step_num + 1) % self.params.grad_accum == 0: self.optimizer.step() self.optimizer.zero_grad() self.scheduler.step() for metric in ['kl', 'entropy']: self.writer.add_scalar(f'Objective/{metric}', stats[f'objective/{metric}'], step_num) for metric in ['lm', 'kl', 'entropy', 'total']: self.writer.add_scalar(f'Loss/{metric}', stats[f'loss/{metric}'], step_num) self.writer.add_scalar(f'Params/lr', self.optimizer.param_groups[0]['lr'], step_num) self.writer.add_scalar(f'Params/kl_coef', self.kl_ctl.value, step_num) self.writer.add_scalar(f'Params/entropy_coef', self.entropy_ctl.value, step_num) self.kl_ctl.update(stats['objective/kl'], self.params.batch_size, True) self.entropy_ctl.update(stats['objective/entropy'], self.params.batch_size, False) step_time = time.time() - step_started_at eps_per_second = float(self.params.batch_size) / step_time log.info(f"[step {step_num}] step_time={step_time:.2f}s, eps/s={eps_per_second:.2f}") def loss(self, step, query_input_ids, query_mask, response_input_ids, response_mask): outputs = self.policy.forward_pass(query_input_ids, query_mask, response_input_ids, response_mask, use_control_code=True) lm_loss, logprobs, entropy, logits = outputs['response/lm_loss'], outputs['response/log_prob'], \ outputs['response/entropy'], outputs['response/logits'] masks = response_mask.to(self.policy.device) with torch.no_grad(): ref_outputs = self.policy.forward_pass(query_input_ids[:, 1:], query_mask[:, 1:], response_input_ids, response_mask, use_control_code=False) ref_logprobs, ref_logits = ref_outputs['response/log_prob'], ref_outputs['response/logits'] kl = torch.sum(self.kl_loss(F.log_softmax(ref_logits, dim=-1), F.softmax(logits, dim=-1)), dim=-1) loss = reduce_mean(lm_loss + self.kl_ctl.value * kl - self.entropy_ctl.value * entropy, masks) data = {'logprobs': logprobs, 'ref_logprobs': ref_logprobs, 'masks': masks, 'logits': logits, 'ref_logits': ref_logits, 'lm_loss': reduce_mean(lm_loss, masks), 'kl_loss': reduce_mean(kl, masks), 'entropy': reduce_mean(entropy, masks), 'total_loss': loss} stats = self.record_step_stats(data) queries, responses = decode(self.policy.tokenizer, query_input_ids, response_input_ids) self.print_samples(queries=queries, responses=responses, lm_loss=reduce_mean(lm_loss, masks, axis=1), logprobs=logprobs, ref_logprobs=ref_logprobs, masks=masks, step=step) return loss, stats def record_step_stats(self, data): masks = data['masks'] kl = torch.sum(self.kl_loss(F.log_softmax(data['ref_logits'], dim=-1), F.softmax(data['logits'], dim=-1)), dim=-1) mean_kl = torch.mean(reduce_sum(kl, masks, axis=1)) mean_entropy = torch.mean(reduce_sum(-data['logprobs'], masks, axis=1)) stats = { 'objective/kl': mean_kl.item(), 'objective/entropy': mean_entropy.item(), } stats.update({ 'loss/total': data['total_loss'].item(), 'loss/kl': data['kl_loss'].item(), 'loss/lm': data['lm_loss'].item(), 'loss/entropy': data['entropy'].item(), }) return stats def print_samples(self, queries, responses, lm_loss, logprobs, ref_logprobs, masks, step): if step % self.params.log_interval != 0: return # Log samples for i in range(min(3, len(queries))): sample_kl = torch.sum((logprobs[i] - ref_logprobs[i]) * masks[i]).item() print(queries[i] + responses[i]) print(f" lm_loss = {lm_loss[i].item():+.2f}") print(f" kl = {sample_kl:+.2f}") print(f" total = {lm_loss[i].item() + self.params.kl_coef * sample_kl:+.2f}") def save(self, step): if step < self.params.min_save_step or step > self.params.max_save_step or step % self.params.save_interval != 0: return torch.save({ 'step': step, 'value_model': self.policy.value_model.state_dict(), 'optimizer': self.optimizer.state_dict(), 'scheduler': self.scheduler.state_dict(), 'data_pool': self.data_pool.data_to_save(), }, f'{self.params.model_dir}/ckp_{step}.pth') log.info(f"[step {step}] model checkpoint saved") def eval(self, step): if step % self.params.eval_interval != 0: return log.info(f"[step {step}] evaluating ...") concepts, prompts, uncons_gens, cons_gens = [], [], [], [] for i, batch in enumerate(tqdm(self.val_dataloader)): input_ids, attention_mask, concept, constraints = batch with torch.no_grad(): uncons_rollouts = self.policy.sample(input_ids=input_ids, attention_mask=attention_mask, max_len=self.params.response_length, top_p=self.params.top_p, use_control_code=(step > 0)) cons_rollouts = self.policy.sample(input_ids=input_ids, attention_mask=attention_mask, constraints=constraints, max_len=self.params.response_length, top_p=self.params.top_p, use_control_code=(step > 0)) concepts.extend(concept) prompts.extend(uncons_rollouts['query/text']) uncons_gens.extend(uncons_rollouts['response/text']) cons_gens.extend(cons_rollouts['response/text']) for eval_name, gens in [('unconstrained', uncons_gens), ('constrained', cons_gens)]: print(f" {eval_name.capitalize()} evaluation: ") score_dict = self.score_model.get_reward(prompts, gens, concepts, f'step{step}_eval_{eval_name}') for name, scores in score_dict.items(): metric_score = np.mean(scores) print(f" {name} = {metric_score:+.2f}") self.writer.add_scalar(f'{eval_name.capitalize()}_eval/{name}', metric_score, step) def main(): args = get_args() random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) if args.cuda and torch.cuda.is_available() and args.cuda_deterministic: torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False num_gpus = torch.cuda.device_count() log.info(f'Detect {num_gpus} GPUS') device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') if args.resume is None: date_time = datetime.now().strftime("%m-%d-%Y_%H:%M:%S") args.save_dir = os.path.join(args.output_dir, date_time) else: sub_dirs = args.resume.split(os.sep) date_time, args.output_dir, args.save_dir = sub_dirs[-3], os.sep.join(sub_dirs[:-3]), os.sep.join(sub_dirs[:-2]) args.reward_dir = os.path.join(args.save_dir, 'reward') args.model_dir = os.path.join(args.save_dir, 'model') args.tensorboard_dir = os.path.join(args.output_dir, 'tensorboard', date_time) log.info(f'Write to output directory: {args.save_dir}') if args.resume is None: for d in [args.output_dir, args.save_dir, args.reward_dir, args.model_dir, args.tensorboard_dir]: ensure_dir(d) with open(os.path.join(args.save_dir, 'args.json'), 'w') as f: json.dump(args.__dict__, f, indent=2) tree_tokens = [' _TREE_TOKEN_{}'.format(str(idx).zfill(5)) for idx in range(args.n_extra_tokens)] log.info(f'Initializing models ...') policy_checkpoint = torch.load(args.base_model_checkpoint, map_location='cpu')['policy_model'] policy = Policy(base_model_name=args.base_model_name, base_model_checkpoint=policy_checkpoint, value_model_name=args.value_model_name, device=device, tree_tokens=tree_tokens, alpha=args.alpha, calibrate=args.gpt3_calibrate, force_eos=args.force_eos) reward = Reward(save_path=args.reward_dir, batch_size=args.reward_batch_size, device=num_gpus - 1, params=args) data_pool = DataPool(tree_tokens=tree_tokens, n_extra_tokens=args.n_extra_tokens) log.info(f'Initialization done!') prompt_collator = PromptCollator(tokenizer=policy.tokenizer) train_dataset = PromptDataset(path=args.dataset_train, tokenizer=policy.tokenizer) train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, drop_last=True, collate_fn=prompt_collator) log.info(f'Load train set with {len(train_dataset)} examples') val_dataset = PromptDataset(path=args.dataset_val, tokenizer=policy.tokenizer) val_dataloader = DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False, collate_fn=prompt_collator) log.info(f'Load val set with {len(val_dataset)} examples') # set up optimizer and scheduler optimizer = Adam(policy.value_model.parameters(), lr=args.lr, eps=1e-5)
args.total_steps = ceil_div(args.total_episodes, args.batch_size)
5
2023-10-20 08:30:18+00:00
12k
violet-sto/HN-GFN
main.py
[ { "identifier": "Dataset", "path": "dataset.py", "snippet": "class Dataset:\n\n def __init__(self, args, bpath, oracle, device):\n self.test_split_rng = np.random.RandomState(142857)\n self.train_rng = np.random.RandomState(int(time.time()))\n self.train_mols = []\n self.t...
from curses import raw from dataset import Dataset from mol_mdp_ext import MolMDPExtended, BlockMoleculeDataExtended from oracle.oracle import Oracle from proxy import get_proxy from generator import TBGFlowNet, FMGFlowNet from utils.metrics import circle_points, compute_success, compute_diversity, compute_novelty, evaluate, compute_correlation from utils.utils import set_random_seed from utils.logging import get_logger from datetime import datetime from botorch.utils.multi_objective.hypervolume import Hypervolume from botorch.utils.sampling import sample_simplex from botorch.utils.transforms import normalize, unnormalize from torch.distributions.dirichlet import Dirichlet from rdkit.Chem import AllChem from rdkit import DataStructs from pymoo.util.ref_dirs import get_reference_directions import os import argparse import json import time import threading import pdb import pickle import gzip import warnings import torch.multiprocessing as mp import torch.nn.functional as F import torch import pandas as pd import numpy as np
10,298
warnings.filterwarnings('ignore') def arg_parse(): parser = argparse.ArgumentParser() parser.add_argument("--device", type=str, default='cuda') parser.add_argument('--seed', type=int, default=42, help='seed') parser.add_argument("--run", default=0, help="run", type=int) parser.add_argument('--save', action='store_true', default=False, help='Save model.') parser.add_argument('--debug', action='store_true', default=False, help='debug mode, no multi thread') parser.add_argument("--enable_tensorboard", action='store_true', default=False) parser.add_argument("--log_dir", default='runs/synthetic') parser.add_argument("--include_nblocks", default=False) parser.add_argument("--num_samples", default=1000, type=int) parser.add_argument("--floatX", default='float32') parser.add_argument('--sample_iterations', type=int, default=1000, help='sample mols and compute metrics') # objectives parser.add_argument("--objectives", type=str, default='gsk3b,jnk3') parser.add_argument("--scalar", default='WeightedSum', type=str) #TODO: other scalars parser.add_argument("--alpha", default=1., type=float, help='dirichlet distribution') parser.add_argument("--alpha_vector", default='1,1', type=str) # GFlowNet parser.add_argument("--min_blocks", default=2, type=int) parser.add_argument("--max_blocks", default=8, type=int) parser.add_argument("--num_iterations", default=30000, type=int) # 30k parser.add_argument("--criterion", default="FM", type=str) parser.add_argument("--learning_rate", default=5e-4, help="Learning rate", type=float) parser.add_argument("--Z_learning_rate", default=5e-3, help="Learning rate", type=float) parser.add_argument("--clip_grad", default=0, type=float) parser.add_argument("--trajectories_mbsize", default=16, type=int) parser.add_argument("--offline_mbsize", default=0, type=int) parser.add_argument("--hindsight_mbsize", default=0, type=int) parser.add_argument("--reward_min", default=1e-2, type=float) parser.add_argument("--reward_norm", default=0.8, type=float) parser.add_argument("--reward_exp", default=6, type=float) parser.add_argument("--reward_exp_ramping", default=0, type=float) # Hyperparameters for TB parser.add_argument("--partition_init", default=30, type=float) # Hyperparameters for FM parser.add_argument("--log_reg_c", default=(0.1/8) ** 4, type=float) # (0.1/8)**8 parser.add_argument("--balanced_loss", default=True) parser.add_argument("--leaf_coef", default=10, type=float) # Architecture parser.add_argument("--repr_type", default='block_graph') parser.add_argument("--model_version", default='v4') parser.add_argument("--condition_type", default='HN', type=str) # 'HN', 'FiLM', 'concat' parser.add_argument("--num_conv_steps", default=10, type=int) parser.add_argument("--nemb", default=256, help="#hidden", type=int) parser.add_argument("--weight_decay", default=0, type=float) parser.add_argument("--random_action_prob", default=0.05, type=float) parser.add_argument("--bootstrap_tau", default=0, type=float) parser.add_argument("--ray_hidden_dim", default=100, type=int) parser.add_argument("--logit_clipping", default=0., type=float) return parser.parse_args() class RolloutWorker: def __init__(self, args, bpath, proxy, device): self.args = args self.test_split_rng = np.random.RandomState(142857) self.train_rng = np.random.RandomState(int(time.time()))
warnings.filterwarnings('ignore') def arg_parse(): parser = argparse.ArgumentParser() parser.add_argument("--device", type=str, default='cuda') parser.add_argument('--seed', type=int, default=42, help='seed') parser.add_argument("--run", default=0, help="run", type=int) parser.add_argument('--save', action='store_true', default=False, help='Save model.') parser.add_argument('--debug', action='store_true', default=False, help='debug mode, no multi thread') parser.add_argument("--enable_tensorboard", action='store_true', default=False) parser.add_argument("--log_dir", default='runs/synthetic') parser.add_argument("--include_nblocks", default=False) parser.add_argument("--num_samples", default=1000, type=int) parser.add_argument("--floatX", default='float32') parser.add_argument('--sample_iterations', type=int, default=1000, help='sample mols and compute metrics') # objectives parser.add_argument("--objectives", type=str, default='gsk3b,jnk3') parser.add_argument("--scalar", default='WeightedSum', type=str) #TODO: other scalars parser.add_argument("--alpha", default=1., type=float, help='dirichlet distribution') parser.add_argument("--alpha_vector", default='1,1', type=str) # GFlowNet parser.add_argument("--min_blocks", default=2, type=int) parser.add_argument("--max_blocks", default=8, type=int) parser.add_argument("--num_iterations", default=30000, type=int) # 30k parser.add_argument("--criterion", default="FM", type=str) parser.add_argument("--learning_rate", default=5e-4, help="Learning rate", type=float) parser.add_argument("--Z_learning_rate", default=5e-3, help="Learning rate", type=float) parser.add_argument("--clip_grad", default=0, type=float) parser.add_argument("--trajectories_mbsize", default=16, type=int) parser.add_argument("--offline_mbsize", default=0, type=int) parser.add_argument("--hindsight_mbsize", default=0, type=int) parser.add_argument("--reward_min", default=1e-2, type=float) parser.add_argument("--reward_norm", default=0.8, type=float) parser.add_argument("--reward_exp", default=6, type=float) parser.add_argument("--reward_exp_ramping", default=0, type=float) # Hyperparameters for TB parser.add_argument("--partition_init", default=30, type=float) # Hyperparameters for FM parser.add_argument("--log_reg_c", default=(0.1/8) ** 4, type=float) # (0.1/8)**8 parser.add_argument("--balanced_loss", default=True) parser.add_argument("--leaf_coef", default=10, type=float) # Architecture parser.add_argument("--repr_type", default='block_graph') parser.add_argument("--model_version", default='v4') parser.add_argument("--condition_type", default='HN', type=str) # 'HN', 'FiLM', 'concat' parser.add_argument("--num_conv_steps", default=10, type=int) parser.add_argument("--nemb", default=256, help="#hidden", type=int) parser.add_argument("--weight_decay", default=0, type=float) parser.add_argument("--random_action_prob", default=0.05, type=float) parser.add_argument("--bootstrap_tau", default=0, type=float) parser.add_argument("--ray_hidden_dim", default=100, type=int) parser.add_argument("--logit_clipping", default=0., type=float) return parser.parse_args() class RolloutWorker: def __init__(self, args, bpath, proxy, device): self.args = args self.test_split_rng = np.random.RandomState(142857) self.train_rng = np.random.RandomState(int(time.time()))
self.mdp = MolMDPExtended(bpath)
1
2023-10-24 14:10:35+00:00
12k
SALT-NLP/Efficient_Unlearning
src/models/transformers/parameter-efficient-finetuning/layer.py
[ { "identifier": "AdapterCompositionBlock", "path": "src/models/transformers/parameter-efficient-finetuning/composition.py", "snippet": "class AdapterCompositionBlock(Sequence):\n def __init__(self, *children):\n self.children = [parse_composition(b, None) for b in children]\n\n def __getite...
from abc import ABC, abstractmethod from typing import List, Mapping, Union from torch import nn from .composition import AdapterCompositionBlock, BatchSplit, Fuse, Parallel, Split, Stack from .configuration import AdapterConfig from .context import AdapterSetup, ForwardContext from .modeling import Adapter, BertFusion, ParallelAdapter import numpy as np import torch
7,849
class AdapterLayerBase(ABC): """ Base class for all adaptation methods that require per-layer modules. """ @property def layer_idx(self): return getattr(self, "_layer_idx", -1) @layer_idx.setter def layer_idx(self, layer_idx): idx = getattr(self, "_layer_idx", layer_idx) assert idx == layer_idx setattr(self, "_layer_idx", idx) def get_active_setup(self, module_dict): if getattr(self.config, "is_adaptable", False): # First check current context before falling back to defined setup context = AdapterSetup.get_context() if context is not None: adapter_setup = context.adapter_setup else: adapter_setup = self.config.adapters.active_setup else: adapter_setup = None skip_adapters = adapter_setup is None or ( self.config.adapters.skip_layers is not None and self.layer_idx in self.config.adapters.skip_layers ) if not skip_adapters and (len(set(module_dict.keys()) & adapter_setup.flatten()) > 0): return adapter_setup else: return None def _store_gating_score(self, adapter_name, gating_score): context = ForwardContext.get_context() if context.output_adapter_gating_scores: gating_cache = context.adapter_gating_scores if self.layer_idx not in gating_cache[adapter_name]: gating_cache[adapter_name][self.layer_idx] = {} gating_score = gating_score.detach().squeeze().cpu().numpy() if len(gating_score.shape) == 0: gating_score = np.expand_dims(gating_score, axis=0) cache_score = gating_cache[adapter_name][self.layer_idx].get(self.location_key, None) if cache_score is not None: gating_cache[adapter_name][self.layer_idx][self.location_key] = np.column_stack( (cache_score, gating_score) ) else: gating_cache[adapter_name][self.layer_idx][self.location_key] = gating_score def _store_fusion_attentions(self, fusion_name, attentions): context = ForwardContext.get_context() if context.output_adapter_fusion_attentions: attention_cache = context.adapter_fusion_attentions if self.layer_idx not in attention_cache[fusion_name]: attention_cache[fusion_name][self.layer_idx] = {} attention_cache[fusion_name][self.layer_idx][self.location_key] = attentions @abstractmethod def add_adapter(self, adapter_name: str, layer_idx: int): raise NotImplementedError() @abstractmethod def delete_adapter(self, adapter_name: str): raise NotImplementedError() @abstractmethod def add_fusion_layer(self, adapter_names: Union[List, str]): raise NotImplementedError() @abstractmethod def delete_fusion_layer(self, adapter_names: Union[List, str]): raise NotImplementedError() @abstractmethod
class AdapterLayerBase(ABC): """ Base class for all adaptation methods that require per-layer modules. """ @property def layer_idx(self): return getattr(self, "_layer_idx", -1) @layer_idx.setter def layer_idx(self, layer_idx): idx = getattr(self, "_layer_idx", layer_idx) assert idx == layer_idx setattr(self, "_layer_idx", idx) def get_active_setup(self, module_dict): if getattr(self.config, "is_adaptable", False): # First check current context before falling back to defined setup context = AdapterSetup.get_context() if context is not None: adapter_setup = context.adapter_setup else: adapter_setup = self.config.adapters.active_setup else: adapter_setup = None skip_adapters = adapter_setup is None or ( self.config.adapters.skip_layers is not None and self.layer_idx in self.config.adapters.skip_layers ) if not skip_adapters and (len(set(module_dict.keys()) & adapter_setup.flatten()) > 0): return adapter_setup else: return None def _store_gating_score(self, adapter_name, gating_score): context = ForwardContext.get_context() if context.output_adapter_gating_scores: gating_cache = context.adapter_gating_scores if self.layer_idx not in gating_cache[adapter_name]: gating_cache[adapter_name][self.layer_idx] = {} gating_score = gating_score.detach().squeeze().cpu().numpy() if len(gating_score.shape) == 0: gating_score = np.expand_dims(gating_score, axis=0) cache_score = gating_cache[adapter_name][self.layer_idx].get(self.location_key, None) if cache_score is not None: gating_cache[adapter_name][self.layer_idx][self.location_key] = np.column_stack( (cache_score, gating_score) ) else: gating_cache[adapter_name][self.layer_idx][self.location_key] = gating_score def _store_fusion_attentions(self, fusion_name, attentions): context = ForwardContext.get_context() if context.output_adapter_fusion_attentions: attention_cache = context.adapter_fusion_attentions if self.layer_idx not in attention_cache[fusion_name]: attention_cache[fusion_name][self.layer_idx] = {} attention_cache[fusion_name][self.layer_idx][self.location_key] = attentions @abstractmethod def add_adapter(self, adapter_name: str, layer_idx: int): raise NotImplementedError() @abstractmethod def delete_adapter(self, adapter_name: str): raise NotImplementedError() @abstractmethod def add_fusion_layer(self, adapter_names: Union[List, str]): raise NotImplementedError() @abstractmethod def delete_fusion_layer(self, adapter_names: Union[List, str]): raise NotImplementedError() @abstractmethod
def enable_adapters(self, adapter_setup: AdapterCompositionBlock, unfreeze_adapters: bool, unfreeze_fusion: bool):
0
2023-10-18 18:05:54+00:00
12k
justincui03/tesla
distill.py
[ { "identifier": "augment", "path": "utils.py", "snippet": "def augment(images, dc_aug_param, device):\n # This can be sped up in the future.\n\n if dc_aug_param != None and dc_aug_param['strategy'] != 'none':\n scale = dc_aug_param['scale']\n crop = dc_aug_param['crop']\n rota...
import os import argparse import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision.utils import wandb import copy import random import warnings from tqdm import tqdm from utils import augment, get_dataset, get_network, get_eval_pool, evaluate_synset, get_time, DiffAugment, DiffAugmentList, ParamDiffAug from reparam_module import ReparamModule from torch.utils.data import Subset from torch.utils.data import DataLoader from PIL import PngImagePlugin
8,079
args.distributed = torch.cuda.device_count() > 1 print('Hyper-parameters: \n', args.__dict__) print('Evaluation model pool: ', model_eval_pool) ''' organize the real dataset ''' indices_class = [[] for c in range(num_classes)] # Build label to index map print("---------------Build label to index map--------------") # For machines with limited RAM, it's impossible to load all ImageNet or even TinyImageNet into memory. # Even if it's possible, it will take too long to process. # Therefore we pregenerate an indices to image map and use this map to quickly random samples from ImageNet or TinyImageNet dataset. if args.dataset == 'ImageNet': indices_class = np.load('indices/imagenet_indices_class.npy', allow_pickle=True) elif args.dataset == 'Tiny': indices_class = np.load('indices/tiny_indices_class.npy', allow_pickle=True) else: for i, data in tqdm(enumerate(dst_train)): indices_class[data[1]].append(i) # for c in range(num_classes): # print('class c = %d: %d real images'%(c, len(indices_class[c]))) def get_images(c, n): # get random n images from class c idx_shuffle = np.random.permutation(indices_class[c])[:n] subset = Subset(dst_train, idx_shuffle) data_loader = DataLoader(subset, batch_size=n) # only read the first batch which has n(IPC) number of images. for data in data_loader: return data[0].to("cpu") ''' initialize the synthetic data ''' label_syn = torch.tensor([np.ones(args.ipc)*i for i in range(num_classes)], dtype=torch.long, requires_grad=False, device=args.device).view(-1) # [0,0,0, 1,1,1, ..., 9,9,9] if args.texture: image_syn = torch.randn(size=(num_classes * args.ipc, channel, im_size[0]*args.canvas_size, im_size[1]*args.canvas_size), dtype=torch.float) else: image_syn = torch.randn(size=(num_classes * args.ipc, channel, im_size[0], im_size[1]), dtype=torch.float) syn_lr = torch.tensor(args.lr_teacher).to(args.device) if args.pix_init == 'real': print('initialize synthetic data from random real images') for c in range(num_classes): image_syn.data[c * args.ipc:(c + 1) * args.ipc] = get_images(c, args.ipc).detach().data else: print('initialize synthetic data from random noise') ''' training ''' image_syn = image_syn.detach().to(args.device).requires_grad_(True) print(image_syn.shape) syn_lr = syn_lr.detach().to(args.device).requires_grad_(True) optimizer_img = torch.optim.SGD([image_syn], lr=args.lr_img, momentum=0.5) optimizer_lr = torch.optim.SGD([syn_lr], lr=args.lr_lr, momentum=0.5) optimizer_img.zero_grad() optimizer_lr.zero_grad() criterion = nn.CrossEntropyLoss().to(args.device) print('%s training begins'%get_time()) expert_dir = os.path.join(args.buffer_path, args.dataset) if args.dataset in ["CIFAR10", "CIFAR100"] and not args.zca: expert_dir += "_NO_ZCA" expert_dir = os.path.join(expert_dir, args.model) print("Expert Dir: {}".format(expert_dir)) if not args.random_trajectory: if args.load_all: buffer = [] n = 0 while os.path.exists(os.path.join(expert_dir, "replay_buffer_{}.pt".format(n))): buffer = buffer + torch.load(os.path.join(expert_dir, "replay_buffer_{}.pt".format(n))) n += 1 if n == 0: raise AssertionError("No buffers detected at {}".format(expert_dir)) else: expert_files = [] n = 0 while os.path.exists(os.path.join(expert_dir, "replay_buffer_{}.pt".format(n))): expert_files.append(os.path.join(expert_dir, "replay_buffer_{}.pt".format(n))) n += 1 if n == 0: raise AssertionError("No buffers detected at {}".format(expert_dir)) file_idx = 0 expert_idx = 0 random.shuffle(expert_files) if args.max_files is not None: expert_files = expert_files[:args.max_files] print("loading file {}".format(expert_files[file_idx])) buffer = torch.load(expert_files[file_idx]) if args.max_experts is not None: buffer = buffer[:args.max_experts] random.shuffle(buffer) best_acc = {m: 0 for m in model_eval_pool} best_std = {m: 0 for m in model_eval_pool} for it in range(0, args.Iteration+1): save_this_it = False # writer.add_scalar('Progress', it, it) wandb.log({"Progress": it}, step=it) ''' Evaluate synthetic data ''' if it in eval_it_pool and args.eval_it > 0: for model_eval in model_eval_pool: print('-------------------------\nEvaluation\nmodel_train = %s, model_eval = %s, iteration = %d'%(args.model, model_eval, it)) if args.dsa: print('DSA augmentation strategy: \n', args.dsa_strategy) print('DSA augmentation parameters: \n', args.dsa_param.__dict__) else: print('DC augmentation parameters: \n', args.dc_aug_param) accs_test = [] accs_train = [] for it_eval in range(args.num_eval):
LARGE_ENOUGH_NUMBER = 100 PngImagePlugin.MAX_TEXT_CHUNK = LARGE_ENOUGH_NUMBER * (1024**2) warnings.filterwarnings("ignore", category=DeprecationWarning) def main(args): if args.zca and args.texture: raise AssertionError("Cannot use zca and texture together") if args.texture and args.pix_init == "real": print("WARNING: Using texture with real initialization will take a very long time to smooth out the boundaries between images.") if args.max_experts is not None and args.max_files is not None: args.total_experts = args.max_experts * args.max_files print("CUDNN STATUS: {}".format(torch.backends.cudnn.enabled)) args.dsa = True if args.dsa == 'True' else False args.device = 'cuda' if torch.cuda.is_available() else 'cpu' eval_it_pool = np.arange(0, args.Iteration + 1, args.eval_it).tolist() channel, im_size, num_classes, class_names, mean, std, dst_train, dst_test, testloader, loader_train_dict, class_map, class_map_inv = get_dataset(args.dataset, args.data_path, args.batch_real, args=args) model_eval_pool = get_eval_pool(args.eval_mode, args.model, args.model) im_res = im_size[0] args.im_size = im_size accs_all_exps = dict() # record performances of all experiments for key in model_eval_pool: accs_all_exps[key] = [] data_save = [] if args.dsa: # args.epoch_eval_train = 1000 args.dc_aug_param = None args.dsa_param = ParamDiffAug() dsa_params = args.dsa_param if args.zca: zca_trans = args.zca_trans else: zca_trans = None wandb.init(sync_tensorboard=False, project="DatasetDistillation", job_type="CleanRepo", config=args, ) args = type('', (), {})() for key in wandb.config._items: setattr(args, key, wandb.config._items[key]) args.dsa_param = dsa_params args.zca_trans = zca_trans if args.batch_syn is None: args.batch_syn = num_classes * args.ipc args.distributed = torch.cuda.device_count() > 1 print('Hyper-parameters: \n', args.__dict__) print('Evaluation model pool: ', model_eval_pool) ''' organize the real dataset ''' indices_class = [[] for c in range(num_classes)] # Build label to index map print("---------------Build label to index map--------------") # For machines with limited RAM, it's impossible to load all ImageNet or even TinyImageNet into memory. # Even if it's possible, it will take too long to process. # Therefore we pregenerate an indices to image map and use this map to quickly random samples from ImageNet or TinyImageNet dataset. if args.dataset == 'ImageNet': indices_class = np.load('indices/imagenet_indices_class.npy', allow_pickle=True) elif args.dataset == 'Tiny': indices_class = np.load('indices/tiny_indices_class.npy', allow_pickle=True) else: for i, data in tqdm(enumerate(dst_train)): indices_class[data[1]].append(i) # for c in range(num_classes): # print('class c = %d: %d real images'%(c, len(indices_class[c]))) def get_images(c, n): # get random n images from class c idx_shuffle = np.random.permutation(indices_class[c])[:n] subset = Subset(dst_train, idx_shuffle) data_loader = DataLoader(subset, batch_size=n) # only read the first batch which has n(IPC) number of images. for data in data_loader: return data[0].to("cpu") ''' initialize the synthetic data ''' label_syn = torch.tensor([np.ones(args.ipc)*i for i in range(num_classes)], dtype=torch.long, requires_grad=False, device=args.device).view(-1) # [0,0,0, 1,1,1, ..., 9,9,9] if args.texture: image_syn = torch.randn(size=(num_classes * args.ipc, channel, im_size[0]*args.canvas_size, im_size[1]*args.canvas_size), dtype=torch.float) else: image_syn = torch.randn(size=(num_classes * args.ipc, channel, im_size[0], im_size[1]), dtype=torch.float) syn_lr = torch.tensor(args.lr_teacher).to(args.device) if args.pix_init == 'real': print('initialize synthetic data from random real images') for c in range(num_classes): image_syn.data[c * args.ipc:(c + 1) * args.ipc] = get_images(c, args.ipc).detach().data else: print('initialize synthetic data from random noise') ''' training ''' image_syn = image_syn.detach().to(args.device).requires_grad_(True) print(image_syn.shape) syn_lr = syn_lr.detach().to(args.device).requires_grad_(True) optimizer_img = torch.optim.SGD([image_syn], lr=args.lr_img, momentum=0.5) optimizer_lr = torch.optim.SGD([syn_lr], lr=args.lr_lr, momentum=0.5) optimizer_img.zero_grad() optimizer_lr.zero_grad() criterion = nn.CrossEntropyLoss().to(args.device) print('%s training begins'%get_time()) expert_dir = os.path.join(args.buffer_path, args.dataset) if args.dataset in ["CIFAR10", "CIFAR100"] and not args.zca: expert_dir += "_NO_ZCA" expert_dir = os.path.join(expert_dir, args.model) print("Expert Dir: {}".format(expert_dir)) if not args.random_trajectory: if args.load_all: buffer = [] n = 0 while os.path.exists(os.path.join(expert_dir, "replay_buffer_{}.pt".format(n))): buffer = buffer + torch.load(os.path.join(expert_dir, "replay_buffer_{}.pt".format(n))) n += 1 if n == 0: raise AssertionError("No buffers detected at {}".format(expert_dir)) else: expert_files = [] n = 0 while os.path.exists(os.path.join(expert_dir, "replay_buffer_{}.pt".format(n))): expert_files.append(os.path.join(expert_dir, "replay_buffer_{}.pt".format(n))) n += 1 if n == 0: raise AssertionError("No buffers detected at {}".format(expert_dir)) file_idx = 0 expert_idx = 0 random.shuffle(expert_files) if args.max_files is not None: expert_files = expert_files[:args.max_files] print("loading file {}".format(expert_files[file_idx])) buffer = torch.load(expert_files[file_idx]) if args.max_experts is not None: buffer = buffer[:args.max_experts] random.shuffle(buffer) best_acc = {m: 0 for m in model_eval_pool} best_std = {m: 0 for m in model_eval_pool} for it in range(0, args.Iteration+1): save_this_it = False # writer.add_scalar('Progress', it, it) wandb.log({"Progress": it}, step=it) ''' Evaluate synthetic data ''' if it in eval_it_pool and args.eval_it > 0: for model_eval in model_eval_pool: print('-------------------------\nEvaluation\nmodel_train = %s, model_eval = %s, iteration = %d'%(args.model, model_eval, it)) if args.dsa: print('DSA augmentation strategy: \n', args.dsa_strategy) print('DSA augmentation parameters: \n', args.dsa_param.__dict__) else: print('DC augmentation parameters: \n', args.dc_aug_param) accs_test = [] accs_train = [] for it_eval in range(args.num_eval):
net_eval = get_network(model_eval, channel, num_classes, im_size).to(args.device) # get a random model
2
2023-10-17 23:11:36+00:00
12k
upiterbarg/hihack
models/utils.py
[ { "identifier": "CDGPT5", "path": "models/cdgpt5.py", "snippet": "class CDGPT5(nn.Module):\n def __init__(self, shape, action_space, flags, device):\n super(CDGPT5, self).__init__()\n\n self.flags = flags\n self.num_actions = len(action_space)\n self.use_prev_action = flag...
import omegaconf import os import pathlib import pdb import sys import torch from .cdgpt5 import CDGPT5 from .cleaved_hierarchical_policy import CleavedHierarchicalPolicy from .flat_transformer import FlatTransformer from .hierarchical_lstm import HierarchicalLSTM from .hierarchical_transformer_lstm import HierarchicalTransformerLSTM from .transformer_lstm import TransformerLSTM from nle.env.base import DUNGEON_SHAPE from omegaconf import OmegaConf from tasks import ENVS
10,738
base_path = str(pathlib.Path().resolve()) hihack_path = os.path.join(base_path[:base_path.find('hihack')], 'hihack') sys.path.insert(0, os.path.join(hihack_path, 'dungeonsdata-neurips2022/experiment_code/hackrl')) MODELS = [ CDGPT5, HierarchicalLSTM,
base_path = str(pathlib.Path().resolve()) hihack_path = os.path.join(base_path[:base_path.find('hihack')], 'hihack') sys.path.insert(0, os.path.join(hihack_path, 'dungeonsdata-neurips2022/experiment_code/hackrl')) MODELS = [ CDGPT5, HierarchicalLSTM,
HierarchicalTransformerLSTM,
4
2023-10-23 15:44:32+00:00
12k
avilliai/Bert_Vits2_Sever
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,618
_, 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]) else: train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, None], None, None) scheduler_g.step() scheduler_d.step() if net_dur_disc is not None: scheduler_dur_disc.step() def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers): net_g, net_d, net_dur_disc = nets optim_g, optim_d, optim_dur_disc = optims scheduler_g, scheduler_d, scheduler_dur_disc = schedulers train_loader, eval_loader = loaders if writers is not None: writer, writer_eval = writers train_loader.batch_sampler.set_epoch(epoch) global global_step net_g.train() net_d.train() if net_dur_disc is not None: net_dur_disc.train() for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert) in tqdm(enumerate(train_loader)): if net_g.module.use_noise_scaled_mas: current_mas_noise_scale = net_g.module.mas_noise_scale_initial - net_g.module.noise_scale_delta * global_step net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0) x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True) spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(rank, non_blocking=True) y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True) speakers = speakers.cuda(rank, non_blocking=True) tone = tone.cuda(rank, non_blocking=True) language = language.cuda(rank, non_blocking=True) bert = bert.cuda(rank, non_blocking=True) with autocast(enabled=hps.train.fp16_run): y_hat, l_length, attn, ids_slice, x_mask, z_mask, \ (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_) = net_g(x, x_lengths, spec, spec_lengths, speakers, tone, language, bert) mel = spec_to_mel_torch( spec, hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax) y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length) y_hat_mel = mel_spectrogram_torch( y_hat.squeeze(1), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax ) y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice # Discriminator y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) with autocast(enabled=False): loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g) loss_disc_all = loss_disc if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x.detach(), x_mask.detach(), logw.detach(), logw_.detach()) with autocast(enabled=False): # TODO: I think need to mean using the mask, but for now, just mean all loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g = discriminator_loss(y_dur_hat_r, y_dur_hat_g) loss_dur_disc_all = loss_dur_disc optim_dur_disc.zero_grad() scaler.scale(loss_dur_disc_all).backward() scaler.unscale_(optim_dur_disc) grad_norm_dur_disc = commons.clip_grad_value_(net_dur_disc.parameters(), None) scaler.step(optim_dur_disc) optim_d.zero_grad() scaler.scale(loss_disc_all).backward() scaler.unscale_(optim_d) grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) scaler.step(optim_d) with autocast(enabled=hps.train.fp16_run): # Generator y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw, logw_) with autocast(enabled=False): loss_dur = torch.sum(l_length.float()) loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
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() if not hps.cont: shutil.copy('./pretrained_models/D_0.pth','./logs/OUTPUT_MODEL/D_0.pth') shutil.copy('./pretrained_models/G_0.pth','./logs/OUTPUT_MODEL/G_0.pth') shutil.copy('./pretrained_models/DUR_0.pth','./logs/OUTPUT_MODEL/DUR_0.pth') mp.spawn(run, nprocs=n_gpus, args=(n_gpus, hps,)) def run(rank, n_gpus, hps): 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]) else: train_and_evaluate(rank, epoch, hps, [net_g, net_d, net_dur_disc], [optim_g, optim_d, optim_dur_disc], [scheduler_g, scheduler_d, scheduler_dur_disc], scaler, [train_loader, None], None, None) scheduler_g.step() scheduler_d.step() if net_dur_disc is not None: scheduler_dur_disc.step() def train_and_evaluate(rank, epoch, hps, nets, optims, schedulers, scaler, loaders, logger, writers): net_g, net_d, net_dur_disc = nets optim_g, optim_d, optim_dur_disc = optims scheduler_g, scheduler_d, scheduler_dur_disc = schedulers train_loader, eval_loader = loaders if writers is not None: writer, writer_eval = writers train_loader.batch_sampler.set_epoch(epoch) global global_step net_g.train() net_d.train() if net_dur_disc is not None: net_dur_disc.train() for batch_idx, (x, x_lengths, spec, spec_lengths, y, y_lengths, speakers, tone, language, bert) in tqdm(enumerate(train_loader)): if net_g.module.use_noise_scaled_mas: current_mas_noise_scale = net_g.module.mas_noise_scale_initial - net_g.module.noise_scale_delta * global_step net_g.module.current_mas_noise_scale = max(current_mas_noise_scale, 0.0) x, x_lengths = x.cuda(rank, non_blocking=True), x_lengths.cuda(rank, non_blocking=True) spec, spec_lengths = spec.cuda(rank, non_blocking=True), spec_lengths.cuda(rank, non_blocking=True) y, y_lengths = y.cuda(rank, non_blocking=True), y_lengths.cuda(rank, non_blocking=True) speakers = speakers.cuda(rank, non_blocking=True) tone = tone.cuda(rank, non_blocking=True) language = language.cuda(rank, non_blocking=True) bert = bert.cuda(rank, non_blocking=True) with autocast(enabled=hps.train.fp16_run): y_hat, l_length, attn, ids_slice, x_mask, z_mask, \ (z, z_p, m_p, logs_p, m_q, logs_q), (hidden_x, logw, logw_) = net_g(x, x_lengths, spec, spec_lengths, speakers, tone, language, bert) mel = spec_to_mel_torch( spec, hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.mel_fmin, hps.data.mel_fmax) y_mel = commons.slice_segments(mel, ids_slice, hps.train.segment_size // hps.data.hop_length) y_hat_mel = mel_spectrogram_torch( y_hat.squeeze(1), hps.data.filter_length, hps.data.n_mel_channels, hps.data.sampling_rate, hps.data.hop_length, hps.data.win_length, hps.data.mel_fmin, hps.data.mel_fmax ) y = commons.slice_segments(y, ids_slice * hps.data.hop_length, hps.train.segment_size) # slice # Discriminator y_d_hat_r, y_d_hat_g, _, _ = net_d(y, y_hat.detach()) with autocast(enabled=False): loss_disc, losses_disc_r, losses_disc_g = discriminator_loss(y_d_hat_r, y_d_hat_g) loss_disc_all = loss_disc if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x.detach(), x_mask.detach(), logw.detach(), logw_.detach()) with autocast(enabled=False): # TODO: I think need to mean using the mask, but for now, just mean all loss_dur_disc, losses_dur_disc_r, losses_dur_disc_g = discriminator_loss(y_dur_hat_r, y_dur_hat_g) loss_dur_disc_all = loss_dur_disc optim_dur_disc.zero_grad() scaler.scale(loss_dur_disc_all).backward() scaler.unscale_(optim_dur_disc) grad_norm_dur_disc = commons.clip_grad_value_(net_dur_disc.parameters(), None) scaler.step(optim_dur_disc) optim_d.zero_grad() scaler.scale(loss_disc_all).backward() scaler.unscale_(optim_d) grad_norm_d = commons.clip_grad_value_(net_d.parameters(), None) scaler.step(optim_d) with autocast(enabled=hps.train.fp16_run): # Generator y_d_hat_r, y_d_hat_g, fmap_r, fmap_g = net_d(y, y_hat) if net_dur_disc is not None: y_dur_hat_r, y_dur_hat_g = net_dur_disc(hidden_x, x_mask, logw, logw_) with autocast(enabled=False): loss_dur = torch.sum(l_length.float()) loss_mel = F.l1_loss(y_mel, y_hat_mel) * hps.train.c_mel loss_kl = kl_loss(z_p, logs_q, m_p, logs_p, z_mask) * hps.train.c_kl
loss_fm = feature_loss(fmap_r, fmap_g)
8
2023-10-23 08:24:12+00:00
12k
t-ega/whatsapp-cloud-sdk
whatsapp_cloud_sdk/bot.py
[ { "identifier": "CustomHTTPError", "path": "whatsapp_cloud_sdk/_exceptions/http_error.py", "snippet": "class CustomHTTPError(Exception):\n \"\"\"\n Represents a custom HTTP error.\n\n This exception class is used to raise custom HTTP errors with\n specific status codes and response text.\n ...
from typing import Optional, List, Dict from unicodedata import decimal from whatsapp_cloud_sdk._exceptions.http_error import CustomHTTPError from whatsapp_cloud_sdk._base_api import _BaseApi from whatsapp_cloud_sdk._files.contact import Contact from whatsapp_cloud_sdk._utils.json_serializer import MyEncoder from whatsapp_cloud_sdk._validators.messages import ( TextMessage, ButtonMessage, ButtonContents, LinkMessage, LocationMessage, ) from whatsapp_cloud_sdk._formaters.message_formatter import MessageFormatter, LinkTypes import json import requests
7,558
return await self.__send(data=payload) async def send_audio_by_url( self, link: str, recipient_number: str, message_id: Optional[str], ): """ Send an audio file by URL to a recipient. Args: link (str): The URL of the audio file. recipient_number (str): The recipient's WhatsApp phone number. message_id (str, optional): An optional message ID if it is a reply to a message. Returns: Coroutine: A coroutine that should be awaited, The return value of the coroutine would contain The response from the WhatsApp API. """ message = LinkMessage(link=link) payload = formatter.format_link_message( to=recipient_number, link=message.link, m_type=LinkTypes.AUDIO, message_id=message_id, ) return await self.__send(data=payload) async def send_document_by_url( self, link: str, caption: Optional[str], recipient_number: str, message_id: Optional[str] = None, ): """ Send a document by URL to a recipient. Args: link (str): The URL of the document. caption (str, optional): An optional caption for the document. recipient_number (str): The recipient's WhatsApp phone number. message_id (str, optional): An optional message ID if it is a reply to a message. Returns: Coroutine: A coroutine that should be awaited, The return value of the coroutine would contain The response from the WhatsApp API. """ message = LinkMessage( link=link, caption=caption, ) payload = formatter.format_send_document_by_url( to=recipient_number, document_link=message.link, caption=message.caption, message_id=message_id, ) return await self.__send(data=payload) async def send_video_by_url( self, link: str, caption: Optional[str], recipient_number: str, message_id: Optional[str] = None, ): """ Send a video by URL to a recipient. Args: link (str): The URL of the video. caption (str, optional): An optional caption for the video. recipient_number (str): The recipient's WhatsApp phone number. message_id (str, optional): An optional message ID if it is a reply to a message. Returns: Coroutine: A coroutine that should be awaited, The return value of the coroutine would contain The response from the WhatsApp API. """ message = LinkMessage(link=link, caption=caption) payload = formatter.format_link_message( to=recipient_number, link=message.link, m_type=LinkTypes.VIDEO, caption=message.caption, message_id=message_id, ) return await self.__send(data=payload) # pylint: disable=too-many-arguments async def send_location( self, latitude: decimal, longitude: int, name: str, address: str, recipient_number: str, message_id: Optional[str] = None, ): """ Send a location to a recipient. Args: latitude (decimal): The latitude of the location. longitude (int): The longitude of the location. name (str): The name of the location. address (str): The address of the location. recipient_number (str): The recipient's WhatsApp phone number. message_id (str, optional): An optional message ID if it is a reply to a message. Returns: Coroutine: A coroutine that should be awaited, The return value of the coroutine would contain The response from the WhatsApp API. """
"""This module Represents a WhatsApp bot for communication with the WhatsApp API.""" formatter = MessageFormatter() class Bot(_BaseApi): # pylint: disable=line-too-long """ Represents a WhatsApp bot for communication with the WhatsApp API. This class inherits from the `BaseApi` class and provides methods for sending various types of messages, marking messages as read, and handling communication with the WhatsApp API. Args: cloud_api_access_token (str, optional): The Cloud API access token used for authentication. wa_phone_number_id (str, optional): The WhatsApp phone number ID. version (str, optional): The WhatsApp API version to use. Inherits attributes from the `BaseApi` class, such as `WA_URL` and `HEADERS`. Attributes: Inherits attributes from the `BaseApi` class. Methods: - `send_text(text: str, recipient_number: str, message_id: str = None, preview_url: bool = False)`: Send a text message to a recipient. - `send_text_with_buttons(text: str, buttons: list, recipient_number: str)`: Send a text message with buttons to a recipient. - `send_reply_with_reaction(message_id: str, emoji: str, recipient_number: str)`: Send a reaction to a message. - `send_image_by_url(link: str, caption: Optional[str], recipient_number: str, message_id: Optional[str])`: Send an image by URL. - `send_audio_by_url(link: str, caption: Optional[str], recipient_number: str)`: Send audio by URL. - `send_document_by_url(link: str, caption: Optional[str], recipient_number: str)`: Send a document by URL. - `send_video_by_url(link: str, caption: Optional[str], recipient_number: str, message_id: Optional[str] = None) `: Send a video by URL. - `send_location(latitude: decimal, longitude: int, name: str, address: str, recipient_number: str)`: Send a location. - `send_contact(contact: list, recipient_number: str)`: Send a contact. - `send_sticker_with_url(link: str, recipient_number: str)`: Send a sticker by URL. - `mark_message_as_read(message_id: str)`: Mark a message as read. - `__send(data: dict, method: Optional[str] = "POST") -> dict`: Send data to the WhatsApp API. Usage Example: ``` python from your_library import Bot # Initialize the bot. bot = Bot(cloud_api_access_token="your_access_token", wa_phone_number_id="your_phone_number_id", version="v17.0") # Use bot methods to interact with the WhatsApp API bot.send_text("Hello, world!", "recipient_number") ``` """ def __init__( self, cloud_api_access_token: str = None, wa_phone_number_id: str = None, version: str = None, ): """ Initialize a Bot instance for WhatsApp API communication. Args: cloud_api_access_token (str, optional): The Cloud API access token used for authentication. wa_phone_number_id (str, optional): The WhatsApp phone number ID. version (str, optional): The WhatsApp API version to use. Inherits attributes from the `BaseApi` class. """ super().__init__( cloud_api_access_token=cloud_api_access_token, wa_phone_number_id=wa_phone_number_id, version=version, ) async def send_text( self, text: str, recipient_number: str, message_id: str = None, preview_url: bool = False, ): """ Send a text message to a recipient. Args: text (str): The text of the message. recipient_number (str): The recipient's WhatsApp phone number. message_id (str, optional): The ID of the message if it is a reply to a message (optional). preview_url (bool): Enable or disable URL preview (default is False). Returns: Coroutine: A coroutine that should be awaited, The return value of the coroutine would contain The response from the WhatsApp API. """ message = TextMessage( text=text, recipient_number=recipient_number, message_id=message_id ) payload = formatter.format_text_message( to=message.recipient_number, body=message.text, message_id=message_id, preview_url=preview_url, ) return await self.__send(data=payload) async def send_text_with_buttons( self, text: str, buttons: List[Dict[str, str]], recipient_number: str, message_id: Optional[str], ): """ Send a text message with buttons to a recipient. Args: text (str): The text of the message. buttons (list): List of buttons, where each button is a dictionary with the following keys: - 'title' (str): The title or label of the button. - 'id' (optional, str): An optional id for the button. recipient_number (str): The recipient's WhatsApp phone number. message_id (str, optional): An optional message ID if it is a reply to a message. Returns: Coroutine: A coroutine that should be awaited, The return value of the coroutine would contain The response from the WhatsApp API. """ if not isinstance(buttons, list): raise TypeError("Buttons must be a list of dict object") buttons_content = [ButtonContents(**b) for b in buttons] message = ButtonMessage( text=text, recipient_number=recipient_number, buttons=buttons_content ) payload = formatter.format_button_message( to=recipient_number, text=message.text, buttons=message.buttons, message_id=message_id, ) return await self.__send(data=payload) # pylint: disable=fixme # TODO: Add input validation for all bot methods async def send_reaction_message( self, message_id: Optional[str], emoji, recipient_number: str ): """ Send a reaction message. Args: message_id (str, optional): An optional message ID if it is a reply to a message. emoji (str): The reaction emoji to send. recipient_number (str): The recipient's WhatsApp phone number. Returns: Coroutine: A coroutine that should be awaited, The return value of the coroutine would contain The response from the WhatsApp API. """ payload = formatter.format_reply_with_reaction( to=recipient_number, message_id=message_id, emoji=emoji ) return await self.__send(data=payload) async def send_image_by_url( self, link: str, caption: Optional[str], recipient_number: str, message_id: Optional[str], ): """ Send an image by URL to a recipient. Args: link (str): The URL of the image. caption (str, optional): An optional caption for the image. recipient_number (str): The recipient's WhatsApp phone number. message_id (str, optional): An optional message ID if it is a reply to a message. Returns: Coroutine: A coroutine that should be awaited, The return value of the coroutine would contain The response from the WhatsApp API. """ message = LinkMessage(link=link, caption=caption) payload = formatter.format_link_message( to=recipient_number, link=message.link, m_type=LinkTypes.IMAGE, message_id=message_id, ) return await self.__send(data=payload) async def send_audio_by_url( self, link: str, recipient_number: str, message_id: Optional[str], ): """ Send an audio file by URL to a recipient. Args: link (str): The URL of the audio file. recipient_number (str): The recipient's WhatsApp phone number. message_id (str, optional): An optional message ID if it is a reply to a message. Returns: Coroutine: A coroutine that should be awaited, The return value of the coroutine would contain The response from the WhatsApp API. """ message = LinkMessage(link=link) payload = formatter.format_link_message( to=recipient_number, link=message.link, m_type=LinkTypes.AUDIO, message_id=message_id, ) return await self.__send(data=payload) async def send_document_by_url( self, link: str, caption: Optional[str], recipient_number: str, message_id: Optional[str] = None, ): """ Send a document by URL to a recipient. Args: link (str): The URL of the document. caption (str, optional): An optional caption for the document. recipient_number (str): The recipient's WhatsApp phone number. message_id (str, optional): An optional message ID if it is a reply to a message. Returns: Coroutine: A coroutine that should be awaited, The return value of the coroutine would contain The response from the WhatsApp API. """ message = LinkMessage( link=link, caption=caption, ) payload = formatter.format_send_document_by_url( to=recipient_number, document_link=message.link, caption=message.caption, message_id=message_id, ) return await self.__send(data=payload) async def send_video_by_url( self, link: str, caption: Optional[str], recipient_number: str, message_id: Optional[str] = None, ): """ Send a video by URL to a recipient. Args: link (str): The URL of the video. caption (str, optional): An optional caption for the video. recipient_number (str): The recipient's WhatsApp phone number. message_id (str, optional): An optional message ID if it is a reply to a message. Returns: Coroutine: A coroutine that should be awaited, The return value of the coroutine would contain The response from the WhatsApp API. """ message = LinkMessage(link=link, caption=caption) payload = formatter.format_link_message( to=recipient_number, link=message.link, m_type=LinkTypes.VIDEO, caption=message.caption, message_id=message_id, ) return await self.__send(data=payload) # pylint: disable=too-many-arguments async def send_location( self, latitude: decimal, longitude: int, name: str, address: str, recipient_number: str, message_id: Optional[str] = None, ): """ Send a location to a recipient. Args: latitude (decimal): The latitude of the location. longitude (int): The longitude of the location. name (str): The name of the location. address (str): The address of the location. recipient_number (str): The recipient's WhatsApp phone number. message_id (str, optional): An optional message ID if it is a reply to a message. Returns: Coroutine: A coroutine that should be awaited, The return value of the coroutine would contain The response from the WhatsApp API. """
message = LocationMessage(longitude=longitude, name=name, address=address)
8
2023-10-15 21:12:45+00:00
12k
caglarkucuk/earthformer-satellite-to-radar
ef-sat2rad/earthformer/datasets/sevir/ORG_sevir_torch_wrap.py
[ { "identifier": "cfg", "path": "ef-sat2rad/earthformer/config.py", "snippet": "_CURR_DIR = os.path.realpath(os.path.dirname(os.path.realpath(__file__)))" }, { "identifier": "SEVIRDataLoader", "path": "ef-sat2rad/earthformer/datasets/sevir/sevir_dataloader.py", "snippet": "class SEVIRData...
import os import numpy as np import datetime import pandas as pd import torch from typing import Union, Dict, Sequence, Tuple, List from torch.utils.data import Dataset as TorchDataset, DataLoader from pytorch_lightning import LightningDataModule from ...config import cfg from .sevir_dataloader import SEVIRDataLoader
9,314
class SEVIRTorchDataset(TorchDataset): def __init__(self, seq_len: int = 25, raw_seq_len: int = 49, sample_mode: str = "sequent", stride: int = 12, batch_size: int = 1, layout: str = "NHWT", num_shard: int = 1, rank: int = 0, split_mode: str = "uneven", sevir_catalog: Union[str, pd.DataFrame] = None, sevir_data_dir: str = None, start_date: datetime.datetime = None, end_date: datetime.datetime = None, datetime_filter = None, catalog_filter = "default", shuffle: bool = False, shuffle_seed: int = 1, output_type = np.float32, preprocess: bool = True, rescale_method: str = "01", verbose: bool = False): super(SEVIRTorchDataset, self).__init__() self.layout = layout
class SEVIRTorchDataset(TorchDataset): def __init__(self, seq_len: int = 25, raw_seq_len: int = 49, sample_mode: str = "sequent", stride: int = 12, batch_size: int = 1, layout: str = "NHWT", num_shard: int = 1, rank: int = 0, split_mode: str = "uneven", sevir_catalog: Union[str, pd.DataFrame] = None, sevir_data_dir: str = None, start_date: datetime.datetime = None, end_date: datetime.datetime = None, datetime_filter = None, catalog_filter = "default", shuffle: bool = False, shuffle_seed: int = 1, output_type = np.float32, preprocess: bool = True, rescale_method: str = "01", verbose: bool = False): super(SEVIRTorchDataset, self).__init__() self.layout = layout
self.sevir_dataloader = SEVIRDataLoader(
1
2023-10-23 11:45:50+00:00
12k
DTennant/GPC
data/get_datasets.py
[ { "identifier": "MergedDataset", "path": "data/data_utils.py", "snippet": "class MergedDataset(Dataset):\n\n \"\"\"\n Takes two datasets (labelled_dataset, unlabelled_dataset) and merges them\n Allows you to iterate over them in parallel\n \"\"\"\n\n def __init__(self, labelled_dataset, u...
from data.data_utils import MergedDataset from data.cifar import get_cifar_10_datasets, get_cifar_100_datasets, get_cifar_100_ucd_datasets from data.herbarium_19 import get_herbarium_datasets from data.stanford_cars import get_scars_datasets from data.imagenet import get_imagenet_100_datasets, get_imagenet_ucd_100_datasets from data.cub import get_cub_datasets, get_cub_universal_datasets from data.fgvc_aircraft import get_aircraft_datasets from data.inat_mini import get_inat_universal_datasets from data.domainnet import get_domainnet_universal_datasets from data.color_symbol import get_color_symbol_universal_datasets from data.cifar import subsample_classes as subsample_dataset_cifar from data.herbarium_19 import subsample_classes as subsample_dataset_herb from data.stanford_cars import subsample_classes as subsample_dataset_scars from data.imagenet import subsample_classes as subsample_dataset_imagenet from data.cub import subsample_classes as subsample_dataset_cub from data.fgvc_aircraft import subsample_classes as subsample_dataset_air from copy import deepcopy from config import osr_split_dir import pickle import os
8,122
sub_sample_class_funcs = { 'cifar10': subsample_dataset_cifar, 'cifar100': subsample_dataset_cifar, 'imagenet_100': subsample_dataset_imagenet, 'herbarium_19': subsample_dataset_herb, 'cub': subsample_dataset_cub,
sub_sample_class_funcs = { 'cifar10': subsample_dataset_cifar, 'cifar100': subsample_dataset_cifar, 'imagenet_100': subsample_dataset_imagenet, 'herbarium_19': subsample_dataset_herb, 'cub': subsample_dataset_cub,
'aircraft': subsample_dataset_air,
10
2023-10-23 18:23:22+00:00
12k
nju-websoft/SCR
main.py
[ { "identifier": "reset_id", "path": "framework/utils.py", "snippet": "def reset_id(labels, new_id):\n res = []\n for index in range(len(labels)):\n res.append(new_id[int(labels[index])])\n return torch.tensor(res)" }, { "identifier": "get_reset", "path": "framework/utils.py",...
import torch import random import numpy as np import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import math import warnings from framework.utils import reset_id, get_reset, trigger_combine_event, unpack_batch from framework.optimization import BertAdam, AdamW from argparse import ArgumentParser from model.trigger_encoder import triggerEncoder from model.argument_detection import argumentDetection from model.classifier import classifier from model.entity_detection import entityDetection from framework.config import Config from framework.dataloader import * from transformers import logging from sklearn.cluster import KMeans
8,488
trig = copy.deepcopy(trig[0]) gold = copy.deepcopy(gold[0]) sentence = ''.join(sentence) + str(trig) if sentence in gold_args: print(gold_args[sentence]) print(gold) assert(0) gold_args[sentence] = gold label_num += len(gold) for step, (input_ids, input_masks, in_sent, segment_ids, sentence, trigger, ner) in enumerate(eval_data_loader): input_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_ids])).cuda() input_masks = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_masks])).cuda() segment_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in segment_ids])).cuda() with torch.no_grad(): logits = argument_detection.get_res(input_ids, segment_ids, input_masks, ner) for i in range(len(in_sent)): sent = copy.deepcopy(sentence[i]) tr = copy.deepcopy(trigger[i]) tr = sampler.index2vocab[tr] sent = ''.join(sent) + str(tr) new_logits = logits[i] seen_args = copy.deepcopy(metadata[tr]) seen_args += [0] pred_roles = [] if new_logits == None: continue for index, value in enumerate(new_logits): logi = value[seen_args] max_value, pred_role = torch.max(logi, dim = 0) start, end = ner[i][index] one_pred = (start, end, seen_args[int(pred_role)]) if seen_args[int(pred_role)] != 0: pred_roles.append(one_pred) if sent in gold_args: one_gold_args = copy.deepcopy(gold_args[sent]) pred_num += len(pred_roles) for preds in pred_roles: if preds in one_gold_args: while(preds in one_gold_args): correct_num += 1 one_gold_args.remove(preds) else: pred_num += len(pred_roles) if pred_num == 0 or label_num == 0 or correct_num == 0: return 0 pred_c = 100.0*correct_num/pred_num recall_c = 100.0*correct_num/label_num f1_c = 2*pred_c*recall_c/(pred_c+recall_c) return f1_c def select_argu_data(config, argument_detection, relation_dataset,new_id, event_mention): train_data_loader = get_ACEArgData_loader(relation_dataset, config, shuffle = False, batch_size = 1) features = [] argument_detection.eval() for step, (sentence, input_ids, input_masks, in_sent, segment_ids, args, args_offset, gold_args, ner, trigger) in enumerate(train_data_loader): input_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_ids])).cuda() input_masks = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_masks])).cuda() segment_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in segment_ids])).cuda() with torch.no_grad(): feature = argument_detection.get_feature(input_ids, segment_ids, input_masks).cpu() features.append(feature) features = np.concatenate(features) num_clusters = min(config.memory_size, len(relation_dataset)) if num_clusters == len(relation_dataset): memory = [] for i in relation_dataset: memory.append(i) return memory distances = KMeans(n_clusters = num_clusters, random_state = 0).fit_transform(features) memory = [] for k in range(num_clusters): select_index = np.argmin(distances[:, k]) ins = relation_dataset[select_index] memory.append(ins) return memory def main(): # load config parser = ArgumentParser() parser.add_argument('--config', default='./config/ace.ini') args = parser.parse_args() config = Config(args.config) # set train param config.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') batch_size_per_step = int(config.batch_size / config.gradient_accumulation_steps) triger_result_total, trigger_result_cur, argument_result_total, argument_result_cur = [], [], [], [] # six truns and get average for i in range(config.total_round): print(f"Now is round {i}") config.seed += 100 random.seed(config.seed) np.random.seed(config.seed) torch.manual_seed(config.seed) # now is trigger detection task sampler = ACETriDataloder(config, i) trigger_one_round_res = [] argument_one_round_res = [] # trigger memory space trigger_memorized_samples = {} # argument memory space argument_memorized_samples = {} # init trigger encode model
logging.set_verbosity_warning() logging.set_verbosity_error() warnings.filterwarnings('ignore') def eval_trigger(trigger_encoder, trigger_classifier, eval_data, config, new_id, save, ltlabel, id2label): eval_data_loader = get_ACETriData_loader(eval_data, config, shuffle = True) trigger_encoder.eval() trigger_classifier.eval() pred_num = 0 correct_num = 0 label_num = 0 pred_res = [] for step, (sentence_ids, input_ids, input_masks, in_sent, segment_ids, labels, ners, sentence) in enumerate(eval_data_loader): sentence_ids, input_ids, input_masks, segment_ids, labels, ners = unpack_batch(sentence_ids, input_ids, input_masks, segment_ids, labels, ners, new_id, config.device) with torch.no_grad(): feature = trigger_encoder(sentence_ids, input_ids, input_masks, segment_ids) #feature = torch.stack([x.to(device) for x in feature],dim=0) logits = trigger_classifier(feature, None, None) new_logits = logits for index, value in enumerate(in_sent): evetype = [] pred_first = True value = value == 1 gold_offset = torch.nonzero(labels[index][value]).squeeze(dim = 1) gold_label = torch.gather(labels[index][value], dim = 0, index = gold_offset) assert(len(gold_label) != 0) gold_label = [int(val) for val in gold_label] gold_offset = [int(val) for val in gold_offset] new_gold_label = [] i = 0 while i < len(gold_label): if i+1 >= len(gold_label): if config.lttest and id2label[gold_label[i]] not in ltlabel: break else: new_gold_label.append(gold_label[i]) break while gold_label[i] == gold_label[i+1] and gold_offset[i]+1 == gold_offset[i+1]: i += 1 if i+1 >= len(gold_label): break if config.lttest == False or id2label[gold_label[i]] in ltlabel: new_gold_label.append(gold_label[i]) i+=1 gold_label = new_gold_label label_num += len(gold_label) res = new_logits[index][value,:] max_value, pred_tri_each_word = torch.max(res, 1) pred_trigger = 0 offset = 0 pred_offset, pred_label = [], [] for offset, trigger in enumerate(pred_tri_each_word): if trigger!=0: if config.lttest == False or id2label[int(trigger)] in ltlabel: pred_offset.append(offset) pred_label.append(trigger) new_pred_label = [] i = 0 while i < len(pred_label): if i+1 >= len(pred_label): new_pred_label.append(pred_label[i]) break while pred_label[i] == pred_label[i+1] and pred_offset[i]+1 == pred_offset[i+1]: i += 1 if i+1 >= len(pred_label): break new_pred_label.append(pred_label[i]) i+=1 new_pred_label = [int(val) for val in new_pred_label] pred_num += len(new_pred_label) for pred_trigger in new_pred_label: if save: if id2label[pred_trigger] not in evetype: evetype.append(id2label[pred_trigger]) onesamp = {} onesamp['sentence'] = sentence[index] onesamp['trigger'] = id2label[pred_trigger] onesamp['s_start'] = 0 pred_res.append(onesamp) if pred_trigger in gold_label: correct_num += 1 gold_label.remove(pred_trigger) if pred_num == 0 or label_num == 0 or correct_num == 0: return 0 pred_c = 100.0*correct_num/pred_num recall_c = 100.0*correct_num/label_num f1_c = 2*pred_c*recall_c/(pred_c+recall_c) if save: f = open(config.trigger_pred_file, 'w') json.dump(pred_res, f) f.close() return f1_c def train_simple_trigger(trigger_encoder, trigger_classifier, tr_data, config, new_id): train_data_loader = get_ACETriData_loader(tr_data, config, shuffle = True) trigger_encoder.train() trigger_classifier.train() param_optimizer_1 = list(trigger_encoder.named_parameters()) param_optimizer_1 = [n for n in param_optimizer_1 if 'pooler' not in n[0]] param_optimizer_2 = list(trigger_classifier.named_parameters()) param_optimizer_2 = [n for n in param_optimizer_2 if 'pooler' not in n[0]] no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer_1 if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01, "betas": (0.9, 0.999), 'lr':config.trigger_encoder_learning_rate}, {'params': [p for n, p in param_optimizer_1 if any(nd in n for nd in no_decay)], 'weight_decay': 0.0, "betas": (0.9, 0.999),'lr':config.trigger_encoder_learning_rate}, {'params': [p for n, p in param_optimizer_2 if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01, "betas": (0.9, 0.999), 'lr':config.trigger_classifier_learning_rate}, {'params': [p for n, p in param_optimizer_2 if any(nd in n for nd in no_decay)], 'weight_decay': 0.0, "betas": (0.9, 0.999), 'lr':config.trigger_classifier_learning_rate} ] optimizer = AdamW(params = optimizer_grouped_parameters) epoch_index, best_f1, es_index = 0, 0, 0 fd_criterion = nn.CosineEmbeddingLoss() logits = None global_step = 0 while(True): losses = [] for step, (sentence_ids, input_ids, input_masks, in_sent, segment_ids, labels, ners, sentence) in enumerate(train_data_loader): sentence_ids, input_ids, input_masks, segment_ids, labels, ners = unpack_batch(sentence_ids, input_ids, input_masks, segment_ids, labels, ners, new_id, config.device) feature = trigger_encoder(sentence_ids, input_ids, input_masks, segment_ids) logits, loss = trigger_classifier(feature, input_masks, labels) losses.append(loss.cpu().detach().numpy()) loss.backward() if (step + 1) % config.gradient_accumulation_steps == 0: optimizer.step() optimizer.zero_grad() global_step += 1 print(f"epoch: {epoch_index}, loss is {np.array(losses).mean()}") epoch_index += 1 if epoch_index >= 5: break def train_trigger(trigger_encoder, trigger_classifier, tr_data, de_data, seen_train_event, config, new_id, forward_encoder, forward_classifier, forward_event, trigger_tailed, ltlabel, id2label): if config.kd == True and forward_event != None: forward_index = reset_id(forward_event, new_id).cuda() print(forward_index) T = config.temp train_data_loader = get_ACETriData_loader(tr_data, config, shuffle = True) trigger_encoder.train() trigger_classifier.train() param_optimizer_1 = list(trigger_encoder.named_parameters()) param_optimizer_1 = [n for n in param_optimizer_1 if 'pooler' not in n[0]] param_optimizer_2 = list(trigger_classifier.named_parameters()) param_optimizer_2 = [n for n in param_optimizer_2 if 'pooler' not in n[0]] no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer_1 if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01, "betas": (0.9, 0.999), 'lr':config.trigger_encoder_learning_rate}, {'params': [p for n, p in param_optimizer_1 if any(nd in n for nd in no_decay)], 'weight_decay': 0.0, "betas": (0.9, 0.999),'lr':config.trigger_encoder_learning_rate}, {'params': [p for n, p in param_optimizer_2 if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01, "betas": (0.9, 0.999), 'lr':config.trigger_classifier_learning_rate}, {'params': [p for n, p in param_optimizer_2 if any(nd in n for nd in no_decay)], 'weight_decay': 0.0, "betas": (0.9, 0.999), 'lr':config.trigger_classifier_learning_rate} ] if config.merit == 'epochs': num_train_optimization_steps = len(train_data_loader) // config.gradient_accumulation_steps * config.epochs optimizer = AdamW(params = optimizer_grouped_parameters, weight_decay=config.weight_decay) elif config.merit == 'early_stop': optimizer = AdamW(params = optimizer_grouped_parameters) epoch_index, best_f1, es_index = 0, 0, 0 #fd_criterion = nn.CosineEmbeddingLoss(reduction = 'sum') fd_criterion = nn.CosineEmbeddingLoss() logits = None global_step = 0 while(True): losses = [] for step, (sentence_ids, input_ids, input_masks, in_sent, segment_ids, labels, ners, sentence) in enumerate(train_data_loader): sentence_ids, input_ids, input_masks, segment_ids, labels, ners = unpack_batch(sentence_ids, input_ids, input_masks, segment_ids, labels, ners, new_id, config.device) feature = trigger_encoder(sentence_ids, input_ids, input_masks, segment_ids) if len(trigger_tailed) != 0: tail_res = [] for i, label in enumerate(labels): flabels = label!=0 pos_labels = label[flabels] pos_index = torch.nonzero(label) for index, fe in enumerate(pos_labels): if int(fe) in trigger_tailed: protos, standard = trigger_tailed[int(fe)] protos = protos[flabels] standard = standard[flabels] for st in range(len(standard)): s = torch.tensor(np.random.normal(0, standard[st], 1)).cuda() j = pos_index[index] feature[i][j] += s tail_res.append((i,j,s)) logits, loss = trigger_classifier(feature, input_masks, labels) if config.kd == True and forward_event != None: #print(tail_res) kd_loss = 0 temp_masks = copy.deepcopy(input_masks) forward_features = forward_encoder(sentence_ids, input_ids, temp_masks, segment_ids) if len(trigger_tailed) != 0: for i,j,s in tail_res: forward_features[i][j] += s forward_logits = forward_classifier(forward_features, temp_masks, None) forward_logits = (forward_logits.index_select(2, forward_index)/T).view(-1, len(forward_event)) new_logits = (logits.index_select(2, forward_index)/T).view(-1, len(forward_event)) active_loss = (input_masks.view(-1) == 1).cuda() forward_logits = forward_logits[active_loss] new_logits = new_logits[active_loss] if config.select == True: max_forward_index = max(forward_index) label_index = (labels.view(-1)<=max_forward_index)[active_loss].cuda() forward_logits[:,0] = 0 new_logits[:,0] = 0 forward_logits = forward_logits[label_index] new_logits = new_logits[label_index] forward_logits = F.softmax(forward_logits, dim = 1) new_logits = F.log_softmax(new_logits, dim = 1) kd_loss = -torch.mean(torch.sum(forward_logits * new_logits, dim = 1)) #kd_loss = -torch.sum(torch.sum(forward_logits * new_logits, dim = 1)) if config.attention == True: attention = trigger_encoder.get_attention(input_ids, input_masks, segment_ids) forward_attention = forward_encoder.get_attention(input_ids, input_masks, segment_ids) attention = attention.matmul(feature) forward_attention = forward_attention.matmul(forward_features) attention = F.normalize(attention, p=2, dim=2).view(-1, attention.shape[2])[active_loss] forward_attention = F.normalize(forward_attention, p=2, dim=2).view(-1, forward_attention.shape[2])[active_loss] fd_loss = fd_criterion(attention, forward_attention, torch.ones(attention.shape[0]).cuda()) kd_loss = kd_loss + fd_loss loss = (1-config.alpha)*loss+config.alpha*kd_loss losses.append(loss.cpu().detach().numpy()) loss.backward() if (step + 1) % config.gradient_accumulation_steps == 0: optimizer.step() optimizer.zero_grad() global_step += 1 if config.merit == 'early_stop': res = 0 res = eval_trigger(trigger_encoder, trigger_classifier, de_data, config, new_id, False, ltlabel, id2label) trigger_encoder.train() trigger_classifier.train() if res > best_f1: best_f1 = res es_index = 0 encoder_output_path = config.output_dir+ config.trigger_encoder_file torch.save(trigger_encoder.state_dict(), encoder_output_path) classifier_output_path = config.output_dir+ config.trigger_classifier_file torch.save(trigger_classifier.state_dict(), classifier_output_path) else: es_index += 1 print(f"epoch: {epoch_index}, loss is {np.array(losses).mean()}, f1 is {res} and best f1 is {best_f1}") epoch_index += 1 if es_index >= config.early_stop: trigger_encoder.load_state_dict(torch.load(encoder_output_path)) trigger_classifier.load_state_dict(torch.load(classifier_output_path)) break if config.merit == 'epochs': print(f"epoch: {epoch_index}, loss is {np.array(losses).mean()}") epoch_index += 1 if epoch_index >= config.epochs: break def select_data(config, trigger_encoder, relation_dataset, new_id, event): train_data_loader = get_ACETriData_loader(relation_dataset, config, shuffle = False, batch_size = 1) features = [] trigger_encoder.eval() for step, (sentence_ids, input_ids, input_masks, in_sent, segment_ids, labels, ners, sentence) in enumerate(train_data_loader): sentence_ids, input_ids, input_masks, segment_ids, labels, ners = unpack_batch(sentence_ids, input_ids, input_masks, segment_ids, labels, ners, new_id, config.device) with torch.no_grad(): feature = trigger_encoder.get_feature(sentence_ids, input_ids, input_masks, segment_ids).cpu() features.append(feature) features = np.concatenate(features) num_clusters = min(config.memory_size, len(relation_dataset)) if num_clusters == len(relation_dataset): memory = [] for i in relation_dataset: memory.append(i) return memory distances = KMeans(n_clusters = num_clusters, random_state = 0).fit_transform(features) memory = [] for k in range(num_clusters): select_index = np.argmin(distances[:, k]) ins = relation_dataset[select_index] memory.append(ins) return memory def addPseudoLabel(trigger_encoder, trigger_classifier, data, config, id2label): pseudo_data = [] eval_data_loader = get_ACETriData_loader(data, config, shuffle = True, batch_size = 1) trigger_encoder.eval() trigger_classifier.eval() for step, (sentence_ids, input_ids, input_masks, in_sent, segment_ids, labels, ners, sentence) in enumerate(eval_data_loader): sentence_ids, input_ids, input_masks, segment_ids, labels, ners = unpack_batch(sentence_ids, input_ids, input_masks, segment_ids, labels, ners, None, config.device) with torch.no_grad(): feature = trigger_encoder(sentence_ids, input_ids, input_masks, segment_ids) logits = trigger_classifier(feature, None, None) new_logits = logits for index, value in enumerate(in_sent): pred_first = True value = value == 1 gold_offset = torch.nonzero(labels[index][value]).squeeze(dim = 1) gold_label = torch.gather(labels[index][value], dim = 0, index = gold_offset) gold_label = [int(val) for val in gold_label] gold_offset = [int(val) for val in gold_offset] res = new_logits[index][value,:] max_value, pred_tri_each_word = torch.max(res, 1) pred_trigger = 0 for offset, trigger in enumerate(pred_tri_each_word): if trigger!=0 and max_value[offset] > 0.8 and offset not in gold_offset: one_sample = {} one_sample['sentence_ids'] = sentence_ids[0].tolist() one_sample['input_ids'] = input_ids[0].tolist() one_sample['input_masks'] = input_masks[0].tolist() pseudo_label = torch.zeros(len(input_ids[0])) pseudo_label[offset] = id2label[int(trigger)] one_sample['labels'] = pseudo_label.tolist() one_sample['in_sent'] = in_sent[0].tolist() one_sample['segment_ids'] = segment_ids[0].tolist() one_sample['ners'] = ners[0].tolist() one_sample['sentence'] = sentence[0] pseudo_data.append(one_sample) return pseudo_data + data def get_trigger_proto(config, trigger_encoder, relation_dataset, new_id, event): train_data_loader = get_ACETriData_loader(relation_dataset, config, shuffle = False, batch_size = 1) features = [] trigger_encoder.eval() for step, (sentence_ids, input_ids, input_masks, in_sent, segment_ids, labels, ners, sentence) in enumerate(train_data_loader): sentence_ids, input_ids, input_masks, segment_ids, labels, ners = unpack_batch(sentence_ids, input_ids, input_masks, segment_ids, labels, ners, new_id, config.device) with torch.no_grad(): feature = trigger_encoder(sentence_ids, input_ids, input_masks, segment_ids) feature = feature[labels == event] features.append(feature) features = torch.cat(features, dim = 0) proto = torch.mean(features, dim = 0, keepdim = True).cpu() standard = torch.sqrt(torch.var(features, dim=0)).cpu() return proto, standard def kt_long_tailed(trigger_protos, trigger_num): len_tail = int(0.8*len(trigger_num)) res = {} for i in range(len_tail): tail_event = trigger_num[i][0] tail_proto, tail_standard = trigger_protos[tail_event] tail_proto = tail_proto.squeeze(0) tail_standard = tail_standard.squeeze(0) tail_cos, all_proto, all_standard = [], [], [] for event, (proto, standard) in trigger_protos.items(): proto = proto.squeeze(0) standard = standard.squeeze(0) if event != tail_event: tail_cos.append(F.cosine_similarity(tail_proto, proto, dim = 0)) all_proto.append(proto) all_standard.append(standard) all_proto = torch.stack(all_proto) all_standard = torch.stack(all_standard) tail_cos = torch.stack(tail_cos) tail_cos = F.softmax(tail_cos, dim=0) res_standard = torch.matmul(tail_cos, all_standard) res_proto = torch.matmul(tail_cos, all_proto) res[tail_event] = (res_proto, res_standard) return res def eval_entity_detection(entity_detection, eval_data, config, new_id): eval_data_loader = get_ACETriData_loader(eval_data, config, shuffle = True) entity_detection.eval() pred_num = 0 correct_num = 0 label_num = 0 pred_res = [] for step, (sentence_ids, input_ids, input_masks, in_sent, segment_ids, labels, ners, sentence) in enumerate(eval_data_loader): sentence_ids, input_ids, input_masks, segment_ids, labels, ners = unpack_batch(sentence_ids, input_ids, input_masks, segment_ids, labels, ners, new_id, config.device) with torch.no_grad(): logits = entity_detection.get_res(input_ids, segment_ids, input_masks) new_logits = logits for index, value in enumerate(in_sent): value = value == 1 pred_logits = torch.tensor(new_logits[index])[1:-1].tolist() gold_offset = [] start, end, now = 0,0,0 for offset, wo in enumerate(ners[index][value]): wo = int(wo) if wo !=0 and now == 0: now = wo start = offset end = offset+1 elif wo !=0 and now !=0 and wo == now: end = offset+1 elif wo !=0 and now !=0 and wo != now: now = wo gold_offset.append((start, end)) start = offset end = offset+1 elif wo == 0 and now == 0: start, end = 0, 0 elif wo == 0 and now != 0: now = 0 gold_offset.append((start, end)) if now != 0: gold_offset.append((start, end)) for i in gold_offset: start, end = i for j in range(start, end-1): if ners[index][value][j] != ners[index][value][j+1]: print(ners[index][value]) print(gold_offset) assert(0) label_num+=len(gold_offset) pred_offset = [] start, end, now = 0,0,0 pred_tri_each_word = pred_logits for offset, wo in enumerate(pred_tri_each_word): wo = int(wo) if wo !=0 and now == 0: now = wo start = offset end = offset+1 elif wo !=0 and now !=0 and wo == now: end = offset+1 elif wo !=0 and now !=0 and wo != now: now = wo pred_offset.append((start, end)) start = offset end = offset+1 elif wo == 0 and now == 0: start, end = 0, 0 elif wo == 0 and now != 0: now = 0 pred_offset.append((start, end)) if now != 0: pred_offset.append((start, end)) pred_num += len(pred_offset) for pred in pred_offset: if pred in gold_offset: correct_num += 1 if pred_num == 0 or label_num == 0 or correct_num == 0: return 0 pred_c = 100.0*correct_num/pred_num recall_c = 100.0*correct_num/label_num f1_c = 2*pred_c*recall_c/(pred_c+recall_c) return f1_c def pred_entity_detection(config, entity_detection, sampler): eval_data = sampler.read_pred_sample(config.trigger_pred_file) eval_data_loader = get_ACEPredData_loader(eval_data, config, shuffle = True) entity_detection.eval() pred_num = 0 correct_num = 0 label_num = 0 pred_res = [] for step, (input_ids, input_masks, in_sent, segment_ids, sentence, event) in enumerate(eval_data_loader): input_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_ids])).cuda() input_masks = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_masks])).cuda() segment_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in segment_ids])).cuda() with torch.no_grad(): logits = entity_detection.get_res(input_ids, segment_ids, input_masks) new_logits = logits for index, value in enumerate(in_sent): value = value == 1 pred_logits = torch.tensor(new_logits[index])[1:-1].tolist() pred_offset = [] start, end, now = 0,0,0 pred_tri_each_word = pred_logits for offset, wo in enumerate(pred_tri_each_word): wo = int(wo) if wo !=0 and now == 0: now = wo start = offset end = offset+1 elif wo !=0 and now !=0 and wo == now: end = offset+1 elif wo !=0 and now !=0 and wo != now: now = wo pred_offset.append((start, end)) start = offset end = offset+1 elif wo == 0 and now == 0: start, end = 0, 0 elif wo == 0 and now != 0: now = 0 pred_offset.append((start, end)) if now != 0: pred_offset.append((start, end)) onesamp = {} onesamp['sentence'] = sentence[index] onesamp['trigger'] = event[index] onesamp['s_start'] = 0 onesamp['ner'] = pred_offset pred_res.append(onesamp) f = open(config.entity_pred_file, 'w') json.dump(pred_res, f) f.close() print('Entity predict over') def train_entity_detection(entity_detection, tr_data, de_data, config, new_id): train_data_loader = get_ACETriData_loader(tr_data, config, shuffle = True) entity_detection.train() param_optimizer_1 = list(entity_detection.named_parameters()) param_optimizer_1 = [n for n in param_optimizer_1 if 'pooler' not in n[0]] no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer_1 if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01, "betas": (0.9, 0.999), 'lr':config.entity_detection_leraning_rate}, {'params': [p for n, p in param_optimizer_1 if any(nd in n for nd in no_decay)], 'weight_decay': 0.0, "betas": (0.9, 0.999),'lr':config.entity_detection_leraning_rate} ] optimizer = AdamW(params = optimizer_grouped_parameters) epoch_index, best_f1, es_index = 0, 0, 0 fd_criterion = nn.CosineEmbeddingLoss() logits = None global_step = 0 while(True): losses = [] for step, (sentence_ids, input_ids, input_masks, in_sent, segment_ids, labels, ners, sentence) in enumerate(train_data_loader): sentence_ids, input_ids, input_masks, segment_ids, labels, ners = unpack_batch(sentence_ids, input_ids, input_masks, segment_ids, labels, ners, new_id, config.device) loss = entity_detection(input_ids, ners, segment_ids, input_masks) losses.append(loss.cpu().detach().numpy()) loss.backward() if (step + 1) % config.gradient_accumulation_steps == 0: optimizer.step() optimizer.zero_grad() global_step += 1 res = 0 res = eval_entity_detection(entity_detection, de_data, config, new_id) entity_detection.train() if res > best_f1: best_f1 = res es_index = 0 encoder_output_path = config.output_dir+ config.entity_file torch.save(entity_detection.state_dict(), encoder_output_path) else: es_index += 1 print(f"epoch: {epoch_index}, loss is {np.array(losses).mean()}, f1 is {res} and best f1 is {best_f1}") epoch_index += 1 if es_index >= config.early_stop: entity_detection.load_state_dict(torch.load(encoder_output_path)) break def train_argument_detection(argument_detection, tr_data, de_data, config, metadata, unseen_metadata): train_data_loader = get_ACEArgData_loader(tr_data, config, shuffle = True) argument_detection.train() param_optimizer_1 = list(argument_detection.named_parameters()) param_optimizer_1 = [n for n in param_optimizer_1 if 'pooler' not in n[0]] no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer_1 if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01, "betas": (0.9, 0.999), 'lr':config.argument_detection_leraning_rate}, {'params': [p for n, p in param_optimizer_1 if any(nd in n for nd in no_decay)], 'weight_decay': 0.0, "betas": (0.9, 0.999),'lr':config.argument_detection_leraning_rate} ] optimizer = AdamW(params = optimizer_grouped_parameters) epoch_index, best_f1, es_index = 0, 0, 0 fd_criterion = nn.CosineEmbeddingLoss() logits = None global_step = 0 while(True): losses = [] for step, (sentence, input_ids, input_masks, in_sent, segment_ids, args, args_offset, gold_args, ner, trigger) in enumerate(train_data_loader): input_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_ids])).cuda() input_masks = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_masks])).cuda() segment_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in segment_ids])).cuda() args = torch.tensor(np.array([item.cpu().detach().numpy() for item in args])).cuda() loss = argument_detection(input_ids, args, segment_ids, input_masks, args_offset, metadata, unseen_metadata, trigger, ner, gold_args) losses.append(loss.cpu().detach().numpy()) loss.backward() if (step + 1) % config.gradient_accumulation_steps == 0: optimizer.step() optimizer.zero_grad() global_step += 1 res = 0 res = eval_argument_detection(argument_detection, de_data, config, metadata) argument_detection.train() if res > best_f1: best_f1 = res es_index = 0 encoder_output_path = config.output_dir+ config.argument_file torch.save(argument_detection.state_dict(), encoder_output_path) else: es_index += 1 print(f"epoch: {epoch_index}, loss is {np.array(losses).mean()}, f1 is {res} and best f1 is {best_f1}") epoch_index += 1 if es_index >= config.early_stop: argument_detection.load_state_dict(torch.load(encoder_output_path)) break def eval_argument_detection(argument_detection, eval_data, config, metadata): eval_data_loader = get_ACEArgData_loader(eval_data, config, shuffle = True) argument_detection.eval() pred_num = 0 correct_num = 0 label_num = 0 pred_res = [] for step, (sentence, input_ids, input_masks, in_sent, segment_ids, args, args_offset, gold_args, ner, trigger) in enumerate(eval_data_loader): input_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_ids])).cuda() input_masks = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_masks])).cuda() segment_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in segment_ids])).cuda() with torch.no_grad(): logits = argument_detection.get_res(input_ids, segment_ids, input_masks, ner) for i in range(len(in_sent)): new_logits = logits[i] seen_args = copy.deepcopy(metadata[trigger[i]]) seen_args += [0] pred_roles = [] if new_logits == None: continue for index, value in enumerate(new_logits): logi = value[seen_args] max_value, pred_role = torch.max(logi, dim = 0) start, end = ner[i][index] one_pred = (start, end, seen_args[int(pred_role)]) if seen_args[int(pred_role)] != 0: pred_roles.append(one_pred) one_gold_args = copy.deepcopy(gold_args[i]) pred_num += len(pred_roles) label_num += len(one_gold_args) for preds in pred_roles: if preds in one_gold_args: correct_num += 1 one_gold_args.remove(preds) if pred_num == 0 or label_num == 0 or correct_num == 0: return 0 pred_c = 100.0*correct_num/pred_num recall_c = 100.0*correct_num/label_num f1_c = 2*pred_c*recall_c/(pred_c+recall_c) return f1_c def pred_argument_detection(config, argument_detection, sampler, metadata, gold_data): eval_data = sampler.read_pred_ner_sample(config.entity_pred_file) eval_data_loader = get_ACEPredNerData_loader(eval_data, config, shuffle = True) argument_detection.eval() pred_num = 0 correct_num = 0 label_num = 0 pred_res = [] gold_args = {} gold_data_loader = get_ACEArgData_loader(gold_data, config, shuffle = True, batch_size = 1) for step, (sentence, _, _, _, _, args, args_offset, gold, _, trig) in enumerate(gold_data_loader): sentence = copy.deepcopy(sentence[0]) trig = copy.deepcopy(trig[0]) gold = copy.deepcopy(gold[0]) sentence = ''.join(sentence) + str(trig) if sentence in gold_args: print(gold_args[sentence]) print(gold) assert(0) gold_args[sentence] = gold label_num += len(gold) for step, (input_ids, input_masks, in_sent, segment_ids, sentence, trigger, ner) in enumerate(eval_data_loader): input_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_ids])).cuda() input_masks = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_masks])).cuda() segment_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in segment_ids])).cuda() with torch.no_grad(): logits = argument_detection.get_res(input_ids, segment_ids, input_masks, ner) for i in range(len(in_sent)): sent = copy.deepcopy(sentence[i]) tr = copy.deepcopy(trigger[i]) tr = sampler.index2vocab[tr] sent = ''.join(sent) + str(tr) new_logits = logits[i] seen_args = copy.deepcopy(metadata[tr]) seen_args += [0] pred_roles = [] if new_logits == None: continue for index, value in enumerate(new_logits): logi = value[seen_args] max_value, pred_role = torch.max(logi, dim = 0) start, end = ner[i][index] one_pred = (start, end, seen_args[int(pred_role)]) if seen_args[int(pred_role)] != 0: pred_roles.append(one_pred) if sent in gold_args: one_gold_args = copy.deepcopy(gold_args[sent]) pred_num += len(pred_roles) for preds in pred_roles: if preds in one_gold_args: while(preds in one_gold_args): correct_num += 1 one_gold_args.remove(preds) else: pred_num += len(pred_roles) if pred_num == 0 or label_num == 0 or correct_num == 0: return 0 pred_c = 100.0*correct_num/pred_num recall_c = 100.0*correct_num/label_num f1_c = 2*pred_c*recall_c/(pred_c+recall_c) return f1_c def select_argu_data(config, argument_detection, relation_dataset,new_id, event_mention): train_data_loader = get_ACEArgData_loader(relation_dataset, config, shuffle = False, batch_size = 1) features = [] argument_detection.eval() for step, (sentence, input_ids, input_masks, in_sent, segment_ids, args, args_offset, gold_args, ner, trigger) in enumerate(train_data_loader): input_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_ids])).cuda() input_masks = torch.tensor(np.array([item.cpu().detach().numpy() for item in input_masks])).cuda() segment_ids = torch.tensor(np.array([item.cpu().detach().numpy() for item in segment_ids])).cuda() with torch.no_grad(): feature = argument_detection.get_feature(input_ids, segment_ids, input_masks).cpu() features.append(feature) features = np.concatenate(features) num_clusters = min(config.memory_size, len(relation_dataset)) if num_clusters == len(relation_dataset): memory = [] for i in relation_dataset: memory.append(i) return memory distances = KMeans(n_clusters = num_clusters, random_state = 0).fit_transform(features) memory = [] for k in range(num_clusters): select_index = np.argmin(distances[:, k]) ins = relation_dataset[select_index] memory.append(ins) return memory def main(): # load config parser = ArgumentParser() parser.add_argument('--config', default='./config/ace.ini') args = parser.parse_args() config = Config(args.config) # set train param config.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') batch_size_per_step = int(config.batch_size / config.gradient_accumulation_steps) triger_result_total, trigger_result_cur, argument_result_total, argument_result_cur = [], [], [], [] # six truns and get average for i in range(config.total_round): print(f"Now is round {i}") config.seed += 100 random.seed(config.seed) np.random.seed(config.seed) torch.manual_seed(config.seed) # now is trigger detection task sampler = ACETriDataloder(config, i) trigger_one_round_res = [] argument_one_round_res = [] # trigger memory space trigger_memorized_samples = {} # argument memory space argument_memorized_samples = {} # init trigger encode model
entity_detection = entityDetection(config).to(config.device)
9
2023-10-17 02:40:04+00:00
12k
IBM/VillanDiffusion
operate.py
[ { "identifier": "fid", "path": "fid_score.py", "snippet": "def fid(path: List[str], batch_size: int=50, dims: int=2048, device: str=None, num_workers: int=None):\n if device is None:\n device = torch.device('cuda' if (torch.cuda.is_available()) else 'cpu')\n else:\n device = torch.de...
from functools import partial from typing import List, Set, Tuple, Union from diffusers import DiffusionPipeline, StableDiffusionPipeline, AutoencoderKL, UNet2DConditionModel, DPMSolverMultistepScheduler from torchmetrics import StructuralSimilarityIndexMeasure from torch import nn from PIL import Image from tqdm import tqdm from accelerate import Accelerator from fid_score import fid from dataset import CaptionBackdoor, Backdoor, DatasetLoader, ImagePathDataset, ReplicateDataset from config import SamplingStatic, MeasuringStatic, PromptDatasetStatic, DEFAULT_PROMPTS_POKEMON, DEFAULT_PROMPTS_CELEBA, ModelSchedStatic from tools import batchify, batchify_generator, randn_images, encode_latents, save_grid, match_count from tools import Log import glob import json import os import random import pickle import gc import torch import numpy as np
7,396
""" Some commly used operations """ # import argparse # from math import ceil, sqrt # from dataclasses import dataclass, field # from transformers import AutoTokenizer, PretrainedConfig class Sampling: def __init__(self, backdoor_ds_root: str="datasets", num_inference_steps: int=SamplingStatic.NUM_INFERENCE_STEPS, guidance_scale: float=SamplingStatic.GUIDANCE_SCALE, max_batch_n: int=SamplingStatic.MAX_BATCH_N): # self.__image_trigger_type: str = image_trigger # self.__caption_trigger_type: str = caption_trigger self.__num_inference_steps: int = num_inference_steps self.__guidance_scale: float = guidance_scale self.__max_batch_n: int = max_batch_n self.__image_backdoor: Backdoor = Backdoor(root=backdoor_ds_root) # self.__caption_backdoor: CaptionBackdoor = CaptionBackdoor() @property def image_backdoor(self): return self.__image_backdoor @staticmethod def get_folder(sched_name: str=None, num_inference_steps: int=None, img_num: int=None, image_trigger: str=None, caption_trigger: str=None): if caption_trigger is not None: out_img_dir: str = "caption_backdoor_samples" elif image_trigger is not None: out_img_dir: str = "image_backdoor_samples" else: out_img_dir: str = "clean_samples" if sched_name is not None: out_img_dir += f"_{str(sched_name)}" if num_inference_steps is not None: out_img_dir += f"_step{str(num_inference_steps)}" if img_num is not None: out_img_dir += f"_n{str(img_num)}" return out_img_dir @staticmethod def _batch_sampling(prompts: List[str], pipeline: DiffusionPipeline, inits: torch.Tensor=None, num_inference_steps: int=SamplingStatic.NUM_INFERENCE_STEPS, guidance_scale: float=SamplingStatic.GUIDANCE_SCALE, max_batch_n: int=SamplingStatic.MAX_BATCH_N, seed: int=SamplingStatic.SEED, handle_batch_fn: callable=SamplingStatic.HANDLE_BATCH_FN, return_imgs: bool=False): with torch.no_grad(): tensor_dtype: torch.dtype = torch.FloatTensor for i, param in enumerate(pipeline.unet.parameters()): tensor_dtype: torch.dtype = param.type() if i > 0: break device: str = pipeline.device pipeline_call = partial(pipeline, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=torch.manual_seed(seed), output_type=None) prompt_batchs = batchify(xs=prompts, max_batch_n=max_batch_n) if inits is not None: if len(prompts) != len(inits): raise ValueError() init_batchs = torch.split(inits.type(tensor_dtype), max_batch_n) else: init_batchs = [None] * len(prompt_batchs) # print(f"Prompt Batchs: {prompt_batchs}") # print(f"Init Batchs: {len(init_batchs)}") all_imgs = [] cnt: int = 0 # print(f"prompt_batch: {len(prompt_batchs)}, init_batch: {len(init_batchs)}") for prompt_batch, init_batch in zip(prompt_batchs, init_batchs): # print(f"prompt_batch: {prompt_batch}") print(f"prompt_batch Size: {len(prompt_batch)}, init_batchs: {init_batch}") if init_batch is not None: init_batch = init_batch.to(device=device) batch_imgs = pipeline_call(prompt=prompt_batch, latents=init_batch).images handle_batch_fn(cnt, batch_imgs, prompt_batch, init_batch) cnt += len(batch_imgs) if return_imgs: all_imgs += [batch_imgs] del prompt_batch del batch_imgs if init_batch is not None: del init_batch torch.cuda.empty_cache() gc.collect() del pipeline torch.cuda.empty_cache() gc.collect() if return_imgs: return np.concatenate(all_imgs) else: return None @staticmethod def _sample(prompts: List[str], pipe: DiffusionPipeline, inits: torch.Tensor=None, num_inference_steps: int=SamplingStatic.NUM_INFERENCE_STEPS, guidance_scale: float=SamplingStatic.GUIDANCE_SCALE, max_batch_n: int=SamplingStatic.MAX_BATCH_N, seed: int=SamplingStatic.SEED, handle_fn: callable=SamplingStatic.HANDLE_FN, handle_batch_fn: callable=SamplingStatic.HANDLE_BATCH_FN, return_imgs: bool=False): if len(prompts) < SamplingStatic.SHOW_PROMPT_N:
""" Some commly used operations """ # import argparse # from math import ceil, sqrt # from dataclasses import dataclass, field # from transformers import AutoTokenizer, PretrainedConfig class Sampling: def __init__(self, backdoor_ds_root: str="datasets", num_inference_steps: int=SamplingStatic.NUM_INFERENCE_STEPS, guidance_scale: float=SamplingStatic.GUIDANCE_SCALE, max_batch_n: int=SamplingStatic.MAX_BATCH_N): # self.__image_trigger_type: str = image_trigger # self.__caption_trigger_type: str = caption_trigger self.__num_inference_steps: int = num_inference_steps self.__guidance_scale: float = guidance_scale self.__max_batch_n: int = max_batch_n self.__image_backdoor: Backdoor = Backdoor(root=backdoor_ds_root) # self.__caption_backdoor: CaptionBackdoor = CaptionBackdoor() @property def image_backdoor(self): return self.__image_backdoor @staticmethod def get_folder(sched_name: str=None, num_inference_steps: int=None, img_num: int=None, image_trigger: str=None, caption_trigger: str=None): if caption_trigger is not None: out_img_dir: str = "caption_backdoor_samples" elif image_trigger is not None: out_img_dir: str = "image_backdoor_samples" else: out_img_dir: str = "clean_samples" if sched_name is not None: out_img_dir += f"_{str(sched_name)}" if num_inference_steps is not None: out_img_dir += f"_step{str(num_inference_steps)}" if img_num is not None: out_img_dir += f"_n{str(img_num)}" return out_img_dir @staticmethod def _batch_sampling(prompts: List[str], pipeline: DiffusionPipeline, inits: torch.Tensor=None, num_inference_steps: int=SamplingStatic.NUM_INFERENCE_STEPS, guidance_scale: float=SamplingStatic.GUIDANCE_SCALE, max_batch_n: int=SamplingStatic.MAX_BATCH_N, seed: int=SamplingStatic.SEED, handle_batch_fn: callable=SamplingStatic.HANDLE_BATCH_FN, return_imgs: bool=False): with torch.no_grad(): tensor_dtype: torch.dtype = torch.FloatTensor for i, param in enumerate(pipeline.unet.parameters()): tensor_dtype: torch.dtype = param.type() if i > 0: break device: str = pipeline.device pipeline_call = partial(pipeline, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, generator=torch.manual_seed(seed), output_type=None) prompt_batchs = batchify(xs=prompts, max_batch_n=max_batch_n) if inits is not None: if len(prompts) != len(inits): raise ValueError() init_batchs = torch.split(inits.type(tensor_dtype), max_batch_n) else: init_batchs = [None] * len(prompt_batchs) # print(f"Prompt Batchs: {prompt_batchs}") # print(f"Init Batchs: {len(init_batchs)}") all_imgs = [] cnt: int = 0 # print(f"prompt_batch: {len(prompt_batchs)}, init_batch: {len(init_batchs)}") for prompt_batch, init_batch in zip(prompt_batchs, init_batchs): # print(f"prompt_batch: {prompt_batch}") print(f"prompt_batch Size: {len(prompt_batch)}, init_batchs: {init_batch}") if init_batch is not None: init_batch = init_batch.to(device=device) batch_imgs = pipeline_call(prompt=prompt_batch, latents=init_batch).images handle_batch_fn(cnt, batch_imgs, prompt_batch, init_batch) cnt += len(batch_imgs) if return_imgs: all_imgs += [batch_imgs] del prompt_batch del batch_imgs if init_batch is not None: del init_batch torch.cuda.empty_cache() gc.collect() del pipeline torch.cuda.empty_cache() gc.collect() if return_imgs: return np.concatenate(all_imgs) else: return None @staticmethod def _sample(prompts: List[str], pipe: DiffusionPipeline, inits: torch.Tensor=None, num_inference_steps: int=SamplingStatic.NUM_INFERENCE_STEPS, guidance_scale: float=SamplingStatic.GUIDANCE_SCALE, max_batch_n: int=SamplingStatic.MAX_BATCH_N, seed: int=SamplingStatic.SEED, handle_fn: callable=SamplingStatic.HANDLE_FN, handle_batch_fn: callable=SamplingStatic.HANDLE_BATCH_FN, return_imgs: bool=False): if len(prompts) < SamplingStatic.SHOW_PROMPT_N:
Log.info(f"Prompts: {prompts}")
14
2023-10-17 19:57:37+00:00
12k
nchen909/Pass-Tuning
models_list/adapter/modeling_auto.py
[ { "identifier": "PLBartForConditionalGeneration", "path": "models_list/adapter/modeling_plbart.py", "snippet": "class PLBartForConditionalGeneration(PLBartPreTrainedModel):\n base_model_prefix = \"model\"\n _keys_to_ignore_on_load_missing = [\n r\"final_logits_bias\",\n r\"encoder.ve...
import warnings from collections import OrderedDict from transformers.utils import logging from transformers.models.albert.modeling_albert import ( AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from .modeling_plbart import ( PLBartForConditionalGeneration, PLBartModel, ) from transformers.models.bart.modeling_bart import ( BartForCausalLM, BartForQuestionAnswering, BartForSequenceClassification, ) from transformers.models.bert.modeling_bert import ( BertForMaskedLM, BertForMultipleChoice, BertForNextSentencePrediction, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertForTokenClassification, BertLMHeadModel, BertModel, ) from transformers.models.bert_generation.modeling_bert_generation import BertGenerationDecoder, BertGenerationEncoder from transformers.models.big_bird.modeling_big_bird import ( BigBirdForCausalLM, BigBirdForMaskedLM, BigBirdForMultipleChoice, BigBirdForPreTraining, BigBirdForQuestionAnswering, BigBirdForSequenceClassification, BigBirdForTokenClassification, BigBirdModel, ) from transformers.models.bigbird_pegasus.modeling_bigbird_pegasus import ( BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, ) from transformers.models.blenderbot.modeling_blenderbot import BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel from transformers.models.blenderbot_small.modeling_blenderbot_small import ( BlenderbotSmallForCausalLM, BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, ) from transformers.models.camembert.modeling_camembert import ( CamembertForCausalLM, CamembertForMaskedLM, CamembertForMultipleChoice, CamembertForQuestionAnswering, CamembertForSequenceClassification, CamembertForTokenClassification, CamembertModel, ) from transformers.models.canine.modeling_canine import ( CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineModel, ) from transformers.models.clip.modeling_clip import CLIPModel from transformers.models.convbert.modeling_convbert import ( ConvBertForMaskedLM, ConvBertForMultipleChoice, ConvBertForQuestionAnswering, ConvBertForSequenceClassification, ConvBertForTokenClassification, ConvBertModel, ) from transformers.models.ctrl.modeling_ctrl import CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel from transformers.models.deberta.modeling_deberta import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta_v2.modeling_deberta_v2 import ( DebertaV2ForMaskedLM, DebertaV2ForQuestionAnswering, DebertaV2ForSequenceClassification, DebertaV2ForTokenClassification, DebertaV2Model, ) from transformers.models.deit.modeling_deit import DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTModel from transformers.models.detr.modeling_detr import DetrForObjectDetection, DetrModel from transformers.models.distilbert.modeling_distilbert import ( DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) from transformers.models.dpr.modeling_dpr import DPRQuestionEncoder from transformers.models.electra.modeling_electra import ( ElectraForMaskedLM, ElectraForMultipleChoice, ElectraForPreTraining, ElectraForQuestionAnswering, ElectraForSequenceClassification, ElectraForTokenClassification, ElectraModel, ) from transformers.models.encoder_decoder.modeling_encoder_decoder import EncoderDecoderModel from transformers.models.flaubert.modeling_flaubert import ( FlaubertForMultipleChoice, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.fsmt.modeling_fsmt import FSMTForConditionalGeneration, FSMTModel from transformers.models.funnel.modeling_funnel import ( FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, ) from transformers.models.gpt2.modeling_gpt2 import GPT2ForSequenceClassification, GPT2LMHeadModel, GPT2Model from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM, GPTNeoForSequenceClassification, GPTNeoModel from transformers.models.hubert.modeling_hubert import HubertModel from transformers.models.ibert.modeling_ibert import ( IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, ) from transformers.models.layoutlm.modeling_layoutlm import ( LayoutLMForMaskedLM, LayoutLMForSequenceClassification, LayoutLMForTokenClassification, LayoutLMModel, ) from transformers.models.led.modeling_led import ( LEDForConditionalGeneration, LEDForQuestionAnswering, LEDForSequenceClassification, LEDModel, ) from transformers.models.longformer.modeling_longformer import ( LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, ) from transformers.models.luke.modeling_luke import LukeModel from transformers.models.lxmert.modeling_lxmert import LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel from transformers.models.m2m_100.modeling_m2m_100 import M2M100ForConditionalGeneration, M2M100Model from transformers.models.marian.modeling_marian import MarianForCausalLM, MarianModel, MarianMTModel from transformers.models.mbart.modeling_mbart import ( MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, ) from transformers.models.megatron_bert.modeling_megatron_bert import ( MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) from transformers.models.mobilebert.modeling_mobilebert import ( MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) from transformers.models.mpnet.modeling_mpnet import ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) from transformers.models.mt5.modeling_mt5 import MT5ForConditionalGeneration, MT5Model from transformers.models.openai.modeling_openai import OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel from transformers.models.pegasus.modeling_pegasus import PegasusForCausalLM, PegasusForConditionalGeneration, PegasusModel from transformers.models.prophetnet.modeling_prophetnet import ProphetNetForCausalLM, ProphetNetForConditionalGeneration, ProphetNetModel from transformers.models.rag.modeling_rag import ( # noqa: F401 - need to import all RagModels to be in globals() function RagModel, RagSequenceForGeneration, RagTokenForGeneration, ) from transformers.models.reformer.modeling_reformer import ( ReformerForMaskedLM, ReformerForQuestionAnswering, ReformerForSequenceClassification, ReformerModel, ReformerModelWithLMHead, ) from transformers.models.retribert.modeling_retribert import RetriBertModel from transformers.models.roberta.modeling_roberta import ( RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, ) from transformers.models.roformer.modeling_roformer import ( RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerModel, ) from transformers.models.speech_to_text.modeling_speech_to_text import Speech2TextForConditionalGeneration, Speech2TextModel from transformers.models.squeezebert.modeling_squeezebert import ( SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) from .modeling_t5 import T5ForConditionalGeneration, T5Model from transformers.models.tapas.modeling_tapas import ( TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, ) from transformers.models.transfo_xl.modeling_transfo_xl import TransfoXLForSequenceClassification, TransfoXLLMHeadModel, TransfoXLModel from transformers.models.visual_bert.modeling_visual_bert import VisualBertForPreTraining, VisualBertModel from transformers.models.vit.modeling_vit import ViTForImageClassification, ViTModel from transformers.models.wav2vec2.modeling_wav2vec2 import Wav2Vec2ForMaskedLM, Wav2Vec2ForPreTraining, Wav2Vec2Model from transformers.models.xlm.modeling_xlm import ( XLMForMultipleChoice, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm_prophetnet.modeling_xlm_prophetnet import ( XLMProphetNetForCausalLM, XLMProphetNetForConditionalGeneration, XLMProphetNetModel, ) from transformers.models.xlm_roberta.modeling_xlm_roberta import ( XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, ) from transformers.models.xlnet.modeling_xlnet import ( XLNetForMultipleChoice, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, ) from transformers.models.auto.auto_factory import _BaseAutoModelClass, auto_class_update from transformers.models.auto.configuration_auto import ( AlbertConfig, PLBartConfig, BertConfig, BertGenerationConfig, BigBirdConfig, BigBirdPegasusConfig, BlenderbotConfig, BlenderbotSmallConfig, CamembertConfig, CanineConfig, CLIPConfig, ConvBertConfig, CTRLConfig, DebertaConfig, DebertaV2Config, DeiTConfig, DetrConfig, DistilBertConfig, DPRConfig, ElectraConfig, EncoderDecoderConfig, FlaubertConfig, FSMTConfig, FunnelConfig, GPT2Config, GPTNeoConfig, HubertConfig, IBertConfig, LayoutLMConfig, LEDConfig, LongformerConfig, LukeConfig, LxmertConfig, M2M100Config, MarianConfig, MBartConfig, MegatronBertConfig, MobileBertConfig, MPNetConfig, MT5Config, OpenAIGPTConfig, PegasusConfig, ProphetNetConfig, ReformerConfig, RetriBertConfig, RobertaConfig, RoFormerConfig, Speech2TextConfig, SqueezeBertConfig, T5Config, TapasConfig, TransfoXLConfig, VisualBertConfig, ViTConfig, Wav2Vec2Config, XLMConfig, XLMProphetNetConfig, XLMRobertaConfig, XLNetConfig, )
10,780
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Auto Model class. """ # Add modeling imports here # # Instead of loading the BART from the transformers==4.9.1, we choose to load from our own prefix-tuning version. # Instead of loading the T5 from the transformers==4.9.1, we choose to load from our prefix-tuning version. logger = logging.get_logger(__name__) MODEL_MAPPING = OrderedDict( [ # Base model mapping (VisualBertConfig, VisualBertModel), (CanineConfig, CanineModel), (RoFormerConfig, RoFormerModel), (CLIPConfig, CLIPModel), (BigBirdPegasusConfig, BigBirdPegasusModel), (DeiTConfig, DeiTModel), (LukeConfig, LukeModel), (DetrConfig, DetrModel), (GPTNeoConfig, GPTNeoModel), (BigBirdConfig, BigBirdModel), (Speech2TextConfig, Speech2TextModel), (ViTConfig, ViTModel), (Wav2Vec2Config, Wav2Vec2Model), (HubertConfig, HubertModel), (M2M100Config, M2M100Model), (ConvBertConfig, ConvBertModel), (LEDConfig, LEDModel), (BlenderbotSmallConfig, BlenderbotSmallModel), (RetriBertConfig, RetriBertModel), (MT5Config, MT5Model),
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Auto Model class. """ # Add modeling imports here # # Instead of loading the BART from the transformers==4.9.1, we choose to load from our own prefix-tuning version. # Instead of loading the T5 from the transformers==4.9.1, we choose to load from our prefix-tuning version. logger = logging.get_logger(__name__) MODEL_MAPPING = OrderedDict( [ # Base model mapping (VisualBertConfig, VisualBertModel), (CanineConfig, CanineModel), (RoFormerConfig, RoFormerModel), (CLIPConfig, CLIPModel), (BigBirdPegasusConfig, BigBirdPegasusModel), (DeiTConfig, DeiTModel), (LukeConfig, LukeModel), (DetrConfig, DetrModel), (GPTNeoConfig, GPTNeoModel), (BigBirdConfig, BigBirdModel), (Speech2TextConfig, Speech2TextModel), (ViTConfig, ViTModel), (Wav2Vec2Config, Wav2Vec2Model), (HubertConfig, HubertModel), (M2M100Config, M2M100Model), (ConvBertConfig, ConvBertModel), (LEDConfig, LEDModel), (BlenderbotSmallConfig, BlenderbotSmallModel), (RetriBertConfig, RetriBertModel), (MT5Config, MT5Model),
(T5Config, T5Model),
3
2023-10-20 09:24:44+00:00
12k
JoaoPedro9674/django-ledger
django_ledger/tests/base.py
[ { "identifier": "EntityDataGenerator", "path": "django_ledger/io/data_generator.py", "snippet": "class EntityDataGenerator(LoggingMixIn):\n\n def __init__(self,\n user_model,\n entity_model: Union[EntityModel, str],\n start_date: date,\n ...
from datetime import date, timedelta from decimal import Decimal from itertools import cycle from logging import getLogger, DEBUG from random import randint, choice from typing import Optional from django.contrib.auth import get_user_model from django.core.exceptions import ObjectDoesNotExist from django.test import TestCase from django.test.client import Client from django.utils.timezone import get_default_timezone from django_ledger.io.data_generator import EntityDataGenerator from django_ledger.models.entity import EntityModel, EntityModelQuerySet
7,675
UserModel = get_user_model() class DjangoLedgerBaseTest(TestCase): FY_STARTS = None CAPITAL_CONTRIBUTION = None START_DATE = None DAYS_FORWARD = 9 * 30 TX_QUANTITY = 50 user_model = None TEST_DATA = list() CLIENT = None TZ = None N = None USER_EMAIL = None PASSWORD = None USERNAME = None logger = None accrual_cycle = cycle([True, False]) @classmethod def setUpTestData(cls): cls.logger = getLogger(__name__) cls.logger.setLevel(level=DEBUG) cls.USERNAME: str = 'testuser' cls.PASSWORD: str = 'NeverUseThisPassword12345' cls.USER_EMAIL: str = 'testuser@djangoledger.com' cls.N: int = 2 cls.DAYS_FWD: int = randint(180, 180 * 3) cls.TZ = get_default_timezone() cls.START_DATE = cls.get_random_date() cls.CLIENT = Client(enforce_csrf_checks=False) try: cls.user_model = UserModel.objects.get(username=cls.USERNAME) except ObjectDoesNotExist: cls.user_model = UserModel.objects.create_user( username=cls.USERNAME, password=cls.PASSWORD, email=cls.USER_EMAIL, ) cls.FY_STARTS = list(str(i) for i in range(1, 13)) cls.TEST_DATA = list() cls.CAPITAL_CONTRIBUTION = Decimal('50000.00') cls.ENTITY_MODEL_QUERYSET: Optional[EntityModelQuerySet] = None cls.create_entity_models(n=cls.N) cls.populate_entity_models() @classmethod def get_random_date(cls) -> date: return date( year=choice(range(1990, 2020)), month=choice(range(1, 13)), day=choice(range(1, 28)) ) @classmethod def login_client(cls): # cls.logger.info('Logging in client...') cls.CLIENT.login( username=cls.USERNAME, password=cls.PASSWORD ) @classmethod def logout_client(cls): # cls.logger.info('Logging out client...') cls.CLIENT.logout() @classmethod def refresh_test_data(cls, n: int = None): N = n if n else cls.N cls.TEST_DATA = [cls.get_random_entity_data() for _ in range(N)] @classmethod def get_random_entity_data(cls) -> dict: return { 'slug': f'a-cool-slug-{randint(10000, 99999)}', 'name': f'Testing Inc-{randint(100000, 999999)}', 'address_1': f'{randint(100000, 999999)} Main St', 'address_2': f'Suite {randint(1000, 9999)}', 'city': 'Charlotte', 'state': 'NC', 'zip_code': '28202', 'country': 'US', 'email': 'mytest@testinginc.com', 'website': 'http://www.mytestingco.com', 'fy_start_month': choice(cls.FY_STARTS), 'admin': cls.user_model, 'accrual_method': next(cls.accrual_cycle) }
UserModel = get_user_model() class DjangoLedgerBaseTest(TestCase): FY_STARTS = None CAPITAL_CONTRIBUTION = None START_DATE = None DAYS_FORWARD = 9 * 30 TX_QUANTITY = 50 user_model = None TEST_DATA = list() CLIENT = None TZ = None N = None USER_EMAIL = None PASSWORD = None USERNAME = None logger = None accrual_cycle = cycle([True, False]) @classmethod def setUpTestData(cls): cls.logger = getLogger(__name__) cls.logger.setLevel(level=DEBUG) cls.USERNAME: str = 'testuser' cls.PASSWORD: str = 'NeverUseThisPassword12345' cls.USER_EMAIL: str = 'testuser@djangoledger.com' cls.N: int = 2 cls.DAYS_FWD: int = randint(180, 180 * 3) cls.TZ = get_default_timezone() cls.START_DATE = cls.get_random_date() cls.CLIENT = Client(enforce_csrf_checks=False) try: cls.user_model = UserModel.objects.get(username=cls.USERNAME) except ObjectDoesNotExist: cls.user_model = UserModel.objects.create_user( username=cls.USERNAME, password=cls.PASSWORD, email=cls.USER_EMAIL, ) cls.FY_STARTS = list(str(i) for i in range(1, 13)) cls.TEST_DATA = list() cls.CAPITAL_CONTRIBUTION = Decimal('50000.00') cls.ENTITY_MODEL_QUERYSET: Optional[EntityModelQuerySet] = None cls.create_entity_models(n=cls.N) cls.populate_entity_models() @classmethod def get_random_date(cls) -> date: return date( year=choice(range(1990, 2020)), month=choice(range(1, 13)), day=choice(range(1, 28)) ) @classmethod def login_client(cls): # cls.logger.info('Logging in client...') cls.CLIENT.login( username=cls.USERNAME, password=cls.PASSWORD ) @classmethod def logout_client(cls): # cls.logger.info('Logging out client...') cls.CLIENT.logout() @classmethod def refresh_test_data(cls, n: int = None): N = n if n else cls.N cls.TEST_DATA = [cls.get_random_entity_data() for _ in range(N)] @classmethod def get_random_entity_data(cls) -> dict: return { 'slug': f'a-cool-slug-{randint(10000, 99999)}', 'name': f'Testing Inc-{randint(100000, 999999)}', 'address_1': f'{randint(100000, 999999)} Main St', 'address_2': f'Suite {randint(1000, 9999)}', 'city': 'Charlotte', 'state': 'NC', 'zip_code': '28202', 'country': 'US', 'email': 'mytest@testinginc.com', 'website': 'http://www.mytestingco.com', 'fy_start_month': choice(cls.FY_STARTS), 'admin': cls.user_model, 'accrual_method': next(cls.accrual_cycle) }
def get_random_entity_model(self) -> EntityModel:
1
2023-10-20 01:07:20+00:00
12k
hitz-zentroa/This-is-not-a-Dataset
run.py
[ { "identifier": "load_model", "path": "load_model.py", "snippet": "def load_model(\n inference: bool,\n model_weights_name_or_path: str,\n quantization: Optional[int] = None,\n use_lora: bool = False,\n lora_weights_name_or_path: Optional[str] = None,\n lora_target_modules: Optional[Li...
from load_model import load_model from dataset import get_dataloader from evaluate import evaluate from config import DataTrainingArguments, ModelArguments from transformers import ( HfArgumentParser, Seq2SeqTrainingArguments, set_seed, get_scheduler, ) from tqdm import tqdm from accelerate import Accelerator, find_executable_batch_size from typing import List from optimizer import get_optimizer from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from transformers.modeling_utils import unwrap_model import torch import os import wandb import gc import json import math import sys import logging
10,305
skip_special_tokens=False, clean_up_tokenization_spaces=False, ) ) print(f"*** Sample of batch 0 ***") print(f"-- Model inputs --\n{model_inputs}") print(f"*** End of sample ***\n") first = False if not predict_with_generate: if not model.config.is_encoder_decoder: logits = model( input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], ).logits else: encoder_output = model.get_encoder()( input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], ) decoder_args = { "attention_mask": batch["attention_mask"], "use_cache": False, "encoder_outputs": encoder_output, } gen_inputs = model.prepare_inputs_for_generation( input_ids=torch.tensor( [[tokenizer.pad_token_id]] * len(batch["input_ids"]) ).to(batch["input_ids"].device), **decoder_args, ) logits = model( **gen_inputs, ).logits logits = logits[:, -1, :] logits = torch.nn.functional.softmax(logits, dim=-1) logits = logits[:, [yes_id, no_id]] logits = logits[:, 0] / (logits[:, 0] + logits[:, 1]) preds = logits > 0.5 preds = accelerator.gather(preds).cpu().tolist() logits = accelerator.gather(logits).cpu().tolist() if accelerator.is_local_main_process: if accelerator.num_processes > 1: # Remove duplicated in last batch if we are in a distributed setting if step == len(dataloader) - 1: preds = preds[: (len(dataloader.dataset) - samples_seen)] logits = logits[: (len(dataloader.dataset) - samples_seen)] else: samples_seen += len(batch) all_preds.extend(preds) all_scores.extend(logits) else: preds = model.generate( input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], max_new_tokens=6, ) preds = accelerator.gather( accelerator.pad_across_processes( preds, dim=1, pad_index=tokenizer.pad_token_id, ) ).cpu() inputs_ids = accelerator.gather( accelerator.pad_across_processes( batch["input_ids"], dim=1, pad_index=tokenizer.pad_token_id, ) ).cpu() preds = preds[:, len(inputs_ids[0]) :] if accelerator.is_local_main_process: if accelerator.num_processes > 1: # Remove duplicated in last batch if we are in a distributed setting if step == len(dataloader) - 1: preds = preds[: (len(dataloader.dataset) - samples_seen)] else: samples_seen += len(batch) preds = tokenizer.batch_decode(preds, skip_special_tokens=True) # print(preds) for pred in preds: pred = pred.lower() if "true" in pred: all_preds.append(True) else: all_preds.append(False) if accelerator.is_local_main_process: with open(output_path, "w", encoding="utf8") as f: for pred in all_preds if not return_scores else all_scores: print(pred, file=f) if not return_scores: json_dataset = dataloader.dataset.get_jsonl() assert len(json_dataset) == len(all_preds) with open( os.path.splitext(output_path)[0] + ".jsonl", "w", encoding="utf8" ) as f: for json_line, pred in zip(json_dataset, all_preds): json_line["prediction"] = bool(pred) print(json.dumps(json_line, ensure_ascii=False), file=f) model.train() def main( model_args: ModelArguments,
def clean_cache(): """Clean cache to avoid memory leak. This fixes this issue: https://github.com/huggingface/transformers/issues/22801""" print(f"Cleaning GPU memory. Current memory usage: {torch.cuda.memory_allocated()}") torch.cuda.empty_cache() gc.collect() torch.cuda.empty_cache() print(f"GPU memory usage after cleaning: {torch.cuda.memory_allocated()}") def compute_loss(model, inputs, return_outputs=False): """ How the loss is computed by Trainer. By default, all models return the loss in the first element. Subclass and override for custom behavior. """ if "labels" in inputs: labels = inputs.pop("labels") else: raise ValueError("You should supply a labels key to compute the loss") if "loss_weight_mask" in inputs: loss_weight_mask = inputs.pop("loss_weight_mask") else: raise ValueError("You should supply a loss_weight_mask key to compute the loss") if unwrap_model(model).config.is_encoder_decoder: outputs = model(labels=labels, **inputs) else: outputs = model(**inputs) logits = outputs["logits"] if isinstance(outputs, dict) else outputs[0] model_name = unwrap_model(model)._get_name() if ( model_name in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES.values() or model_name == "PeftModelForCausalLM" ): logits = logits[..., :-1, :].contiguous() labels = labels[..., 1:].contiguous() loss_weight_mask = loss_weight_mask[..., 1:].contiguous() logits = logits.view(-1, logits.size(-1)) labels = labels.view(-1) loss_weight_mask = loss_weight_mask.view(-1) loss_fct = torch.nn.CrossEntropyLoss(reduction="none", ignore_index=-100) loss = loss_fct(logits, labels) loss = torch.sum(loss * loss_weight_mask) / torch.sum(loss_weight_mask) return (loss, outputs) if return_outputs else loss def gen_predictions( model, tokenizer, true_tokens_ids: List[int], false_tokens_ids: List[int], dataloader, output_path, accelerator, print_first=False, predict_with_generate=False, return_scores=False, ): if predict_with_generate and return_scores: raise ValueError( "return_scores is not supported when predict_with_generate is True" ) model.eval() with torch.no_grad(): samples_seen: int = 0 yes_id = true_tokens_ids[0] no_id = false_tokens_ids[0] all_preds = [] all_scores = [] first = True for step, batch in enumerate( tqdm(dataloader, f"Inference on {os.path.basename(output_path)}") ): if print_first and accelerator.is_local_main_process: ### DEBUG ### if print_first and first and accelerator.is_main_process: decodeable_inputs = batch.input_ids.clone() decodeable_inputs[ decodeable_inputs == -100 ] = tokenizer.pad_token_id model_inputs = "\n".join( tokenizer.batch_decode( decodeable_inputs, skip_special_tokens=False, clean_up_tokenization_spaces=False, ) ) print(f"*** Sample of batch 0 ***") print(f"-- Model inputs --\n{model_inputs}") print(f"*** End of sample ***\n") first = False if not predict_with_generate: if not model.config.is_encoder_decoder: logits = model( input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], ).logits else: encoder_output = model.get_encoder()( input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], ) decoder_args = { "attention_mask": batch["attention_mask"], "use_cache": False, "encoder_outputs": encoder_output, } gen_inputs = model.prepare_inputs_for_generation( input_ids=torch.tensor( [[tokenizer.pad_token_id]] * len(batch["input_ids"]) ).to(batch["input_ids"].device), **decoder_args, ) logits = model( **gen_inputs, ).logits logits = logits[:, -1, :] logits = torch.nn.functional.softmax(logits, dim=-1) logits = logits[:, [yes_id, no_id]] logits = logits[:, 0] / (logits[:, 0] + logits[:, 1]) preds = logits > 0.5 preds = accelerator.gather(preds).cpu().tolist() logits = accelerator.gather(logits).cpu().tolist() if accelerator.is_local_main_process: if accelerator.num_processes > 1: # Remove duplicated in last batch if we are in a distributed setting if step == len(dataloader) - 1: preds = preds[: (len(dataloader.dataset) - samples_seen)] logits = logits[: (len(dataloader.dataset) - samples_seen)] else: samples_seen += len(batch) all_preds.extend(preds) all_scores.extend(logits) else: preds = model.generate( input_ids=batch["input_ids"], attention_mask=batch["attention_mask"], max_new_tokens=6, ) preds = accelerator.gather( accelerator.pad_across_processes( preds, dim=1, pad_index=tokenizer.pad_token_id, ) ).cpu() inputs_ids = accelerator.gather( accelerator.pad_across_processes( batch["input_ids"], dim=1, pad_index=tokenizer.pad_token_id, ) ).cpu() preds = preds[:, len(inputs_ids[0]) :] if accelerator.is_local_main_process: if accelerator.num_processes > 1: # Remove duplicated in last batch if we are in a distributed setting if step == len(dataloader) - 1: preds = preds[: (len(dataloader.dataset) - samples_seen)] else: samples_seen += len(batch) preds = tokenizer.batch_decode(preds, skip_special_tokens=True) # print(preds) for pred in preds: pred = pred.lower() if "true" in pred: all_preds.append(True) else: all_preds.append(False) if accelerator.is_local_main_process: with open(output_path, "w", encoding="utf8") as f: for pred in all_preds if not return_scores else all_scores: print(pred, file=f) if not return_scores: json_dataset = dataloader.dataset.get_jsonl() assert len(json_dataset) == len(all_preds) with open( os.path.splitext(output_path)[0] + ".jsonl", "w", encoding="utf8" ) as f: for json_line, pred in zip(json_dataset, all_preds): json_line["prediction"] = bool(pred) print(json.dumps(json_line, ensure_ascii=False), file=f) model.train() def main( model_args: ModelArguments,
data_args: DataTrainingArguments,
3
2023-10-18 10:24:48+00:00
12k
SKYeve/Transcript-Combiner
pull_notes.py
[ { "identifier": "YoudaoNoteConvert", "path": "convert.py", "snippet": "class YoudaoNoteConvert(object):\n \"\"\"\n 有道云笔记 xml或者json 内容转换为 markdown 内容\n \"\"\"\n\n @staticmethod\n def covert_html_to_markdown(file_path) -> str:\n \"\"\"\n 转换 HTML 为 MarkDown\n :param file...
import json import logging import os import re import sys import time import traceback import xml.etree.ElementTree as ET import requests from enum import Enum from typing import Tuple from convert import YoudaoNoteConvert from youDaoNoteApi import YoudaoNoteApi from pull_images import PullImages from public import FileActionEnum from public import covert_config
8,321
:param modify_time: :return: """ youdao_file_suffix = os.path.splitext(file_name)[1] # 笔记后缀 note_type = self.judge_type(file_id,youdao_file_suffix) # print(f"{file_name}:{note_type}") is_note = True if note_type == 1 or note_type == 2 else False original_file_path = os.path.join(local_dir, file_name).replace('\\', '/') # 原后缀路径 # 生成.md后缀的文件的绝对路径 local_file_path = os.path.join(local_dir, ''.join([os.path.splitext(file_name)[0], MARKDOWN_SUFFIX])).replace( '\\', '/') if is_note else original_file_path # 如果有有道云笔记是「note」类型,则提示类型 tip = f'| 原文件: {file_name} | 类型:{note_type}' file_action = self._get_file_action(local_file_path, modify_time) if file_action == FileActionEnum.CONTINUE: return if file_action == FileActionEnum.UPDATE: # 考虑到使用 f.write() 直接覆盖原文件,在 Windows 下报错(WinError 183),先将其删除 os.remove(local_file_path) try: self._pull_file(file_id, original_file_path, note_type) print('{}「{}」{}'.format(file_action.value, local_file_path, tip)) except Exception as error: print('{}「{}」失败!请检查文件!错误提示:{}'.format(file_action.value, original_file_path, format(error))) def _judge_is_note(self, file_id, youdao_file_suffix): """ 判断是否是 note 类型 :param file_id: :param youdao_file_suffix: :return: """ is_note = False # 1、如果文件是 .note 类型 if youdao_file_suffix == NOTE_SUFFIX: is_note = True # 2、如果文件没有类型后缀,但以 `<?xml` 开头 if not youdao_file_suffix: response = self.youdaonote_api.get_file_by_id(file_id) content = response.content[:5] is_note = True if content == b"<?xml" else False return is_note # def judge_type(self, noteType: int, orgEditorType: int) -> int: # """ # 判断返回内容 # :param entryType: int # :param orgEditorType: int # :return: note_type: int # """ # note_type = 0 # # 返回xml格式的note笔记内容,noteType == 0 and orgEditorType == 1 # if noteType == 0 and orgEditorType == 1: # note_type = 1 # # 返回json格式的note笔记内容 # elif (noteType == 7 or noteType == 5) and orgEditorType == 1: # note_type = 2 # # 返回md文件内容 # elif noteType == 0 and orgEditorType == 0: # note_type = 3 # return note_type def judge_type(self,file_id: str ,youdao_file_suffix: str) -> int: """ 判断返回内容 :param entryType: int :param orgEditorType: int :return: note_type: int """ note_type = 0 is_xml = False if youdao_file_suffix == ".note": response = self.youdaonote_api.get_file_by_id(file_id) content = response.content[:5] is_xml = True if content == b"<?xml" else False if is_xml: # xml类型 note_type = 1 else: # json类型 note_type = 2 elif youdao_file_suffix == ".md": note_type = 3 else: print(f"文件后缀「{youdao_file_suffix}」不识别,请检查!") return note_type def _pull_file(self, file_id, file_path, note_type): """ 下载文件 :param file_id: :param file_path: :param itype: :return: """ # 1、所有的都先下载 response = self.youdaonote_api.get_file_by_id(file_id) with open(file_path, 'wb') as f: f.write(response.content) # response.content 本身就是字节类型 new_file_path = "" # 2、如果文件是 note 类型,将其转换为 MarkDown 类型 if note_type == 1: try: new_file_path = YoudaoNoteConvert.covert_xml_to_markdown(file_path) except ET.ParseError: print(f'{file_path} 笔记应该为 17 年以前新建,格式为 html,将转换为 Markdown ...') new_file_path = YoudaoNoteConvert.covert_html_to_markdown(file_path) except Exception: print(f'{file_path} 笔记转换 MarkDown 失败,将跳过') elif note_type == 2: new_file_path = YoudaoNoteConvert.covert_json_to_markdown(file_path) elif note_type == 3: YoudaoNoteConvert.markdown_filter(file_path) new_file_path = file_path # 迁移附件和图片 if os.path.exists(new_file_path):
#!/usr/bin/env python3 # -*- coding: utf-8 -*- MARKDOWN_SUFFIX = '.md' NOTE_SUFFIX = '.note' CONFIG_PATH = 'config.json' class YoudaoNotePull(object): """ 有道云笔记 Pull 封装 """ CONFIG_PATH = 'config.json' def __init__(self): self.root_local_dir = None # 本地文件根目录 self.youdaonote_api = None self.smms_secret_token = None self.is_relative_path = None # 是否使用相对路径 def get_ydnote_dir_id(self): """ 获取有道云笔记根目录或指定目录 ID :return: """ config_dict, error_msg = covert_config(CONFIG_PATH) if error_msg: return '', error_msg local_dir, error_msg = self._check_local_dir(local_dir=config_dict['local_dir']) if error_msg: return '', error_msg self.root_local_dir = local_dir self.youdaonote_api = YoudaoNoteApi() error_msg = self.youdaonote_api.login_by_cookies() if error_msg: return '', error_msg self.smms_secret_token = config_dict['smms_secret_token'] self.is_relative_path = config_dict['is_relative_path'] return self._get_ydnote_dir_id(ydnote_dir=config_dict['ydnote_dir']) def pull_dir_by_id_recursively(self, dir_id, local_dir): """ 根据目录 ID 循环遍历下载目录下所有文件 :param dir_id: :param local_dir: 本地目录 :return: error_msg """ dir_info = self.youdaonote_api.get_dir_info_by_id(dir_id) try: entries = dir_info['entries'] except KeyError: raise KeyError('有道云笔记修改了接口地址,此脚本暂时不能使用!请提 issue') for entry in entries: file_entry = entry['fileEntry'] id = file_entry['id'] file_name = file_entry['name'] file_name = self._optimize_file_name(file_name) # noteType = file_entry['noteType'] # orgEditorType = file_entry['orgEditorType'] if file_entry['dir']: sub_dir = os.path.join(local_dir, file_name).replace('\\', '/') # 判断本地文件夹是否存在 if not os.path.exists(sub_dir): os.mkdir(sub_dir) self.pull_dir_by_id_recursively(id, sub_dir) else: modify_time = file_entry['modifyTimeForSort'] self._add_or_update_file(id, file_name, local_dir, modify_time) def _check_local_dir(self, local_dir, test_default_dir=None) -> Tuple[str, str]: """ 检查本地文件夹 :param local_dir: 本地文件夹名(绝对路径) :return: local_dir, error_msg """ # 如果没有指定本地文件夹,当前目录新增 youdaonote 目录 if not local_dir: add_dir = test_default_dir if test_default_dir else 'youdaonote' # 兼容 Windows 系统,将路径分隔符(\\)替换为 / local_dir = os.path.join(os.getcwd(), add_dir).replace('\\', '/') # 如果指定的本地文件夹不存在,创建文件夹 if not os.path.exists(local_dir): try: os.mkdir(local_dir) except: return '', '请检查「{}」上层文件夹是否存在,并使用绝对路径!'.format(local_dir) return local_dir, '' def _get_ydnote_dir_id(self, ydnote_dir) -> Tuple[str, str]: """ 获取指定有道云笔记指定目录 ID :param ydnote_dir: 指定有道云笔记指定目录 :return: dir_id, error_msg """ root_dir_info = self.youdaonote_api.get_root_dir_info_id() root_dir_id = root_dir_info['fileEntry']['id'] # 如果不指定文件夹,取根目录 ID if not ydnote_dir: return root_dir_id, '' dir_info = self.youdaonote_api.get_dir_info_by_id(root_dir_id) for entry in dir_info['entries']: file_entry = entry['fileEntry'] if file_entry['name'] == ydnote_dir: return file_entry['id'], '' return '', '有道云笔记指定顶层目录不存在' def _add_or_update_file(self, file_id, file_name, local_dir, modify_time): """ 新增或更新文件 :param file_id: :param file_name: :param local_dir: :param modify_time: :return: """ youdao_file_suffix = os.path.splitext(file_name)[1] # 笔记后缀 note_type = self.judge_type(file_id,youdao_file_suffix) # print(f"{file_name}:{note_type}") is_note = True if note_type == 1 or note_type == 2 else False original_file_path = os.path.join(local_dir, file_name).replace('\\', '/') # 原后缀路径 # 生成.md后缀的文件的绝对路径 local_file_path = os.path.join(local_dir, ''.join([os.path.splitext(file_name)[0], MARKDOWN_SUFFIX])).replace( '\\', '/') if is_note else original_file_path # 如果有有道云笔记是「note」类型,则提示类型 tip = f'| 原文件: {file_name} | 类型:{note_type}' file_action = self._get_file_action(local_file_path, modify_time) if file_action == FileActionEnum.CONTINUE: return if file_action == FileActionEnum.UPDATE: # 考虑到使用 f.write() 直接覆盖原文件,在 Windows 下报错(WinError 183),先将其删除 os.remove(local_file_path) try: self._pull_file(file_id, original_file_path, note_type) print('{}「{}」{}'.format(file_action.value, local_file_path, tip)) except Exception as error: print('{}「{}」失败!请检查文件!错误提示:{}'.format(file_action.value, original_file_path, format(error))) def _judge_is_note(self, file_id, youdao_file_suffix): """ 判断是否是 note 类型 :param file_id: :param youdao_file_suffix: :return: """ is_note = False # 1、如果文件是 .note 类型 if youdao_file_suffix == NOTE_SUFFIX: is_note = True # 2、如果文件没有类型后缀,但以 `<?xml` 开头 if not youdao_file_suffix: response = self.youdaonote_api.get_file_by_id(file_id) content = response.content[:5] is_note = True if content == b"<?xml" else False return is_note # def judge_type(self, noteType: int, orgEditorType: int) -> int: # """ # 判断返回内容 # :param entryType: int # :param orgEditorType: int # :return: note_type: int # """ # note_type = 0 # # 返回xml格式的note笔记内容,noteType == 0 and orgEditorType == 1 # if noteType == 0 and orgEditorType == 1: # note_type = 1 # # 返回json格式的note笔记内容 # elif (noteType == 7 or noteType == 5) and orgEditorType == 1: # note_type = 2 # # 返回md文件内容 # elif noteType == 0 and orgEditorType == 0: # note_type = 3 # return note_type def judge_type(self,file_id: str ,youdao_file_suffix: str) -> int: """ 判断返回内容 :param entryType: int :param orgEditorType: int :return: note_type: int """ note_type = 0 is_xml = False if youdao_file_suffix == ".note": response = self.youdaonote_api.get_file_by_id(file_id) content = response.content[:5] is_xml = True if content == b"<?xml" else False if is_xml: # xml类型 note_type = 1 else: # json类型 note_type = 2 elif youdao_file_suffix == ".md": note_type = 3 else: print(f"文件后缀「{youdao_file_suffix}」不识别,请检查!") return note_type def _pull_file(self, file_id, file_path, note_type): """ 下载文件 :param file_id: :param file_path: :param itype: :return: """ # 1、所有的都先下载 response = self.youdaonote_api.get_file_by_id(file_id) with open(file_path, 'wb') as f: f.write(response.content) # response.content 本身就是字节类型 new_file_path = "" # 2、如果文件是 note 类型,将其转换为 MarkDown 类型 if note_type == 1: try: new_file_path = YoudaoNoteConvert.covert_xml_to_markdown(file_path) except ET.ParseError: print(f'{file_path} 笔记应该为 17 年以前新建,格式为 html,将转换为 Markdown ...') new_file_path = YoudaoNoteConvert.covert_html_to_markdown(file_path) except Exception: print(f'{file_path} 笔记转换 MarkDown 失败,将跳过') elif note_type == 2: new_file_path = YoudaoNoteConvert.covert_json_to_markdown(file_path) elif note_type == 3: YoudaoNoteConvert.markdown_filter(file_path) new_file_path = file_path # 迁移附件和图片 if os.path.exists(new_file_path):
pull_image = PullImages(self.youdaonote_api,self.smms_secret_token,self.is_relative_path)
2
2023-10-17 11:21:50+00:00
12k
S-LoRA/S-LoRA
slora/server/api_server.py
[ { "identifier": "build_prompt", "path": "slora/server/build_prompt.py", "snippet": "async def build_prompt(request) -> str:\n if not _fastchat_available:\n raise ModuleNotFoundError(\n \"fastchat is not installed. Please install fastchat to use \"\n \"the chat completion ...
import asyncio import time import torch import uvloop import sys import argparse import json import uuid import multiprocessing as mp import uvicorn from .build_prompt import build_prompt from http import HTTPStatus from typing import AsyncGenerator from fastapi import BackgroundTasks, FastAPI, Request from fastapi.responses import Response, StreamingResponse, JSONResponse from .sampling_params import SamplingParams from .httpserver.manager import HttpServerManager from .detokenization.manager import start_detokenization_process from .router.manager import start_router_process from slora.utils.net_utils import alloc_can_use_network_port from slora.common.configs.config import setting from .api_models import ( ChatCompletionRequest, UsageInfo, ChatMessage, ChatCompletionResponseChoice, ChatCompletionResponse, DeltaMessage, ChatCompletionStreamResponse, ChatCompletionStreamResponseChoice, ) from slora.mprophet.measure import ModelProphet from slora.mprophet.lora_stats import LoRAProphet
7,453
sampling_params = SamplingParams(**sample_params_dict) sampling_params.verify() if "req_id" in request_dict: request_id = request_dict["req_id"] else: request_id = uuid.uuid4().hex results_generator = httpserver_manager.generate(adapter_dir, prompt, sampling_params, request_id) # Streaming case async def stream_results() -> AsyncGenerator[bytes, None]: async for request_output, metadata, finished in results_generator: ret = { "token": { "id": metadata.get("id", None), "text": request_output, "logprob": metadata.get("logprob", None), "special": False }, "generated_text": None, "finished": finished, "details": None } yield ("data:" + json.dumps(ret, ensure_ascii=False) + f"\n\n").encode( "utf-8" ) async def abort_request() -> None: await httpserver_manager.abort(request_id) background_tasks = BackgroundTasks() # Abort the request if the client disconnects. background_tasks.add_task(abort_request) return StreamingResponse( stream_results(), media_type="text/event-stream", background=background_tasks ) @app.post("/v1/chat/completions", response_model=ChatCompletionResponse) async def chat_completions( request: ChatCompletionRequest, raw_request: Request ) -> Response: global isFirst if isFirst: loop = asyncio.get_event_loop() loop.create_task(httpserver_manager.handle_loop()) isFirst = False if request.logit_bias is not None: return create_error_response( HTTPStatus.BAD_REQUEST, "The logit_bias parameter is not currently supported", ) if request.n > 1: return create_error_response( HTTPStatus.BAD_REQUEST, "The n parameter currently only supports 1" ) if request.function_call != "none": return create_error_response( HTTPStatus.BAD_REQUEST, "The function call feature is not supported" ) created_time = int(time.time()) prompt = await build_prompt(request) sampling_params = SamplingParams( do_sample=request.do_sample, presence_penalty=request.presence_penalty, frequency_penalty=request.frequency_penalty, temperature=request.temperature, top_p=request.top_p, top_k=request.top_k, ignore_eos=request.ignore_eos, max_new_tokens=request.max_tokens, stop_sequences=request.stop ) sampling_params.verify() request_id = f"chatcmpl-{uuid.uuid4().hex}" results_generator = httpserver_manager.generate(prompt, sampling_params, request_id) # Non-streaming case if not request.stream: final_output = [] prompt_tokens = -1 completion_tokens = 0 async for request_output, metadata in results_generator: if await raw_request.is_disconnected(): # Abort the request if the client disconnects. await httpserver_manager.abort(request_id) return Response(status_code=499) completion_tokens += 1 if prompt_tokens == -1: prompt_tokens = metadata["prompt_tokens"] final_output.append(request_output) usage = UsageInfo( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens ) chat_message = ChatMessage(role="assistant", content="".join(final_output)) choice = ChatCompletionResponseChoice(index=0, message=chat_message) resp = ChatCompletionResponse( id=request_id, created=created_time, model=request.model, choices=[choice], usage=usage ) return resp # Streaming case async def stream_results() -> AsyncGenerator[bytes, None]: async for request_output, metadata in results_generator: delta_message = DeltaMessage(role="assistant", content=request_output)
# Adapted from vllm/entrypoints/api_server.py # of the vllm-project/vllm GitHub repository. # # Copyright 2023 ModelTC Team # Copyright 2023 vLLM 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. asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) GB = 1024 ** 3 MB = 1024 ** 2 TIMEOUT_KEEP_ALIVE = 5 # seconds. app = FastAPI() isFirst = True def create_error_response(status_code: HTTPStatus, message: str) -> JSONResponse: return JSONResponse({"message": message}, status_code=status_code.value) @app.get("/healthz") @app.get("/health") def healthcheck(): return "OK" @app.post("/generate") async def generate(request: Request) -> Response: global isFirst if isFirst: loop = asyncio.get_event_loop() loop.create_task(httpserver_manager.handle_loop()) isFirst = False request_dict = await request.json() adapter_dir = request_dict["lora_dir"] if "lora_dir" in request_dict else None prompt = request_dict.pop("inputs") sample_params_dict = request_dict["parameters"] return_details = sample_params_dict.pop("return_details", False) sampling_params = SamplingParams(**sample_params_dict) sampling_params.verify() if "req_id" in request_dict: request_id = request_dict["req_id"] else: request_id = uuid.uuid4().hex results_generator = httpserver_manager.generate(adapter_dir, prompt, sampling_params, request_id) # Non-streaming case final_output = [] count_output_tokens = 0 tokens = [] async for request_output, metadata, finished in results_generator: count_output_tokens += 1 if finished == -1: return Response(status_code=499) if await request.is_disconnected(): # Abort the request if the client disconnects. await httpserver_manager.abort(request_id) return Response(status_code=499) final_output.append(request_output) if return_details: metadata["text"] = request_output tokens.append(metadata) assert final_output is not None ret = { "generated_text": ["".join(final_output)], "count_output_tokens": count_output_tokens, } if return_details: ret["tokens"] = tokens return Response(content=json.dumps(ret, ensure_ascii=False).encode("utf-8")) @app.post("/generate_stream") async def generate_stream(request: Request) -> Response: global isFirst if isFirst: loop = asyncio.get_event_loop() loop.create_task(httpserver_manager.handle_loop()) isFirst = False request_dict = await request.json() adapter_dir = request_dict["lora_dir"] if "lora_dir" in request_dict else None prompt = request_dict.pop("inputs") sample_params_dict = request_dict["parameters"] return_details = sample_params_dict.pop("return_details", False) sampling_params = SamplingParams(**sample_params_dict) sampling_params.verify() if "req_id" in request_dict: request_id = request_dict["req_id"] else: request_id = uuid.uuid4().hex results_generator = httpserver_manager.generate(adapter_dir, prompt, sampling_params, request_id) # Streaming case async def stream_results() -> AsyncGenerator[bytes, None]: async for request_output, metadata, finished in results_generator: ret = { "token": { "id": metadata.get("id", None), "text": request_output, "logprob": metadata.get("logprob", None), "special": False }, "generated_text": None, "finished": finished, "details": None } yield ("data:" + json.dumps(ret, ensure_ascii=False) + f"\n\n").encode( "utf-8" ) async def abort_request() -> None: await httpserver_manager.abort(request_id) background_tasks = BackgroundTasks() # Abort the request if the client disconnects. background_tasks.add_task(abort_request) return StreamingResponse( stream_results(), media_type="text/event-stream", background=background_tasks ) @app.post("/v1/chat/completions", response_model=ChatCompletionResponse) async def chat_completions( request: ChatCompletionRequest, raw_request: Request ) -> Response: global isFirst if isFirst: loop = asyncio.get_event_loop() loop.create_task(httpserver_manager.handle_loop()) isFirst = False if request.logit_bias is not None: return create_error_response( HTTPStatus.BAD_REQUEST, "The logit_bias parameter is not currently supported", ) if request.n > 1: return create_error_response( HTTPStatus.BAD_REQUEST, "The n parameter currently only supports 1" ) if request.function_call != "none": return create_error_response( HTTPStatus.BAD_REQUEST, "The function call feature is not supported" ) created_time = int(time.time()) prompt = await build_prompt(request) sampling_params = SamplingParams( do_sample=request.do_sample, presence_penalty=request.presence_penalty, frequency_penalty=request.frequency_penalty, temperature=request.temperature, top_p=request.top_p, top_k=request.top_k, ignore_eos=request.ignore_eos, max_new_tokens=request.max_tokens, stop_sequences=request.stop ) sampling_params.verify() request_id = f"chatcmpl-{uuid.uuid4().hex}" results_generator = httpserver_manager.generate(prompt, sampling_params, request_id) # Non-streaming case if not request.stream: final_output = [] prompt_tokens = -1 completion_tokens = 0 async for request_output, metadata in results_generator: if await raw_request.is_disconnected(): # Abort the request if the client disconnects. await httpserver_manager.abort(request_id) return Response(status_code=499) completion_tokens += 1 if prompt_tokens == -1: prompt_tokens = metadata["prompt_tokens"] final_output.append(request_output) usage = UsageInfo( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens ) chat_message = ChatMessage(role="assistant", content="".join(final_output)) choice = ChatCompletionResponseChoice(index=0, message=chat_message) resp = ChatCompletionResponse( id=request_id, created=created_time, model=request.model, choices=[choice], usage=usage ) return resp # Streaming case async def stream_results() -> AsyncGenerator[bytes, None]: async for request_output, metadata in results_generator: delta_message = DeltaMessage(role="assistant", content=request_output)
stream_choice = ChatCompletionStreamResponseChoice(
14
2023-11-05 04:08:36+00:00
12k
Yuliang-Liu/Monkey
data_generation/grit/third_party/CenterNet2/projects/CenterNet2/centernet/modeling/dense_heads/centernet.py
[ { "identifier": "heatmap_focal_loss_jit", "path": "data_generation/grit/third_party/CenterNet2/projects/CenterNet2/centernet/modeling/layers/heatmap_focal_loss.py", "snippet": "def heatmap_focal_loss(\n inputs,\n targets,\n pos_inds,\n labels,\n alpha: float = -1,\n beta: float = 4,\n ...
import math import json import copy import numpy as np import torch from typing import List, Dict from torch import nn from torch.nn import functional as F from detectron2.modeling.proposal_generator.build import PROPOSAL_GENERATOR_REGISTRY from detectron2.layers import ShapeSpec, cat from detectron2.structures import Instances, Boxes from detectron2.modeling import detector_postprocess from detectron2.utils.comm import get_world_size from detectron2.config import configurable from ..layers.heatmap_focal_loss import heatmap_focal_loss_jit from ..layers.heatmap_focal_loss import binary_heatmap_focal_loss from ..layers.iou_loss import IOULoss from ..layers.ml_nms import ml_nms from ..debug import debug_train, debug_test from .utils import reduce_sum, _transpose from .centernet_head import CenterNetHead
7,617
'score_thresh': cfg.MODEL.CENTERNET.INFERENCE_TH, 'loc_loss_type': cfg.MODEL.CENTERNET.LOC_LOSS_TYPE, 'hm_min_overlap': cfg.MODEL.CENTERNET.HM_MIN_OVERLAP, 'min_radius': cfg.MODEL.CENTERNET.MIN_RADIUS, 'hm_focal_alpha': cfg.MODEL.CENTERNET.HM_FOCAL_ALPHA, 'hm_focal_beta': cfg.MODEL.CENTERNET.HM_FOCAL_BETA, 'loss_gamma': cfg.MODEL.CENTERNET.LOSS_GAMMA, 'reg_weight': cfg.MODEL.CENTERNET.REG_WEIGHT, 'not_norm_reg': cfg.MODEL.CENTERNET.NOT_NORM_REG, 'with_agn_hm': cfg.MODEL.CENTERNET.WITH_AGN_HM, 'only_proposal': cfg.MODEL.CENTERNET.ONLY_PROPOSAL, 'as_proposal': cfg.MODEL.CENTERNET.AS_PROPOSAL, 'not_nms': cfg.MODEL.CENTERNET.NOT_NMS, 'pos_weight': cfg.MODEL.CENTERNET.POS_WEIGHT, 'neg_weight': cfg.MODEL.CENTERNET.NEG_WEIGHT, 'sigmoid_clamp': cfg.MODEL.CENTERNET.SIGMOID_CLAMP, 'ignore_high_fp': cfg.MODEL.CENTERNET.IGNORE_HIGH_FP, 'center_nms': cfg.MODEL.CENTERNET.CENTER_NMS, 'sizes_of_interest': cfg.MODEL.CENTERNET.SOI, 'more_pos': cfg.MODEL.CENTERNET.MORE_POS, 'more_pos_thresh': cfg.MODEL.CENTERNET.MORE_POS_THRESH, 'more_pos_topk': cfg.MODEL.CENTERNET.MORE_POS_TOPK, 'pre_nms_topk_train': cfg.MODEL.CENTERNET.PRE_NMS_TOPK_TRAIN, 'pre_nms_topk_test': cfg.MODEL.CENTERNET.PRE_NMS_TOPK_TEST, 'post_nms_topk_train': cfg.MODEL.CENTERNET.POST_NMS_TOPK_TRAIN, 'post_nms_topk_test': cfg.MODEL.CENTERNET.POST_NMS_TOPK_TEST, 'nms_thresh_train': cfg.MODEL.CENTERNET.NMS_TH_TRAIN, 'nms_thresh_test': cfg.MODEL.CENTERNET.NMS_TH_TEST, 'no_reduce': cfg.MODEL.CENTERNET.NO_REDUCE, 'debug': cfg.DEBUG, 'vis_thresh': cfg.VIS_THRESH, 'pixel_mean': cfg.MODEL.PIXEL_MEAN, 'pixel_std': cfg.MODEL.PIXEL_STD, 'device': cfg.MODEL.DEVICE, 'centernet_head': CenterNetHead( cfg, [input_shape[f] for f in cfg.MODEL.CENTERNET.IN_FEATURES]), } return ret def forward(self, images, features_dict, gt_instances): features = [features_dict[f] for f in self.in_features] clss_per_level, reg_pred_per_level, agn_hm_pred_per_level = \ self.centernet_head(features) grids = self.compute_grids(features) shapes_per_level = grids[0].new_tensor( [(x.shape[2], x.shape[3]) for x in reg_pred_per_level]) if not self.training: return self.inference( images, clss_per_level, reg_pred_per_level, agn_hm_pred_per_level, grids) else: pos_inds, labels, reg_targets, flattened_hms = \ self._get_ground_truth( grids, shapes_per_level, gt_instances) # logits_pred: M x F, reg_pred: M x 4, agn_hm_pred: M logits_pred, reg_pred, agn_hm_pred = self._flatten_outputs( clss_per_level, reg_pred_per_level, agn_hm_pred_per_level) if self.more_pos: # add more pixels as positive if \ # 1. they are within the center3x3 region of an object # 2. their regression losses are small (<self.more_pos_thresh) pos_inds, labels = self._add_more_pos( reg_pred, gt_instances, shapes_per_level) losses = self.losses( pos_inds, labels, reg_targets, flattened_hms, logits_pred, reg_pred, agn_hm_pred) proposals = None if self.only_proposal: agn_hm_pred_per_level = [x.sigmoid() for x in agn_hm_pred_per_level] proposals = self.predict_instances( grids, agn_hm_pred_per_level, reg_pred_per_level, images.image_sizes, [None for _ in agn_hm_pred_per_level]) elif self.as_proposal: # category specific bbox as agnostic proposals clss_per_level = [x.sigmoid() for x in clss_per_level] proposals = self.predict_instances( grids, clss_per_level, reg_pred_per_level, images.image_sizes, agn_hm_pred_per_level) if self.only_proposal or self.as_proposal: for p in range(len(proposals)): proposals[p].proposal_boxes = proposals[p].get('pred_boxes') proposals[p].objectness_logits = proposals[p].get('scores') proposals[p].remove('pred_boxes') proposals[p].remove('scores') proposals[p].remove('pred_classes') if self.debug: debug_train( [self.denormalizer(x) for x in images], gt_instances, flattened_hms, reg_targets, labels, pos_inds, shapes_per_level, grids, self.strides) return proposals, losses def losses( self, pos_inds, labels, reg_targets, flattened_hms, logits_pred, reg_pred, agn_hm_pred): ''' Inputs: pos_inds: N labels: N reg_targets: M x 4 flattened_hms: M x C logits_pred: M x C reg_pred: M x 4 agn_hm_pred: M x 1 or None N: number of positive locations in all images M: number of pixels from all FPN levels C: number of classes ''' assert (torch.isfinite(reg_pred).all().item()) num_pos_local = pos_inds.numel() num_gpus = get_world_size() if self.no_reduce: total_num_pos = num_pos_local * num_gpus else:
__all__ = ["CenterNet"] INF = 100000000 @PROPOSAL_GENERATOR_REGISTRY.register() class CenterNet(nn.Module): @configurable def __init__(self, # input_shape: Dict[str, ShapeSpec], in_channels=256, *, num_classes=80, in_features=("p3", "p4", "p5", "p6", "p7"), strides=(8, 16, 32, 64, 128), score_thresh=0.05, hm_min_overlap=0.8, loc_loss_type='giou', min_radius=4, hm_focal_alpha=0.25, hm_focal_beta=4, loss_gamma=2.0, reg_weight=2.0, not_norm_reg=True, with_agn_hm=False, only_proposal=False, as_proposal=False, not_nms=False, pos_weight=1., neg_weight=1., sigmoid_clamp=1e-4, ignore_high_fp=-1., center_nms=False, sizes_of_interest=[[0,80],[64,160],[128,320],[256,640],[512,10000000]], more_pos=False, more_pos_thresh=0.2, more_pos_topk=9, pre_nms_topk_train=1000, pre_nms_topk_test=1000, post_nms_topk_train=100, post_nms_topk_test=100, nms_thresh_train=0.6, nms_thresh_test=0.6, no_reduce=False, debug=False, vis_thresh=0.5, pixel_mean=[103.530,116.280,123.675], pixel_std=[1.0,1.0,1.0], device='cuda', centernet_head=None, ): super().__init__() self.num_classes = num_classes self.in_features = in_features self.strides = strides self.score_thresh = score_thresh self.min_radius = min_radius self.hm_focal_alpha = hm_focal_alpha self.hm_focal_beta = hm_focal_beta self.loss_gamma = loss_gamma self.reg_weight = reg_weight self.not_norm_reg = not_norm_reg self.with_agn_hm = with_agn_hm self.only_proposal = only_proposal self.as_proposal = as_proposal self.not_nms = not_nms self.pos_weight = pos_weight self.neg_weight = neg_weight self.sigmoid_clamp = sigmoid_clamp self.ignore_high_fp = ignore_high_fp self.center_nms = center_nms self.sizes_of_interest = sizes_of_interest self.more_pos = more_pos self.more_pos_thresh = more_pos_thresh self.more_pos_topk = more_pos_topk self.pre_nms_topk_train = pre_nms_topk_train self.pre_nms_topk_test = pre_nms_topk_test self.post_nms_topk_train = post_nms_topk_train self.post_nms_topk_test = post_nms_topk_test self.nms_thresh_train = nms_thresh_train self.nms_thresh_test = nms_thresh_test self.no_reduce = no_reduce self.debug = debug self.vis_thresh = vis_thresh if self.center_nms: self.not_nms = True self.iou_loss = IOULoss(loc_loss_type) assert (not self.only_proposal) or self.with_agn_hm # delta for rendering heatmap self.delta = (1 - hm_min_overlap) / (1 + hm_min_overlap) if centernet_head is None: self.centernet_head = CenterNetHead( in_channels=in_channels, num_levels=len(in_features), with_agn_hm=with_agn_hm, only_proposal=only_proposal) else: self.centernet_head = centernet_head if self.debug: pixel_mean = torch.Tensor(pixel_mean).to( torch.device(device)).view(3, 1, 1) pixel_std = torch.Tensor(pixel_std).to( torch.device(device)).view(3, 1, 1) self.denormalizer = lambda x: x * pixel_std + pixel_mean @classmethod def from_config(cls, cfg, input_shape): ret = { # 'input_shape': input_shape, 'in_channels': input_shape[ cfg.MODEL.CENTERNET.IN_FEATURES[0]].channels, 'num_classes': cfg.MODEL.CENTERNET.NUM_CLASSES, 'in_features': cfg.MODEL.CENTERNET.IN_FEATURES, 'strides': cfg.MODEL.CENTERNET.FPN_STRIDES, 'score_thresh': cfg.MODEL.CENTERNET.INFERENCE_TH, 'loc_loss_type': cfg.MODEL.CENTERNET.LOC_LOSS_TYPE, 'hm_min_overlap': cfg.MODEL.CENTERNET.HM_MIN_OVERLAP, 'min_radius': cfg.MODEL.CENTERNET.MIN_RADIUS, 'hm_focal_alpha': cfg.MODEL.CENTERNET.HM_FOCAL_ALPHA, 'hm_focal_beta': cfg.MODEL.CENTERNET.HM_FOCAL_BETA, 'loss_gamma': cfg.MODEL.CENTERNET.LOSS_GAMMA, 'reg_weight': cfg.MODEL.CENTERNET.REG_WEIGHT, 'not_norm_reg': cfg.MODEL.CENTERNET.NOT_NORM_REG, 'with_agn_hm': cfg.MODEL.CENTERNET.WITH_AGN_HM, 'only_proposal': cfg.MODEL.CENTERNET.ONLY_PROPOSAL, 'as_proposal': cfg.MODEL.CENTERNET.AS_PROPOSAL, 'not_nms': cfg.MODEL.CENTERNET.NOT_NMS, 'pos_weight': cfg.MODEL.CENTERNET.POS_WEIGHT, 'neg_weight': cfg.MODEL.CENTERNET.NEG_WEIGHT, 'sigmoid_clamp': cfg.MODEL.CENTERNET.SIGMOID_CLAMP, 'ignore_high_fp': cfg.MODEL.CENTERNET.IGNORE_HIGH_FP, 'center_nms': cfg.MODEL.CENTERNET.CENTER_NMS, 'sizes_of_interest': cfg.MODEL.CENTERNET.SOI, 'more_pos': cfg.MODEL.CENTERNET.MORE_POS, 'more_pos_thresh': cfg.MODEL.CENTERNET.MORE_POS_THRESH, 'more_pos_topk': cfg.MODEL.CENTERNET.MORE_POS_TOPK, 'pre_nms_topk_train': cfg.MODEL.CENTERNET.PRE_NMS_TOPK_TRAIN, 'pre_nms_topk_test': cfg.MODEL.CENTERNET.PRE_NMS_TOPK_TEST, 'post_nms_topk_train': cfg.MODEL.CENTERNET.POST_NMS_TOPK_TRAIN, 'post_nms_topk_test': cfg.MODEL.CENTERNET.POST_NMS_TOPK_TEST, 'nms_thresh_train': cfg.MODEL.CENTERNET.NMS_TH_TRAIN, 'nms_thresh_test': cfg.MODEL.CENTERNET.NMS_TH_TEST, 'no_reduce': cfg.MODEL.CENTERNET.NO_REDUCE, 'debug': cfg.DEBUG, 'vis_thresh': cfg.VIS_THRESH, 'pixel_mean': cfg.MODEL.PIXEL_MEAN, 'pixel_std': cfg.MODEL.PIXEL_STD, 'device': cfg.MODEL.DEVICE, 'centernet_head': CenterNetHead( cfg, [input_shape[f] for f in cfg.MODEL.CENTERNET.IN_FEATURES]), } return ret def forward(self, images, features_dict, gt_instances): features = [features_dict[f] for f in self.in_features] clss_per_level, reg_pred_per_level, agn_hm_pred_per_level = \ self.centernet_head(features) grids = self.compute_grids(features) shapes_per_level = grids[0].new_tensor( [(x.shape[2], x.shape[3]) for x in reg_pred_per_level]) if not self.training: return self.inference( images, clss_per_level, reg_pred_per_level, agn_hm_pred_per_level, grids) else: pos_inds, labels, reg_targets, flattened_hms = \ self._get_ground_truth( grids, shapes_per_level, gt_instances) # logits_pred: M x F, reg_pred: M x 4, agn_hm_pred: M logits_pred, reg_pred, agn_hm_pred = self._flatten_outputs( clss_per_level, reg_pred_per_level, agn_hm_pred_per_level) if self.more_pos: # add more pixels as positive if \ # 1. they are within the center3x3 region of an object # 2. their regression losses are small (<self.more_pos_thresh) pos_inds, labels = self._add_more_pos( reg_pred, gt_instances, shapes_per_level) losses = self.losses( pos_inds, labels, reg_targets, flattened_hms, logits_pred, reg_pred, agn_hm_pred) proposals = None if self.only_proposal: agn_hm_pred_per_level = [x.sigmoid() for x in agn_hm_pred_per_level] proposals = self.predict_instances( grids, agn_hm_pred_per_level, reg_pred_per_level, images.image_sizes, [None for _ in agn_hm_pred_per_level]) elif self.as_proposal: # category specific bbox as agnostic proposals clss_per_level = [x.sigmoid() for x in clss_per_level] proposals = self.predict_instances( grids, clss_per_level, reg_pred_per_level, images.image_sizes, agn_hm_pred_per_level) if self.only_proposal or self.as_proposal: for p in range(len(proposals)): proposals[p].proposal_boxes = proposals[p].get('pred_boxes') proposals[p].objectness_logits = proposals[p].get('scores') proposals[p].remove('pred_boxes') proposals[p].remove('scores') proposals[p].remove('pred_classes') if self.debug: debug_train( [self.denormalizer(x) for x in images], gt_instances, flattened_hms, reg_targets, labels, pos_inds, shapes_per_level, grids, self.strides) return proposals, losses def losses( self, pos_inds, labels, reg_targets, flattened_hms, logits_pred, reg_pred, agn_hm_pred): ''' Inputs: pos_inds: N labels: N reg_targets: M x 4 flattened_hms: M x C logits_pred: M x C reg_pred: M x 4 agn_hm_pred: M x 1 or None N: number of positive locations in all images M: number of pixels from all FPN levels C: number of classes ''' assert (torch.isfinite(reg_pred).all().item()) num_pos_local = pos_inds.numel() num_gpus = get_world_size() if self.no_reduce: total_num_pos = num_pos_local * num_gpus else:
total_num_pos = reduce_sum(
6
2023-11-09 14:31:48+00:00
12k
OpenBMB/ProAgent
main.py
[ { "identifier": "mock_function_call_list", "path": "mock_agent.py", "snippet": "" }, { "identifier": "logger", "path": "ProAgent/loggers/logs.py", "snippet": "class JsonFileHandler(logging.FileHandler):\nclass JsonFormatter(logging.Formatter):\nclass Logger(metaclass=Singleton):\nclass T...
import hydra import omegaconf import logging import json from colorama import Fore, Style from mock_agent import mock_function_call_list from ProAgent.loggers.logs import logger from ProAgent.n8n_parser.compiler import Compiler from ProAgent.handler.ReACT import ReACTHandler from ProAgent.utils import userQuery from ProAgent.running_recorder import RunningRecoder
8,412
@hydra.main(config_path="ProAgent/configs", config_name="generate_n8n_query") def main(cfg: omegaconf.DictConfig): """ The main function that runs the ReACTHandler. Args: cfg (omegaconf.DictConfig): The configuration object. Returns: None """ recorder = RunningRecoder() record_dir = None record_dir = "./apa_case" if record_dir != None: recorder.load_from_disk(record_dir, cfg) # commercial
@hydra.main(config_path="ProAgent/configs", config_name="generate_n8n_query") def main(cfg: omegaconf.DictConfig): """ The main function that runs the ReACTHandler. Args: cfg (omegaconf.DictConfig): The configuration object. Returns: None """ recorder = RunningRecoder() record_dir = None record_dir = "./apa_case" if record_dir != None: recorder.load_from_disk(record_dir, cfg) # commercial
query = userQuery(
4
2023-11-03 01:20:14+00:00
12k
LLaVA-VL/LLaVA-Plus-Codebase
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-11-07 13:06:02+00:00
12k
TheFunny/ArisuAutoSweeper
module/webui/updater.py
[ { "identifier": "ExecutionError", "path": "deploy/Windows/config.py", "snippet": "class ExecutionError(Exception):\n pass" }, { "identifier": "GitManager", "path": "deploy/Windows/git.py", "snippet": "class GitManager(DeployConfig):\n @staticmethod\n def remove(file):\n t...
import datetime import subprocess import threading import time import requests from typing import Generator, List, Tuple from deploy.Windows.config import ExecutionError from deploy.Windows.git import GitManager from deploy.Windows.pip import PipManager from deploy.Windows.utils import DEPLOY_CONFIG from module.base.retry import retry from module.logger import logger from module.webui.config import DeployConfig from module.webui.process_manager import ProcessManager from module.webui.setting import State from module.webui.utils import TaskHandler, get_next_time from module.webui.app import clearup
7,825
logger.info("No update") return 0 try: get_commit = requests.get( base + f"{owner}/{repo}/commits/" + local_sha, headers=headers, params=para, ) except Exception as e: logger.exception(e) logger.warning("Check update failed") return 0 if get_commit.status_code != 200: # for develops logger.info( f"Cannot find local commit {local_sha[:8]} in upstream, skip update" ) return 0 logger.info(f"Update {sha[:8]} available") return 1 def check_update(self): if self.state in (0, "failed", "finish"): self.state = self._check_update() @retry(ExecutionError, tries=3, delay=5, logger=None) def git_install(self): return super().git_install() @retry(ExecutionError, tries=3, delay=5, logger=None) def pip_install(self): return super().pip_install() def update(self): logger.hr("Run update") self.set_repo() try: self.git_install() self.pip_install() except ExecutionError: return False return True def run_update(self): if self.state not in ("failed", 0, 1): return self._start_update() def _start_update(self): self.state = "start" instances = ProcessManager.running_instances() names = [] for alas in instances: names.append(alas.config_name + "\n") logger.info("Waiting all running alas finish.") self._wait_update(instances, names) def _wait_update(self, instances: List[ProcessManager], names): if self.state == "cancel": self.state = 1 self.state = "wait" self.event.set() _instances = instances.copy() start_time = time.time() while _instances: for alas in _instances: if not alas.alive: _instances.remove(alas) logger.info(f"Alas [{alas.config_name}] stopped") logger.info(f"Remains: {[alas.config_name for alas in _instances]}") if self.state == "cancel": self.state = 1 self.event.clear() ProcessManager.restart_processes(instances, self.event) return time.sleep(0.25) if time.time() - start_time > 60 * 10: logger.warning("Waiting alas shutdown timeout, force kill") for alas in _instances: alas.stop() break self._run_update(instances, names) def _run_update(self, instances, names): self.state = "run update" logger.info("All alas stopped, start updating") if self.update(): if State.restart_event is not None: self.state = "reload" with open("./config/reloadalas", mode="w") as f: f.writelines(names) self._trigger_reload(2) clearup() else: self.state = "finish" else: self.state = "failed" logger.warning("Update failed") self.event.clear() ProcessManager.restart_processes(instances, self.event) return False @staticmethod def _trigger_reload(delay=2): def trigger(): # with open("./config/reloadflag", mode="w"): # # app ended here and uvicorn will restart whole app # pass State.restart_event.set() timer = threading.Timer(delay, trigger) timer.start() def schedule_update(self) -> Generator:
class Updater(DeployConfig, GitManager, PipManager): def __init__(self, file=DEPLOY_CONFIG): super().__init__(file=file) self.set_repo() self.state = 0 self.event: threading.Event = None @property def delay(self): self.read() return int(self.CheckUpdateInterval) * 60 @property def schedule_time(self): self.read() t = self.AutoRestartTime if t is not None: return datetime.time.fromisoformat(t) else: return None def execute_output(self, command) -> str: command = command.replace(r"\\", "/").replace("\\", "/").replace('"', '"') log = subprocess.run( command, capture_output=True, text=True, encoding="utf8", shell=True ).stdout return log def get_commit(self, revision="", n=1, short_sha1=False) -> Tuple: """ Return: (sha1, author, isotime, message,) """ ph = "h" if short_sha1 else "H" log = self.execute_output( f'"{self.git}" log {revision} --pretty=format:"%{ph}---%an---%ad---%s" --date=iso -{n}' ) if not log: return None, None, None, None logs = log.split("\n") logs = list(map(lambda log: tuple(log.split("---")), logs)) if n == 1: return logs[0] else: return logs def _check_update(self) -> bool: self.state = "checking" # if State.deploy_config.GitOverCdn: # status = self.goc_client.get_status() # if status == "uptodate": # logger.info(f"No update") # return False # elif status == "behind": # logger.info(f"New update available") # return True # else: # # failed, should fallback to `git pull` # pass source = "origin" for _ in range(3): if self.execute( f'"{self.git}" fetch {source} {self.Branch}', allow_failure=True ): break else: logger.warning("Git fetch failed") return False log = self.execute_output( f'"{self.git}" log --not --remotes={source}/* -1 --oneline' ) if log: logger.info( f"Cannot find local commit {log.split()[0]} in upstream, skip update" ) return False sha1, _, _, message = self.get_commit(f"..{source}/{self.Branch}") if sha1: logger.info(f"New update available") logger.info(f"{sha1[:8]} - {message}") return True else: logger.info(f"No update") return False def _check_update_(self) -> bool: """ Deprecated """ self.state = "checking" r = self.Repository.split("/") owner = r[3] repo = r[4] if "gitee" in r[2]: base = "https://gitee.com/api/v5/repos/" headers = {} token = self.config["ApiToken"] if token: para = {"access_token": token} else: base = "https://api.github.com/repos/" headers = {"Accept": "application/vnd.github.v3.sha"} para = {} token = self.config["ApiToken"] if token: headers["Authorization"] = "token " + token try: list_commit = requests.get( base + f"{owner}/{repo}/branches/{self.Branch}", headers=headers, params=para, ) except Exception as e: logger.exception(e) logger.warning("Check update failed") return 0 if list_commit.status_code != 200: logger.warning(f"Check update failed, code {list_commit.status_code}") return 0 try: sha = list_commit.json()["commit"]["sha"] except Exception as e: logger.exception(e) logger.warning("Check update failed when parsing return json") return 0 local_sha, _, _, _ = self._get_local_commit() if sha == local_sha: logger.info("No update") return 0 try: get_commit = requests.get( base + f"{owner}/{repo}/commits/" + local_sha, headers=headers, params=para, ) except Exception as e: logger.exception(e) logger.warning("Check update failed") return 0 if get_commit.status_code != 200: # for develops logger.info( f"Cannot find local commit {local_sha[:8]} in upstream, skip update" ) return 0 logger.info(f"Update {sha[:8]} available") return 1 def check_update(self): if self.state in (0, "failed", "finish"): self.state = self._check_update() @retry(ExecutionError, tries=3, delay=5, logger=None) def git_install(self): return super().git_install() @retry(ExecutionError, tries=3, delay=5, logger=None) def pip_install(self): return super().pip_install() def update(self): logger.hr("Run update") self.set_repo() try: self.git_install() self.pip_install() except ExecutionError: return False return True def run_update(self): if self.state not in ("failed", 0, 1): return self._start_update() def _start_update(self): self.state = "start" instances = ProcessManager.running_instances() names = [] for alas in instances: names.append(alas.config_name + "\n") logger.info("Waiting all running alas finish.") self._wait_update(instances, names) def _wait_update(self, instances: List[ProcessManager], names): if self.state == "cancel": self.state = 1 self.state = "wait" self.event.set() _instances = instances.copy() start_time = time.time() while _instances: for alas in _instances: if not alas.alive: _instances.remove(alas) logger.info(f"Alas [{alas.config_name}] stopped") logger.info(f"Remains: {[alas.config_name for alas in _instances]}") if self.state == "cancel": self.state = 1 self.event.clear() ProcessManager.restart_processes(instances, self.event) return time.sleep(0.25) if time.time() - start_time > 60 * 10: logger.warning("Waiting alas shutdown timeout, force kill") for alas in _instances: alas.stop() break self._run_update(instances, names) def _run_update(self, instances, names): self.state = "run update" logger.info("All alas stopped, start updating") if self.update(): if State.restart_event is not None: self.state = "reload" with open("./config/reloadalas", mode="w") as f: f.writelines(names) self._trigger_reload(2) clearup() else: self.state = "finish" else: self.state = "failed" logger.warning("Update failed") self.event.clear() ProcessManager.restart_processes(instances, self.event) return False @staticmethod def _trigger_reload(delay=2): def trigger(): # with open("./config/reloadflag", mode="w"): # # app ended here and uvicorn will restart whole app # pass State.restart_event.set() timer = threading.Timer(delay, trigger) timer.start() def schedule_update(self) -> Generator:
th: TaskHandler
9
2023-11-01 07:09:45+00:00
12k
liuzhao1225/YouDub
main.py
[ { "identifier": "TTS_Clone", "path": "youdub/tts_xttsv2.py", "snippet": "class TTS_Clone:\n def __init__(self, model_path=\"tts_models/multilingual/multi-dataset/xtts_v2\", device='cuda', language='zh-cn'):\n logging.info(f'Loading TTS model {model_path}...')\n self.tts = TTS(model_path...
import os import logging import json import re import time import numpy as np import re import argparse from tqdm import tqdm from youdub.tts_xttsv2 import TTS_Clone, audio_process_folder from youdub.tts_bytedance import TTS_Clone as TTS_Clone_bytedance from youdub.tts_bytedance import audio_process_folder as audio_process_folder_bytedance from youdub.asr_whisperX import VideoProcessor from youdub.video_postprocess import replace_audio_ffmpeg from youdub.translation_unsafe import Translator from youdub.utils import split_text from multiprocessing import Process
9,359
# from youdub.tts_bytedance import TTS_Clone as TTS_Clone_bytedance, audio_process_folder as audio_process_folder_bytedance allowed_chars = '[^a-zA-Z0-9_ .]' def translate_from_folder(folder, translator: Translator, original_fname): with open(os.path.join(folder, 'en.json'), mode='r', encoding='utf-8') as f: transcript = json.load(f) _transcript = [sentence['text'] for sentence in transcript if sentence['text']] result = [''] while len(result) != len(_transcript): result, summary = translator.translate(_transcript, original_fname) for i, sentence in enumerate(result): transcript[i]['text'] = sentence transcript = split_text(transcript) # 使用whisperX后,会自动分句,所以不再需要手动分句。同时避免了将`“你好。”`分为`“你好。`和`”`的情况 with open(os.path.join(folder, 'zh.json'), 'w', encoding='utf-8') as f: json.dump(transcript, f, ensure_ascii=False, indent=4) with open(os.path.join(folder, 'summary.txt'), 'w', encoding='utf-8') as f: f.write(summary) # def main(input_folder, output_folder, diarize=False): def main(): parser = argparse.ArgumentParser(description='Process some videos.') parser.add_argument('--input_folders', type=str, nargs='+', required=True, help='The list of input folders containing the videos') parser.add_argument('--output_folders', type=str, nargs='+', required=True, help='The list of output folders where the processed videos will be stored') parser.add_argument('--vocal_only_folders', type=str, nargs='+', default=[], help='The list of input folders containing the videos that only need vocal for the final result.') parser.add_argument('--diarize', action='store_true', help='Enable diarization') args = parser.parse_args() if len(args.input_folders) != len(args.output_folders): raise ValueError( "The number of input folders must match the number of output folders.") print('='*50) print('Initializing...') if args.diarize: print('Diarization enabled.') print('='*50) diarize = args.diarize processor = VideoProcessor(diarize=diarize) translator = Translator() tts = TTS_Clone() tts_bytedance = TTS_Clone_bytedance() for input_folder, output_folder in zip(args.input_folders, args.output_folders): if input_folder in args.vocal_only_folders: vocal_only = True print(f'Vocal only mode enabled for {input_folder}.') else: vocal_only = False if not os.path.exists(os.path.join(input_folder, '0_finished')): os.makedirs(os.path.join(input_folder, '0_finished')) if not os.path.exists(output_folder): os.makedirs(output_folder) if not os.path.exists(os.path.join(output_folder, '0_to_upload')): os.makedirs(os.path.join(output_folder, '0_to_upload')) if not os.path.exists(os.path.join(output_folder, '0_finished')): os.makedirs(os.path.join(output_folder, '0_finished')) print('='*50) print( f'Video processing started for {input_folder} to {output_folder}.') print('='*50) logging.info('Processing folder...') files = os.listdir(input_folder) t = tqdm(files, desc="Processing files") video_lists = [] for file in t: print('='*50) t.set_description(f"Processing {file}") print('='*50) if file.endswith('.mp4') or file.endswith('.mkv') or file.endswith('.avi') or file.endswith('.flv'): original_fname = file[:-4] new_filename = re.sub(r'[^a-zA-Z0-9_. ]', '', file) new_filename = re.sub(r'\s+', ' ', new_filename) new_filename = new_filename.strip() os.rename(os.path.join(input_folder, file), os.path.join(input_folder, new_filename)) file = new_filename video_lists.append(file) input_path = os.path.join(input_folder, file) output_path = os.path.join(output_folder, file[:-4]).strip() if not os.path.exists(output_path): os.makedirs(output_path) speaker_to_voice_type = processor.process_video( input_path, output_path) else: continue if not os.path.exists(os.path.join(output_path, 'zh.json')): translate_from_folder(output_path, translator, original_fname) if len(speaker_to_voice_type) == 1: print('Only one speaker detected. Using TTS.')
# from youdub.tts_bytedance import TTS_Clone as TTS_Clone_bytedance, audio_process_folder as audio_process_folder_bytedance allowed_chars = '[^a-zA-Z0-9_ .]' def translate_from_folder(folder, translator: Translator, original_fname): with open(os.path.join(folder, 'en.json'), mode='r', encoding='utf-8') as f: transcript = json.load(f) _transcript = [sentence['text'] for sentence in transcript if sentence['text']] result = [''] while len(result) != len(_transcript): result, summary = translator.translate(_transcript, original_fname) for i, sentence in enumerate(result): transcript[i]['text'] = sentence transcript = split_text(transcript) # 使用whisperX后,会自动分句,所以不再需要手动分句。同时避免了将`“你好。”`分为`“你好。`和`”`的情况 with open(os.path.join(folder, 'zh.json'), 'w', encoding='utf-8') as f: json.dump(transcript, f, ensure_ascii=False, indent=4) with open(os.path.join(folder, 'summary.txt'), 'w', encoding='utf-8') as f: f.write(summary) # def main(input_folder, output_folder, diarize=False): def main(): parser = argparse.ArgumentParser(description='Process some videos.') parser.add_argument('--input_folders', type=str, nargs='+', required=True, help='The list of input folders containing the videos') parser.add_argument('--output_folders', type=str, nargs='+', required=True, help='The list of output folders where the processed videos will be stored') parser.add_argument('--vocal_only_folders', type=str, nargs='+', default=[], help='The list of input folders containing the videos that only need vocal for the final result.') parser.add_argument('--diarize', action='store_true', help='Enable diarization') args = parser.parse_args() if len(args.input_folders) != len(args.output_folders): raise ValueError( "The number of input folders must match the number of output folders.") print('='*50) print('Initializing...') if args.diarize: print('Diarization enabled.') print('='*50) diarize = args.diarize processor = VideoProcessor(diarize=diarize) translator = Translator() tts = TTS_Clone() tts_bytedance = TTS_Clone_bytedance() for input_folder, output_folder in zip(args.input_folders, args.output_folders): if input_folder in args.vocal_only_folders: vocal_only = True print(f'Vocal only mode enabled for {input_folder}.') else: vocal_only = False if not os.path.exists(os.path.join(input_folder, '0_finished')): os.makedirs(os.path.join(input_folder, '0_finished')) if not os.path.exists(output_folder): os.makedirs(output_folder) if not os.path.exists(os.path.join(output_folder, '0_to_upload')): os.makedirs(os.path.join(output_folder, '0_to_upload')) if not os.path.exists(os.path.join(output_folder, '0_finished')): os.makedirs(os.path.join(output_folder, '0_finished')) print('='*50) print( f'Video processing started for {input_folder} to {output_folder}.') print('='*50) logging.info('Processing folder...') files = os.listdir(input_folder) t = tqdm(files, desc="Processing files") video_lists = [] for file in t: print('='*50) t.set_description(f"Processing {file}") print('='*50) if file.endswith('.mp4') or file.endswith('.mkv') or file.endswith('.avi') or file.endswith('.flv'): original_fname = file[:-4] new_filename = re.sub(r'[^a-zA-Z0-9_. ]', '', file) new_filename = re.sub(r'\s+', ' ', new_filename) new_filename = new_filename.strip() os.rename(os.path.join(input_folder, file), os.path.join(input_folder, new_filename)) file = new_filename video_lists.append(file) input_path = os.path.join(input_folder, file) output_path = os.path.join(output_folder, file[:-4]).strip() if not os.path.exists(output_path): os.makedirs(output_path) speaker_to_voice_type = processor.process_video( input_path, output_path) else: continue if not os.path.exists(os.path.join(output_path, 'zh.json')): translate_from_folder(output_path, translator, original_fname) if len(speaker_to_voice_type) == 1: print('Only one speaker detected. Using TTS.')
audio_process_folder_bytedance(
3
2023-11-02 08:21:31+00:00
12k
BrianPugh/cyclopts
tests/test_group_extractors.py
[ { "identifier": "App", "path": "cyclopts/core.py", "snippet": "class App:\n _name: Optional[Tuple[str, ...]] = field(default=None, alias=\"name\", converter=optional_to_tuple_converter)\n\n _help: Optional[str] = field(default=None, alias=\"help\")\n\n usage: Optional[str] = field(default=None)...
import pytest from cyclopts import App, Group, Parameter from cyclopts.group_extractors import groups_from_app
7,737
def test_groups_annotated_invalid_recursive_definition(): """A default_parameter isn't allowed to have a group set, as it would introduce a paradox.""" default_parameter = Parameter(group="Drink") # pyright: ignore[reportGeneralTypeIssues] with pytest.raises(ValueError): Group("Food", default_parameter=default_parameter) def test_groups_from_app_implicit(): def validator(**kwargs): pass
def test_groups_annotated_invalid_recursive_definition(): """A default_parameter isn't allowed to have a group set, as it would introduce a paradox.""" default_parameter = Parameter(group="Drink") # pyright: ignore[reportGeneralTypeIssues] with pytest.raises(ValueError): Group("Food", default_parameter=default_parameter) def test_groups_from_app_implicit(): def validator(**kwargs): pass
app = App(help_flags=[], version_flags=[])
0
2023-11-03 02:24:25+00:00
12k
RoboFlamingo/RoboFlamingo
robot_flamingo/data/data.py
[ { "identifier": "RealDatasetHDF5", "path": "robot_flamingo/data/real_dataset_hdf5.py", "snippet": "class RealDatasetHDF5(Dataset):\n def __init__(self,\n data_dir,\n image_fn,\n text_fn,\n seq_len=12,\n mode='train',\n ...
import ast import functools import io import json import logging import math import os import random import sys import tarfile import zipfile import braceexpand import torch import torchvision import webdataset as wds import numpy as np import numpy as np import pyhash import torch import horovod.torch as hvd import logging import numpy as np import pyhash import torch import pickle import torch.nn as nn import torch.nn.functional as F import copy from cgitb import text from dataclasses import dataclass from multiprocessing import Value from PIL import Image from torch.utils.data import DataLoader, IterableDataset, get_worker_info, Dataset from torch.utils.data.distributed import DistributedSampler from webdataset.filters import _shuffle from webdataset.tariterators import ( base_plus_ext, tar_file_expander, url_opener, valid_sample, ) from calvin_agent.datasets.utils.episode_utils import ( get_state_info_dict, process_actions, process_depth, process_language, process_rgb, process_state, ) from omegaconf import DictConfig from torch.utils.data import Dataset from robot_flamingo.data.real_dataset_hdf5 import RealDatasetHDF5 from pathlib import Path from typing import Dict, Tuple, Union from calvin_agent.datasets.utils.episode_utils import ( get_state_info_dict, process_actions, process_depth, # process_language, # process_rgb, process_state, ) from omegaconf import DictConfig from torch.utils.data import Dataset from robot_flamingo.data.vl_dataset import CaptionDataset, VQADataset from typing import Any, Dict, List, Tuple, Callable from itertools import chain from calvin_agent.datasets.utils.episode_utils import lookup_naming_pattern
8,811
coco_dataset, batch_size=args.batch_size_vl, pin_memory=False, num_workers=args.workers, prefetch_factor=3, sampler=sampler, persistent_workers=True, collate_fn=coco_dataset.collator, drop_last=True ) return dataloader def get_vqa_dataset(args, image_processor, tokenizer, epoch=0): vqa_data_dir = "path/to/vqav2/train2014" vqa_questions = "path/to/vqav2/v2_OpenEnded_mscoco_train2014_questions.json" vqa_ann = "path/to/vqav2/v2_mscoco_train2014_annotations.json" preprocess_text_fn = functools.partial(preprocess_text_calvin, tokenizer=tokenizer) vqa_dataset = VQADataset(vqa_data_dir, vqa_questions, vqa_ann, preprocess_text_fn, image_processor) sampler = DistributedSampler( vqa_dataset, num_replicas=args.world_size, rank=args.rank, shuffle=True, seed=args.seed, drop_last=True, ) dataloader = DataLoader( vqa_dataset, batch_size=args.batch_size_vl, pin_memory=False, num_workers=args.workers, prefetch_factor=3, sampler=sampler, persistent_workers=True, collate_fn=vqa_dataset.collator, drop_last=True ) return dataloader def get_calvin_dataset(args, image_processor, tokenizer, epoch=0, floor=False): dataset_path = args.calvin_dataset # ann is dict including language and info shared_epoch = SharedEpoch(epoch=epoch) preprocess_image_fn = functools.partial( preprocess_image, image_processor=image_processor ) preprocess_text_fn = functools.partial(preprocess_text_calvin, tokenizer=tokenizer) calvin_dataset = DiskCalvinDataset( datasets_dir=Path(dataset_path) / "training", image_fn=preprocess_image_fn, text_fn=preprocess_text_fn, window_size=args.window_size, rgb_pad=args.rgb_pad, gripper_pad=args.gripper_pad, traj_cons=args.traj_cons, text_aug=args.text_aug, dif_ws=args.dif_ws, min_window_size=args.min_window_size, max_window_size=args.max_window_size, act_step=args.multi_step_action, partial_data=args.partial_data ) round_fn = math.floor if floor else math.ceil num_samples = len(calvin_dataset) global_batch_size = args.batch_size_calvin * args.world_size num_batches = round_fn(num_samples / global_batch_size) num_workers = max(1, args.workers) num_worker_batches = round_fn(num_batches / num_workers) # per dataloader worker num_batches = num_worker_batches * num_workers num_samples = num_batches * global_batch_size sampler = DistributedSampler( calvin_dataset, num_replicas=args.world_size, rank=args.rank, shuffle=True, seed=args.seed, drop_last=True, ) # the batch_size and num_workers are per-GPU ! dataloader = DataLoader( calvin_dataset, batch_size=args.batch_size_calvin, pin_memory=False, num_workers=num_workers, prefetch_factor=3, sampler=sampler, persistent_workers=True, collate_fn=calvin_dataset.collater, drop_last=True ) # dataloader = DataLoader(calvin_dataset, batch_size=args.batch_size_calvin) # add meta-data to dataloader instance for convenience dataloader.num_batches = num_batches dataloader.num_samples = num_samples return DataInfo(dataloader=dataloader, shared_epoch=shared_epoch, sampler=sampler, dataset=calvin_dataset) def get_real_dataset(args, image_processor, tokenizer, epoch=0, floor=False): dataset_path = args.calvin_dataset # ann is dict including language and info shared_epoch = SharedEpoch(epoch=epoch) preprocess_image_fn = functools.partial( preprocess_image, image_processor=image_processor ) preprocess_text_fn = functools.partial(preprocess_text_calvin, tokenizer=tokenizer)
Image.MAX_IMAGE_PIXELS = 1000000000 MAX_NUM_TOKENS = 256 MAX_NUM_IMAGES = 5 TINY_IMAGE_SIZE_THRESHOLD = 1 N_CHANNELS = 3 INTERLEAVED_IMAGE_SIZE = 224 _SHARD_SHUFFLE_SIZE = 2000 _SHARD_SHUFFLE_INITIAL = 500 _SAMPLE_SHUFFLE_SIZE = 5000 _SAMPLE_SHUFFLE_INITIAL = 1000 MIN_KB = 10 MAX_NUM_IMAGES = 5 try: except ImportError: hvd = None hasher = pyhash.fnv1_32() logger = logging.getLogger(__name__) obs_config = DictConfig( { "rgb_obs": ["rgb_static", "rgb_gripper"], "depth_obs": [], "state_obs": ["robot_obs"], "actions": ["rel_actions"], "language": ["language"], } ) prop_state = DictConfig( { "n_state_obs": 15, "keep_indices": [[0, 15]], "robot_orientation_idx": [3, 6], "normalize": True, "normalize_robot_orientation": True, } ) def get_validation_window_size( idx: int, min_window_size: int, max_window_size: int ) -> int: """ In validation step, use hash function instead of random sampling for consistent window sizes across epochs. Args: idx: Sequence index. min_window_size: Minimum window size. max_window_size: Maximum window size. Returns: Window size computed with hash function. """ window_range = max_window_size - min_window_size + 1 return min_window_size + hasher(str(idx)) % window_range class RandomShiftsAug(nn.Module): def __init__(self, pad): super().__init__() self.pad = pad def forward(self, x): n, c, h, w = x.size() assert h == w padding = tuple([self.pad] * 4) x = F.pad(x, padding, 'replicate') eps = 1.0 / (h + 2 * self.pad) arange = torch.linspace(-1.0 + eps, 1.0 - eps, h + 2 * self.pad, device=x.device, dtype=x.dtype)[:h] arange = arange.unsqueeze(0).repeat(h, 1).unsqueeze(2) base_grid = torch.cat([arange, arange.transpose(1, 0)], dim=2) base_grid = base_grid.unsqueeze(0).repeat(n, 1, 1, 1) shift = torch.randint(0, 2 * self.pad + 1, size=(n, 1, 1, 2), device=x.device, dtype=x.dtype) shift *= 2.0 / (h + 2 * self.pad) grid = base_grid + shift return F.grid_sample(x, grid, padding_mode='zeros', align_corners=False) def forward_traj(self, x): n, t, c, h, w = x.size() x = x.view(n*t, *x.shape[2:]) assert h == w padding = tuple([self.pad] * 4) x = F.pad(x, padding, 'replicate') eps = 1.0 / (h + 2 * self.pad) arange = torch.linspace(-1.0 + eps, 1.0 - eps, h + 2 * self.pad, device=x.device, dtype=x.dtype)[:h] arange = arange.unsqueeze(0).repeat(h, 1).unsqueeze(2) base_grid = torch.cat([arange, arange.transpose(1, 0)], dim=2) base_grid = base_grid.unsqueeze(0).repeat(n, 1, 1, 1) base_grid = base_grid.unsqueeze(1).repeat(1, t, 1, 1, 1) base_grid = base_grid.view(n*t, *base_grid.shape[2:]) shift = torch.randint(1, 2 * self.pad + 1, size=(n*t, 1, 1, 2), device=x.device, dtype=x.dtype) shift *= 2.0 / (h + 2 * self.pad) grid = base_grid + shift x = F.grid_sample(x, grid, padding_mode='zeros', align_corners=False) x = x.view(n, t, *x.shape[1:]) return x class BaseCalvinDataset(Dataset): """ Abstract dataset base class. Args: datasets_dir: Path of folder containing episode files (string must contain 'validation' or 'training'). obs_space: DictConfig of observation space. proprio_state: DictConfig with shape of prioprioceptive state. key: 'vis' or 'lang'. lang_folder: Name of the subdirectory of the dataset containing the language annotations. num_workers: Number of dataloading workers for this dataset. transforms: Dict with pytorch data transforms. batch_size: Batch size. min_window_size: Minimum window length of loaded sequences. max_window_size: Maximum window length of loaded sequences. pad: If True, repeat last frame such that all sequences have length 'max_window_size'. aux_lang_loss_window: How many sliding windows to consider for auxiliary language losses, counted from the end of an annotated language episode. """ def __init__( self, datasets_dir: Path, proprio_state: DictConfig = prop_state, lang_folder: str = "lang_annotations", num_workers: int = 0, key: str = "lang", obs_space: DictConfig = obs_config, transforms: Dict = {}, batch_size: int = 32, window_size: int = 16, min_window_size: int = 16, max_window_size: int = 16, pad: bool = True, aux_lang_loss_window: int = 1, rgb_pad=-1, gripper_pad=-1, traj_cons=False, text_aug=False, dif_ws=False, act_step=1 ): self.observation_space = obs_space self.proprio_state = proprio_state self.transforms = transforms self.with_lang = key == "lang" self.relative_actions = "rel_actions" in self.observation_space["actions"] self.pad = pad self.batch_size = batch_size self.num_workers = num_workers self.window_size = window_size if not dif_ws: self.min_window_size = window_size + act_step - 1 self.max_window_size = window_size + act_step - 1 else: self.min_window_size = min_window_size self.max_window_size = max_window_size self.act_step = act_step # print('ws {}, min_ws {}, max_ws {}'.format(self.window_size, self.max_window_size, self.min_window_size)) self.abs_datasets_dir = datasets_dir self.lang_folder = lang_folder # if self.with_lang else None self.aux_lang_loss_window = aux_lang_loss_window self.traj_cons = traj_cons with open('/mnt/bn/robotics/lxh/robot-flamingo/enrich_lang_annotations.json', 'r') as f: self.enrich_lang = json.load(f) self.text_aug = text_aug self.rgb_pad = rgb_pad if self.rgb_pad != -1: self.rgb_shift = RandomShiftsAug(rgb_pad) self.gripper_pad = gripper_pad if self.gripper_pad != -1: self.gripper_shift = RandomShiftsAug(gripper_pad) assert ( "validation" in self.abs_datasets_dir.as_posix() or "training" in self.abs_datasets_dir.as_posix() ) self.validation = "validation" in self.abs_datasets_dir.as_posix() assert self.abs_datasets_dir.is_dir() logger.info(f"loading dataset at {self.abs_datasets_dir}") logger.info("finished loading dataset") def process_rgb( self, episode: Dict[str, np.ndarray], observation_space: DictConfig, transforms: Dict, seq_idx: int = 0, window_size: int = 0, ) -> Dict[str, Dict[str, torch.Tensor]]: rgb_obs_keys = observation_space["rgb_obs"] seq_rgb_obs_dict = {} for _, rgb_obs_key in enumerate(rgb_obs_keys): rgb_obs = episode[rgb_obs_key] # expand dims for single environment obs if len(rgb_obs.shape) != 4: rgb_obs = np.expand_dims(rgb_obs, axis=0) assert len(rgb_obs.shape) == 4 if window_size == 0 and seq_idx == 0: # single file loader # To Square image seq_rgb_obs_ = torch.from_numpy(rgb_obs).byte() else: # episode loader seq_rgb_obs_ = torch.from_numpy( rgb_obs[seq_idx : seq_idx + window_size] ).byte() if rgb_obs_key in transforms: seq_rgb_obs_ = transforms[rgb_obs_key](seq_rgb_obs_) seq_rgb_obs_dict[rgb_obs_key] = seq_rgb_obs_ # shape: N_rgb_obs x (BxHxWxC) return {"rgb_obs": seq_rgb_obs_dict} def process_language( self, episode: Dict[str, np.ndarray], transforms: Dict, with_lang: bool ): return {"lang": episode["language"]} def __getitem__(self, idx: Union[int, Tuple[int, int]], fixed_seed=False) -> Dict: """ Get sequence of dataset. Args: idx: Index of the sequence. Returns: Loaded sequence. """ if isinstance(idx, int): # When max_ws_size and min_ws_size are equal, avoid unnecessary padding # acts like Constant dataset. Currently, used for language data if self.min_window_size == self.max_window_size: window_size = self.max_window_size elif self.min_window_size < self.max_window_size: window_size = self._get_window_size(idx) else: logger.error( f"min_window_size {self.min_window_size} > max_window_size {self.max_window_size}" ) raise ValueError else: idx, window_size = idx head = False sequence = self._get_sequences(idx, window_size, head=head) if self.pad: pad_size = self._get_pad_size(sequence) sequence = self._pad_sequence(sequence, pad_size, head=head) new_list = [] np_rgb = copy.deepcopy(sequence["rgb_obs"]["rgb_static"].numpy()) for i in range(np_rgb.shape[0]): new_list.append(Image.fromarray(np_rgb[i, :, :, :].astype(np.uint8))) sequence["rgb_obs"]["rgb_static"] = new_list new_list = [] np_gripper = copy.deepcopy(sequence["rgb_obs"]["rgb_gripper"].numpy()) for i in range(np_gripper.shape[0]): new_list.append(Image.fromarray(np_gripper[i, :, :, :].astype(np.uint8))) sequence["rgb_obs"]["rgb_gripper"] = new_list # print(pad_size, len(new_list)) return sequence def _get_sequences(self, idx: int, window_size: int, head: bool=False) -> Dict: """ Load sequence of length window_size. Args: idx: Index of starting frame. window_size: Length of sampled episode. Returns: dict: Dictionary of tensors of loaded sequence with different input modalities and actions. """ episode = self._load_episode(idx, window_size) seq_state_obs = process_state( episode, self.observation_space, self.transforms, self.proprio_state ) seq_rgb_obs = self.process_rgb(episode, self.observation_space, self.transforms) seq_depth_obs = process_depth(episode, self.observation_space, self.transforms) seq_acts = process_actions(episode, self.observation_space, self.transforms) info = get_state_info_dict(episode) seq_lang = self.process_language(episode, self.transforms, self.with_lang) info = self._add_language_info(info, idx) seq_dict = { **seq_state_obs, **seq_rgb_obs, **seq_depth_obs, **seq_acts, **info, **seq_lang, } # type:ignore seq_dict["idx"] = idx # type:ignore return seq_dict def _load_episode(self, idx: int, window_size: int) -> Dict[str, np.ndarray]: raise NotImplementedError def _get_window_size(self, idx: int) -> int: """ Sample a window size taking into account the episode limits. Args: idx: Index of the sequence to load. Returns: Window size. """ window_diff = self.max_window_size - self.min_window_size if len(self.episode_lookup) <= idx + window_diff: # last episode max_window = self.min_window_size + len(self.episode_lookup) - idx - 1 elif ( self.episode_lookup[idx + window_diff] != self.episode_lookup[idx] + window_diff ): # less than max_episode steps until next episode steps_to_next_episode = int( np.nonzero( self.episode_lookup[idx : idx + window_diff + 1] - (self.episode_lookup[idx] + np.arange(window_diff + 1)) )[0][0] ) max_window = min( self.max_window_size, (self.min_window_size + steps_to_next_episode - 1) ) else: max_window = self.max_window_size if self.validation: # in validation step, repeat the window sizes for each epoch. return get_validation_window_size(idx, self.min_window_size, max_window) else: return np.random.randint(self.min_window_size, max_window + 1) def __len__(self) -> int: """ Returns: Size of the dataset. """ return len(self.episode_lookup) def _get_pad_size(self, sequence: Dict) -> int: """ Determine how many frames to append to end of the sequence Args: sequence: Loaded sequence. Returns: Number of frames to pad. """ return self.max_window_size - len(sequence["actions"]) def _pad_sequence(self, seq: Dict, pad_size: int, head: bool=False) -> Dict: """ Pad a sequence by repeating the last frame. Args: seq: Sequence to pad. pad_size: Number of frames to pad. Returns: Padded sequence. """ seq.update({"robot_obs": self._pad_with_repetition(seq["robot_obs"], pad_size)}) seq.update( { "rgb_obs": { k: self._pad_with_repetition(v, pad_size, head) for k, v in seq["rgb_obs"].items() } } ) seq.update( { "depth_obs": { k: self._pad_with_repetition(v, pad_size, head) for k, v in seq["depth_obs"].items() } } ) # todo: find better way of distinguishing rk and play action spaces if not self.relative_actions: if head: seq_acts = self._pad_with_zeros(seq["actions"], pad_size, head) else: # repeat action for world coordinates action space seq.update({"actions": self._pad_with_repetition(seq["actions"], pad_size, head)}) else: # for relative actions zero pad all but the last action dims and repeat last action dim (gripper action) if head: seq_acts = self._pad_with_zeros(seq["actions"], pad_size, head) else: seq_acts = torch.cat( [ self._pad_with_zeros(seq["actions"][..., :-1], pad_size, head), self._pad_with_repetition(seq["actions"][..., -1:], pad_size, head), ], dim=-1, ) seq.update({"actions": seq_acts}) seq.update( { "state_info": { k: self._pad_with_repetition(v, pad_size, head) for k, v in seq["state_info"].items() } } ) return seq @staticmethod def _pad_with_repetition(input_tensor: torch.Tensor, pad_size: int, head: bool = False) -> torch.Tensor: """ Pad a sequence Tensor by repeating last element pad_size times. Args: input_tensor: Sequence to pad. pad_size: Number of frames to pad. Returns: Padded Tensor. """ if head: last_repeated = torch.repeat_interleave( torch.unsqueeze(input_tensor[0], dim=0), repeats=pad_size, dim=0 ) padded = torch.vstack((last_repeated, input_tensor)) else: last_repeated = torch.repeat_interleave( torch.unsqueeze(input_tensor[-1], dim=0), repeats=pad_size, dim=0 ) padded = torch.vstack((input_tensor, last_repeated)) return padded @staticmethod def _pad_with_zeros(input_tensor: torch.Tensor, pad_size: int, head: bool = False) -> torch.Tensor: """ Pad a Tensor with zeros. Args: input_tensor: Sequence to pad. pad_size: Number of frames to pad. Returns: Padded Tensor. """ zeros_repeated = torch.repeat_interleave( torch.unsqueeze(torch.zeros(input_tensor.shape[-1]), dim=0), repeats=pad_size, dim=0, ) if head: padded = torch.vstack((zeros_repeated, input_tensor)) else: padded = torch.vstack((input_tensor, zeros_repeated)) return padded def _add_language_info(self, info: Dict, idx: int) -> Dict: """ If dataset contains language, add info to determine if this sequence will be used for the auxiliary losses. Args: info: Info dictionary. idx: Sequence index. Returns: Info dictionary with updated information. """ if not self.with_lang: return info use_for_aux_lang_loss = ( idx + self.aux_lang_loss_window >= len(self.lang_lookup) or self.lang_lookup[idx] < self.lang_lookup[idx + self.aux_lang_loss_window] ) info["use_for_aux_lang_loss"] = use_for_aux_lang_loss return info class DebugDataset(Dataset): def __init__(self, **kwargs: Any,): super().__init__() def __len__(self) -> int: return 10000 def __getitem__(self, index): window_size = 8 rgb = torch.randn(window_size, 3, 200, 200) gripper = torch.randn(window_size, 84, 84) state = torch.randn(window_size, 15) class DiskCalvinDataset(BaseCalvinDataset): """ Dataset that loads episodes as individual files from disk. Args: skip_frames: Skip this amount of windows for language dataset. save_format: File format in datasets_dir (pkl or npz). pretrain: Set to True when pretraining. """ def __init__( self, image_fn: Callable, text_fn: Callable, *args: Any, skip_frames: int = 1, save_format: str = "npz", pretrain: bool = False, partial_data=False, **kwargs: Any, ): super().__init__(*args, **kwargs) self.save_format = save_format self.image_fn = image_fn self.text_fn = text_fn self.partial_data = partial_data if self.save_format == "pkl": self.load_file = load_pkl elif self.save_format == "npz": self.load_file = load_npz else: raise NotImplementedError self.pretrain = pretrain self.skip_frames = skip_frames if self.with_lang: ( self.episode_lookup, self.lang_lookup, self.lang_ann, self.lang_task ) = self._build_file_indices_lang(self.abs_datasets_dir) else: self.episode_lookup = self._build_file_indices(self.abs_datasets_dir) self.naming_pattern, self.n_digits = lookup_naming_pattern( self.abs_datasets_dir, self.save_format ) def _get_episode_name(self, file_idx: int) -> Path: """ Convert file idx to file path. Args: file_idx: index of starting frame. Returns: Path to file. """ return Path( f"{self.naming_pattern[0]}{file_idx:0{self.n_digits}d}{self.naming_pattern[1]}" ) def _load_episode(self, idx: int, window_size: int) -> Dict[str, np.ndarray]: """ Load consecutive frames saved as individual files on disk and combine to episode dict. Args: idx: Index of first frame. window_size: Length of sampled episode. Returns: episode: Dict of numpy arrays containing the episode where keys are the names of modalities. """ start_idx = self.episode_lookup[idx] end_idx = start_idx + window_size keys = list(chain(*self.observation_space.values())) keys.remove("language") keys.append("scene_obs") episodes = [ self.load_file(self._get_episode_name(file_idx)) for file_idx in range(start_idx, end_idx) ] episode = {key: np.stack([ep[key] for ep in episodes]) for key in keys} if self.with_lang: episode["language"] = self.lang_ann[self.lang_lookup[idx]] if self.text_aug: task = self.lang_task[self.lang_lookup[idx]] enrich_lang = random.choice(self.enrich_lang[task] + [episode["language"]]) episode["language"] = enrich_lang return episode def _build_file_indices_lang( self, abs_datasets_dir: Path ): """ This method builds the mapping from index to file_name used for loading the episodes of the language dataset. Args: abs_datasets_dir: Absolute path of the directory containing the dataset. Returns: episode_lookup: Mapping from training example index to episode (file) index. lang_lookup: Mapping from training example to index of language instruction. lang_ann: Language embeddings. """ assert abs_datasets_dir.is_dir() episode_lookup = [] try: print( "trying to load lang data from: ", abs_datasets_dir / self.lang_folder / "auto_lang_ann.npy", ) lang_data = np.load( abs_datasets_dir / self.lang_folder / "auto_lang_ann.npy", allow_pickle=True, ).item() except Exception: print( "Exception, trying to load lang data from: ", abs_datasets_dir / "auto_lang_ann.npy", ) lang_data = np.load( abs_datasets_dir / "auto_lang_ann.npy", allow_pickle=True ).item() ep_start_end_ids = lang_data["info"]["indx"] # each of them are 64 lang_ann = lang_data["language"]["ann"] # length total number of annotations lang_task = lang_data["language"]["task"] lang_lookup = [] partial_st_ed_list = load_partial_traj_data() for i, (start_idx, end_idx) in enumerate(ep_start_end_ids): if self.partial_data: if (start_idx, end_idx) not in partial_st_ed_list: continue if self.pretrain: start_idx = max( start_idx, end_idx + 1 - self.min_window_size - self.aux_lang_loss_window, ) assert end_idx >= self.max_window_size cnt = 0 for idx in range(start_idx, end_idx + 1 - self.min_window_size): if cnt % self.skip_frames == 0: lang_lookup.append(i) episode_lookup.append(idx) cnt += 1 return np.array(episode_lookup), lang_lookup, lang_ann, lang_task def _build_file_indices(self, abs_datasets_dir: Path) -> np.ndarray: """ This method builds the mapping from index to file_name used for loading the episodes of the non language dataset. Args: abs_datasets_dir: Absolute path of the directory containing the dataset. Returns: episode_lookup: Mapping from training example index to episode (file) index. """ assert abs_datasets_dir.is_dir() episode_lookup = [] ep_start_end_ids = np.load(abs_datasets_dir / "ep_start_end_ids.npy") logger.info( f'Found "ep_start_end_ids.npy" with {len(ep_start_end_ids)} episodes.' ) for start_idx, end_idx in ep_start_end_ids: assert end_idx > self.max_window_size for idx in range(start_idx, end_idx + 1 - self.min_window_size): episode_lookup.append(idx) return np.array(episode_lookup) def collater(self, sample): action_tensors = torch.from_numpy(np.array([np.stack(s["actions"]) for s in sample])) state_tensors = torch.from_numpy(np.array([np.stack(s["robot_obs"]) for s in sample])) image_tensors = torch.stack([self.image_fn(s["rgb_obs"]["rgb_static"]) for s in sample]) gripper_tensors = torch.stack([self.image_fn(s["rgb_obs"]["rgb_gripper"]) for s in sample]) stacked_language = [s["lang"] for s in sample] text_tensors, attention_mask = self.text_fn(stacked_language) if self.rgb_pad != -1: bs, seq_len = image_tensors.shape[:2] if self.traj_cons: image_tensors = self.rgb_shift.forward_traj(image_tensors) else: image_tensors = image_tensors.view(bs*seq_len, *image_tensors.shape[2:]) image_tensors = self.rgb_shift(image_tensors) image_tensors = image_tensors.view(bs, seq_len, *image_tensors.shape[1:]) if self.gripper_pad != -1: bs, seq_len = gripper_tensors.shape[:2] if self.traj_cons: gripper_tensors = self.gripper_shift.forward_traj(gripper_tensors) else: gripper_tensors = gripper_tensors.view(bs * seq_len, *gripper_tensors.shape[2:]) gripper_tensors = self.gripper_shift(gripper_tensors) gripper_tensors = gripper_tensors.view(bs, seq_len, *gripper_tensors.shape[1:]) robot_obs = torch.zeros(1) if self.act_step != 1: actions = torch.zeros((action_tensors.shape[0], self.window_size, self.act_step, action_tensors.shape[-1])) for b in range(action_tensors.shape[0]): for ix in range(self.window_size): actions[b, ix] = action_tensors[b, ix:ix+self.act_step] robot_obs = torch.zeros((action_tensors.shape[0], self.window_size, self.act_step, state_tensors.shape[-1])) for b in range(action_tensors.shape[0]): for ix in range(self.window_size): robot_obs[b, ix] = state_tensors[b, ix:ix+self.act_step] robot_obs = torch.cat([robot_obs[..., :6], robot_obs[..., [-1]]], dim=-1) action_tensors = actions image_tensors = image_tensors[:, :-(self.act_step-1)] gripper_tensors = gripper_tensors[:, :-(self.act_step-1)] state_tensors = state_tensors[:, :-(self.act_step-1)] return image_tensors, (text_tensors, attention_mask), action_tensors, gripper_tensors, state_tensors, robot_obs class CalvinDataset(Dataset): """Naive implementation of dataset to store calvin debug dataset, may be changed to WDS for the full dataset """ def __init__(self, image_fn, text_fn, dataset_path, is_train=True) -> None: super().__init__() self.dataset_path = dataset_path self.image_fn = image_fn self.text_fn = text_fn tag = "training" if is_train else "validation" self.file_prefix = f"{self.dataset_path}/{tag}" self.anns = np.load( f"{self.file_prefix}/lang_annotations/auto_lang_ann.npy", allow_pickle=True ).item() def __len__(self): return len(self.anns["info"]["indx"]) def __getitem__(self, index): task = self.anns["language"]["task"][index] text = self.anns["language"]["ann"][index] st, ed = self.anns["info"]["indx"][index] # CJ: randomly sample a datapoint in the episode frame = random.randint(st, ed) frame = np.load( f"{self.file_prefix}/episode_{frame:07d}.npz" ) # , allow_pickle=True (lazy load) rgb_static = Image.fromarray(frame["rgb_static"]) rgb_gripper = Image.fromarray(frame["rgb_gripper"]) actions = np.array(frame["rel_actions"]) actions[..., 6:] = (actions[..., 6:] + 1) // 2 return rgb_static, text, actions def collater(self, sample): images = [s[0] for s in sample] texts = [s[1] for s in sample] actions = [s[2] for s in sample] image_tensors = self.image_fn(images) text_tensors = self.text_fn(texts) action_tensors = torch.FloatTensor(np.stack(actions)) return image_tensors, text_tensors, action_tensors def load_pkl(filename: Path) -> Dict[str, np.ndarray]: with open(filename, "rb") as f: return pickle.load(f) def load_npz(filename: Path) -> Dict[str, np.ndarray]: return np.load(filename.as_posix()) class SharedEpoch: def __init__(self, epoch: int = 0): self.shared_epoch = Value("i", epoch) def set_value(self, epoch): self.shared_epoch.value = epoch def get_value(self): return self.shared_epoch.value @dataclass class DataInfo: dataloader: DataLoader sampler: DistributedSampler = None shared_epoch: SharedEpoch = None dataset: Dataset = None def set_epoch(self, epoch): if self.shared_epoch is not None: self.shared_epoch.set_value(epoch) if self.sampler is not None and isinstance(self.sampler, DistributedSampler): self.sampler.set_epoch(epoch) def preprocess_image(sample, image_processor): image = [image_processor(s).unsqueeze(0) for s in sample] image = torch.cat(image, dim=0) # apply random horizontal flip and color jitter return image def preprocess_text_calvin(sample, tokenizer): tokenizer.padding_side = "right" sample = [ # (f"{s.strip()}{tokenizer.eos_token}") # for s in sample (f"<image>{s.strip()}<|endofchunk|>{tokenizer.eos_token}") for s in sample ] text = tokenizer( sample, max_length=32, padding="longest", truncation="only_first", return_tensors="pt", ) return text["input_ids"], text["attention_mask"] def preprocess_interleaved(sample, tokenizer, clip_processor, sim_threshold): info = json.loads(sample[0]) tar_file_obj = io.BytesIO(sample[1]) image_tar = tarfile.open(fileobj=tar_file_obj) sentences = info["text_list"] images, image_idxs = [], [] for image_path, sim in zip(info["image_info"], info["similarity_matrix"]): # pick one image per sentence if info["image_info"][image_path]["matched_text_index"] in image_idxs: continue rawbytes = image_tar.extractfile( os.path.join(image_tar.getnames()[0], image_path) ).read() # filter to images >= 10KB if len(rawbytes) // 1000 <= MIN_KB: continue if sim[info["image_info"][image_path]["matched_text_index"]] < sim_threshold: continue image = Image.open(io.BytesIO(rawbytes)).convert("RGB") images.append(image) image_idxs.append(info["image_info"][image_path]["matched_text_index"]) if len(images) == 0: raise ValueError("No images in sample") # filter out images that are exact duplicates images_tensors = preprocess_image(images, clip_processor) keep_ixs = range(min(len(images_tensors), MAX_NUM_IMAGES)) images_tensors = images_tensors[keep_ixs] image_idxs = [image_idxs[ix] for ix in keep_ixs] # pad to 5 images if len(images_tensors) < MAX_NUM_IMAGES: zero_padding = torch.zeros( (MAX_NUM_IMAGES - len(images_tensors), 3, 224, 224), dtype=torch.float ) images_tensors = torch.cat((images_tensors, zero_padding), dim=0) # add in <image> and <eoc> tokens # eoc after sentence = "sentence loss" for ix in image_idxs: sentences[ix] = f"<|endofchunk|><image>{sentences[ix]}" text = " ".join(sentences) text = text.replace("<|endofchunk|>", "", 1) # but remove first eoc # whitespace cleanup text = ( text.replace(" <|endofchunk|>", "<|endofchunk|>") .replace("<image> ", "<image>") .replace(" <image>", "<image>") ) text = f"{text}<|endofchunk|>{tokenizer.eos_token}" tokenizer.padding_side = "right" text_tensor = tokenizer( text, max_length=256, truncation=True, padding="max_length", return_tensors="pt" ) # reject sequences with too few images (after truncation) num_images = torch.count_nonzero( text_tensor["input_ids"] == tokenizer.additional_special_tokens_ids[ tokenizer.additional_special_tokens.index("<image>") ] ) if num_images == 0: raise ValueError("No images in sample") elif ( num_images == 1 and random.random() <= 0.5 ): # 50% chance of keeping single image samples raise ValueError("Only one image in sample") return ( images_tensors, (text_tensor["input_ids"], text_tensor["attention_mask"]), ) def get_coco_dataset(args, image_processor, tokenizer, epoch=0): coco_data_dir = "path/to/coco/train2014" coco_ann = "path/to/coco/annotations/captions_train2014.json" preprocess_text_fn = functools.partial(preprocess_text_calvin, tokenizer=tokenizer) coco_dataset = CaptionDataset(coco_data_dir, coco_ann, preprocess_text_fn, image_processor) sampler = DistributedSampler( coco_dataset, num_replicas=args.world_size, rank=args.rank, shuffle=True, seed=args.seed, drop_last=True, ) dataloader = DataLoader( coco_dataset, batch_size=args.batch_size_vl, pin_memory=False, num_workers=args.workers, prefetch_factor=3, sampler=sampler, persistent_workers=True, collate_fn=coco_dataset.collator, drop_last=True ) return dataloader def get_vqa_dataset(args, image_processor, tokenizer, epoch=0): vqa_data_dir = "path/to/vqav2/train2014" vqa_questions = "path/to/vqav2/v2_OpenEnded_mscoco_train2014_questions.json" vqa_ann = "path/to/vqav2/v2_mscoco_train2014_annotations.json" preprocess_text_fn = functools.partial(preprocess_text_calvin, tokenizer=tokenizer) vqa_dataset = VQADataset(vqa_data_dir, vqa_questions, vqa_ann, preprocess_text_fn, image_processor) sampler = DistributedSampler( vqa_dataset, num_replicas=args.world_size, rank=args.rank, shuffle=True, seed=args.seed, drop_last=True, ) dataloader = DataLoader( vqa_dataset, batch_size=args.batch_size_vl, pin_memory=False, num_workers=args.workers, prefetch_factor=3, sampler=sampler, persistent_workers=True, collate_fn=vqa_dataset.collator, drop_last=True ) return dataloader def get_calvin_dataset(args, image_processor, tokenizer, epoch=0, floor=False): dataset_path = args.calvin_dataset # ann is dict including language and info shared_epoch = SharedEpoch(epoch=epoch) preprocess_image_fn = functools.partial( preprocess_image, image_processor=image_processor ) preprocess_text_fn = functools.partial(preprocess_text_calvin, tokenizer=tokenizer) calvin_dataset = DiskCalvinDataset( datasets_dir=Path(dataset_path) / "training", image_fn=preprocess_image_fn, text_fn=preprocess_text_fn, window_size=args.window_size, rgb_pad=args.rgb_pad, gripper_pad=args.gripper_pad, traj_cons=args.traj_cons, text_aug=args.text_aug, dif_ws=args.dif_ws, min_window_size=args.min_window_size, max_window_size=args.max_window_size, act_step=args.multi_step_action, partial_data=args.partial_data ) round_fn = math.floor if floor else math.ceil num_samples = len(calvin_dataset) global_batch_size = args.batch_size_calvin * args.world_size num_batches = round_fn(num_samples / global_batch_size) num_workers = max(1, args.workers) num_worker_batches = round_fn(num_batches / num_workers) # per dataloader worker num_batches = num_worker_batches * num_workers num_samples = num_batches * global_batch_size sampler = DistributedSampler( calvin_dataset, num_replicas=args.world_size, rank=args.rank, shuffle=True, seed=args.seed, drop_last=True, ) # the batch_size and num_workers are per-GPU ! dataloader = DataLoader( calvin_dataset, batch_size=args.batch_size_calvin, pin_memory=False, num_workers=num_workers, prefetch_factor=3, sampler=sampler, persistent_workers=True, collate_fn=calvin_dataset.collater, drop_last=True ) # dataloader = DataLoader(calvin_dataset, batch_size=args.batch_size_calvin) # add meta-data to dataloader instance for convenience dataloader.num_batches = num_batches dataloader.num_samples = num_samples return DataInfo(dataloader=dataloader, shared_epoch=shared_epoch, sampler=sampler, dataset=calvin_dataset) def get_real_dataset(args, image_processor, tokenizer, epoch=0, floor=False): dataset_path = args.calvin_dataset # ann is dict including language and info shared_epoch = SharedEpoch(epoch=epoch) preprocess_image_fn = functools.partial( preprocess_image, image_processor=image_processor ) preprocess_text_fn = functools.partial(preprocess_text_calvin, tokenizer=tokenizer)
calvin_dataset = RealDatasetHDF5(
0
2023-11-02 01:36:23+00:00
12k
microsoft/monitors4codegen
src/monitors4codegen/multilspy/lsp_protocol_handler/server.py
[ { "identifier": "LspNotification", "path": "src/monitors4codegen/multilspy/lsp_protocol_handler/lsp_requests.py", "snippet": "class LspNotification:\n def __init__(self, send_notification):\n self.send_notification = send_notification\n\n def did_change_workspace_folders(\n self, par...
import asyncio import dataclasses import json import os from typing import Any, Dict, List, Optional, Union from .lsp_requests import LspNotification, LspRequest from .lsp_types import ErrorCodes
8,381
def __init__(self, code: ErrorCodes, message: str) -> None: super().__init__(message) self.code = code def to_lsp(self) -> StringDict: return {"code": self.code, "message": super().__str__()} @classmethod def from_lsp(cls, d: StringDict) -> "Error": return Error(d["code"], d["message"]) def __str__(self) -> str: return f"{super().__str__()} ({self.code})" def make_response(request_id: Any, params: PayloadLike) -> StringDict: return {"jsonrpc": "2.0", "id": request_id, "result": params} def make_error_response(request_id: Any, err: Error) -> StringDict: return {"jsonrpc": "2.0", "id": request_id, "error": err.to_lsp()} def make_notification(method: str, params: PayloadLike) -> StringDict: return {"jsonrpc": "2.0", "method": method, "params": params} def make_request(method: str, request_id: Any, params: PayloadLike) -> StringDict: return {"jsonrpc": "2.0", "method": method, "id": request_id, "params": params} class StopLoopException(Exception): pass def create_message(payload: PayloadLike): body = json.dumps(payload, check_circular=False, ensure_ascii=False, separators=(",", ":")).encode(ENCODING) return ( f"Content-Length: {len(body)}\r\n".encode(ENCODING), "Content-Type: application/vscode-jsonrpc; charset=utf-8\r\n\r\n".encode(ENCODING), body, ) class MessageType: error = 1 warning = 2 info = 3 log = 4 class Request: def __init__(self) -> None: self.cv = asyncio.Condition() self.result: Optional[PayloadLike] = None self.error: Optional[Error] = None async def on_result(self, params: PayloadLike) -> None: self.result = params async with self.cv: self.cv.notify() async def on_error(self, err: Error) -> None: self.error = err async with self.cv: self.cv.notify() def content_length(line: bytes) -> Optional[int]: if line.startswith(b"Content-Length: "): _, value = line.split(b"Content-Length: ") value = value.strip() try: return int(value) except ValueError: raise ValueError("Invalid Content-Length header: {}".format(value)) return None class LanguageServerHandler: """ This class provides the implementation of Python client for the Language Server Protocol. A class that launches the language server and communicates with it using the Language Server Protocol (LSP). It provides methods for sending requests, responses, and notifications to the server and for registering handlers for requests and notifications from the server. Uses JSON-RPC 2.0 for communication with the server over stdin/stdout. Attributes: send: A LspRequest object that can be used to send requests to the server and await for the responses. notify: A LspNotification object that can be used to send notifications to the server. cmd: A string that represents the command to launch the language server process. process: A subprocess.Popen object that represents the language server process. _received_shutdown: A boolean flag that indicates whether the client has received a shutdown request from the server. request_id: An integer that represents the next available request id for the client. _response_handlers: A dictionary that maps request ids to Request objects that store the results or errors of the requests. on_request_handlers: A dictionary that maps method names to callback functions that handle requests from the server. on_notification_handlers: A dictionary that maps method names to callback functions that handle notifications from the server. logger: An optional function that takes two strings (source and destination) and a payload dictionary, and logs the communication between the client and the server. tasks: A dictionary that maps task ids to asyncio.Task objects that represent the asynchronous tasks created by the handler. task_counter: An integer that represents the next available task id for the handler. loop: An asyncio.AbstractEventLoop object that represents the event loop used by the handler. """ def __init__(self, process_launch_info: ProcessLaunchInfo, logger=None) -> None: """ Params: cmd: A string that represents the command to launch the language server process. logger: An optional function that takes two strings (source and destination) and a payload dictionary, and logs the communication between the client and the server. """
""" This file provides the implementation of the JSON-RPC client, that launches and communicates with the language server. The initial implementation of this file was obtained from https://github.com/predragnikolic/OLSP under the MIT License with the following terms: MIT License Copyright (c) 2023 Предраг Николић Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ StringDict = Dict[str, Any] PayloadLike = Union[List[StringDict], StringDict, None] CONTENT_LENGTH = "Content-Length: " ENCODING = "utf-8" @dataclasses.dataclass class ProcessLaunchInfo: """ This class is used to store the information required to launch a process. """ # The command to launch the process cmd: str # The environment variables to set for the process env: Dict[str, str] = dataclasses.field(default_factory=dict) # The working directory for the process cwd: str = os.getcwd() class Error(Exception): def __init__(self, code: ErrorCodes, message: str) -> None: super().__init__(message) self.code = code def to_lsp(self) -> StringDict: return {"code": self.code, "message": super().__str__()} @classmethod def from_lsp(cls, d: StringDict) -> "Error": return Error(d["code"], d["message"]) def __str__(self) -> str: return f"{super().__str__()} ({self.code})" def make_response(request_id: Any, params: PayloadLike) -> StringDict: return {"jsonrpc": "2.0", "id": request_id, "result": params} def make_error_response(request_id: Any, err: Error) -> StringDict: return {"jsonrpc": "2.0", "id": request_id, "error": err.to_lsp()} def make_notification(method: str, params: PayloadLike) -> StringDict: return {"jsonrpc": "2.0", "method": method, "params": params} def make_request(method: str, request_id: Any, params: PayloadLike) -> StringDict: return {"jsonrpc": "2.0", "method": method, "id": request_id, "params": params} class StopLoopException(Exception): pass def create_message(payload: PayloadLike): body = json.dumps(payload, check_circular=False, ensure_ascii=False, separators=(",", ":")).encode(ENCODING) return ( f"Content-Length: {len(body)}\r\n".encode(ENCODING), "Content-Type: application/vscode-jsonrpc; charset=utf-8\r\n\r\n".encode(ENCODING), body, ) class MessageType: error = 1 warning = 2 info = 3 log = 4 class Request: def __init__(self) -> None: self.cv = asyncio.Condition() self.result: Optional[PayloadLike] = None self.error: Optional[Error] = None async def on_result(self, params: PayloadLike) -> None: self.result = params async with self.cv: self.cv.notify() async def on_error(self, err: Error) -> None: self.error = err async with self.cv: self.cv.notify() def content_length(line: bytes) -> Optional[int]: if line.startswith(b"Content-Length: "): _, value = line.split(b"Content-Length: ") value = value.strip() try: return int(value) except ValueError: raise ValueError("Invalid Content-Length header: {}".format(value)) return None class LanguageServerHandler: """ This class provides the implementation of Python client for the Language Server Protocol. A class that launches the language server and communicates with it using the Language Server Protocol (LSP). It provides methods for sending requests, responses, and notifications to the server and for registering handlers for requests and notifications from the server. Uses JSON-RPC 2.0 for communication with the server over stdin/stdout. Attributes: send: A LspRequest object that can be used to send requests to the server and await for the responses. notify: A LspNotification object that can be used to send notifications to the server. cmd: A string that represents the command to launch the language server process. process: A subprocess.Popen object that represents the language server process. _received_shutdown: A boolean flag that indicates whether the client has received a shutdown request from the server. request_id: An integer that represents the next available request id for the client. _response_handlers: A dictionary that maps request ids to Request objects that store the results or errors of the requests. on_request_handlers: A dictionary that maps method names to callback functions that handle requests from the server. on_notification_handlers: A dictionary that maps method names to callback functions that handle notifications from the server. logger: An optional function that takes two strings (source and destination) and a payload dictionary, and logs the communication between the client and the server. tasks: A dictionary that maps task ids to asyncio.Task objects that represent the asynchronous tasks created by the handler. task_counter: An integer that represents the next available task id for the handler. loop: An asyncio.AbstractEventLoop object that represents the event loop used by the handler. """ def __init__(self, process_launch_info: ProcessLaunchInfo, logger=None) -> None: """ Params: cmd: A string that represents the command to launch the language server process. logger: An optional function that takes two strings (source and destination) and a payload dictionary, and logs the communication between the client and the server. """
self.send = LspRequest(self.send_request)
1
2023-11-04 21:49:04+00:00
12k
bigai-nlco/langsuite
langsuite/envs/teach/teach_world.py
[ { "identifier": "CSS4_COLORS", "path": "langsuite/constants.py", "snippet": "CSS4_COLORS = {\n \"aliceblue\": \"#F0F8FF\",\n \"antiquewhite\": \"#FAEBD7\",\n \"aqua\": \"#00FFFF\",\n \"aquamarine\": \"#7FFFD4\",\n \"azure\": \"#F0FFFF\",\n \"beige\": \"#F5F5DC\",\n \"bisque\": \"#FF...
import json import random import numpy as np import plotly.graph_objects as go from collections import defaultdict from copy import deepcopy from pathlib import Path from typing import Any, Dict, Optional, Tuple, Union from langsuite.constants import CSS4_COLORS from langsuite.shapes import Geometry, Point2D, Polygon2D from langsuite.utils.logging import logger from langsuite.world import WORLD_REGISTRY, Object2D, ObjectType, Room, Wall, World
7,288
# bbox = get_bbox(bbox_cornerpoints) bbox = get_bbox(center, size) rotation = obj_data["rotation"]["y"] polys_2d = None center = Point2D(center["x"], center["z"]) position = Point2D( obj_data.get("position").get("x"), obj_data.get("position").get("z") ) if bbox: # ul = center - Point2D(bbox["x"], bbox["z"]) * 0.5 # br = center + Point2D(bbox["x"], bbox["z"]) * 0.5 # polys_2d = Box2D(ul, br) polys_2d = Polygon2D(bbox) # TODO Box2D rotate ISSUE # polys_2d.rotate(360 - rotation, origin=(center.x, center.y)) children = {} if ( "receptacleObjectIds" in obj_data and obj_data["receptacleObjectIds"] is not None and len(obj_data["receptacleObjectIds"]) > 0 ): children_id = deepcopy(obj_data["receptacleObjectIds"]) while len(children_id) > 0: c_id = children_id.pop(0) for object_c in objs_data: if object_c["objectId"] == c_id: children[c_id] = TeachObject.create(object_c, objs_data) break return cls( object_id, geometry=polys_2d, asset_id=asset_id, position=center, rotation=rotation, children=children, props=props, ) def plot(self, axes=None): if self.geometry is None: return x, y = self.geometry.shapely_geo.exterior.xy axes.fill(x, y) if len(self.children) > 0: for c in self.children: self.children[c].plot(axes=axes) def render(self, fig): if self.geometry is None: return x, y = self.geometry.shapely_geo.exterior.xy fig.add_trace( go.Scatter( mode="lines", x=np.array(x), y=np.array(y), fill="toself", name=self.id, fillcolor=self.color, line=dict(width=0), ) ) if len(self.children) > 0: for c in self.children: self.children[c].render(fig) def find_all_children(self): children = [] if len(self.children) > 0: for child in self.children.values(): children.append(child) children.extend(child.find_all_children()) return children def del_child(self, child_id): if child_id in self.children: del self.children[child_id] return True else: for child in self.children.values(): if child.del_children(child_id): return True return False def get_obj_pose_info(self): if "openable" in self.props and self.props["openable"]: openness = self.props["openness"] openable = True else: openness = None openable = False if "pickupable" in self.props: pickupable = self.props["pickupable"] else: pickupable = False if "isBroken" in self.props: isBroken = self.props["isBroken"] else: isBroken = False return { "type": self.id.split("|")[0], "position": self.position, "rotation": self.rotation, "openable": openable, "openness": openness, "pickupable": pickupable, "broken": isBroken, "objectId": self.id, "name": self.id, "parentReceptacles": [], "bounding_box": None, } @WORLD_REGISTRY.register()
# Copyright (c) BIGAI Research. All rights reserved. # Licensed under the MIT license. from __future__ import annotations TeachPath = Path(__file__).parent class TeachWall(Wall): def __init__( self, wall_id: str, *, alias: Optional[str] = None, geometry: Optional[Geometry] = None, asset_id: Optional[str] = None, room2room: Union[Tuple[str], str] = list(), empty: bool, **kwargs, ): super().__init__( wall_id, alias=alias, geometry=geometry, asset_id=asset_id, room2room=room2room, **kwargs, ) self.empty = empty @classmethod def create(cls, id, polys_2d): empty = False polys_2d = Polygon2D(polys_2d) return cls(id, geometry=polys_2d, empty=empty) def plot(self, axes=None): if self.geometry is None: return x, y = self.geometry.shapely_geo.exterior.xy if self.empty: axes.plot(x, y, color="black", linestyle="-.", linewidth=0.5) else: axes.plot(x, y, color="black", linewidth=0.5) axes.fill(x, y, color="gray") def render(self): if not self.geometry: return class TeachRoom(Room): @classmethod def create(cls, room_data): polys_3d = room_data["floorPolygon"] polys_2d = [] for p in polys_3d: polys_2d.append((p[0], p[1])) polys_2d = Polygon2D(polys_2d) return cls(room_data["id"], geometry=polys_2d, asset_id=room_data["roomType"]) def plot(self, axes=None, color="aliceblue"): if self.geometry is None: return x, y = self.geometry.shapely_geo.exterior.xy axes.fill(x, y, color=color) def render(self, fig=None): if self.geometry is None: return if not fig: fig = go.Figure() x, y = self.geometry.shapely_geo.exterior.xy fig.add_trace( go.Scatter( x=np.array(x), y=np.array(y), fill="toself", fillcolor="aliceblue", name=self.id, line=dict(color="gray"), ) ) class TeachObject(Object2D): colorscales = list(CSS4_COLORS.keys()) color_registry = defaultdict() def __init__( self, obj_id: str, *, alias: Optional[str] = None, geometry: Optional[Polygon2D] = None, asset_id: Optional[str] = None, position: Point2D = None, rotation: float = 0, props: Dict[str, Any] = defaultdict(), **kwargs, ) -> None: super().__init__( ObjectType.OBJECT, obj_id, alias=alias, geometry=geometry, asset_id=asset_id, **kwargs, ) self.chilren_types = [ObjectType.OBJECT] if props is not None: self.props.update(props) self.category = self.id.split("|")[0] if self.category not in TeachObject.color_registry: select_color = random.choice(TeachObject.colorscales) TeachObject.color_registry.update({self.category: select_color}) TeachObject.colorscales.remove(select_color) self.color = TeachObject.color_registry.get(self.category) # self.position = self.geometry.centroid self.position = position self.rotation = rotation @classmethod def create(cls, obj_data, objs_data): if "Floor" in obj_data["objectId"]: obj_data["axisAlignedBoundingBox"]["size"] = {"x": 0, "y": 0, "z": 0} asset_id = obj_data["objectType"] object_id = obj_data["objectId"] props = obj_data size = obj_data.get("axisAlignedBoundingBox").get("size") center = obj_data.get("axisAlignedBoundingBox").get("center") def get_bbox(center, size): minx = center["x"] - (1 / 2) * size["x"] maxx = center["x"] + (1 / 2) * size["x"] minz = center["z"] - (1 / 2) * size["z"] maxz = center["z"] + (1 / 2) * size["z"] return [[minx, minz], [minx, maxz], [maxx, maxz], [maxx, minz]] # bbox = get_bbox(bbox_cornerpoints) bbox = get_bbox(center, size) rotation = obj_data["rotation"]["y"] polys_2d = None center = Point2D(center["x"], center["z"]) position = Point2D( obj_data.get("position").get("x"), obj_data.get("position").get("z") ) if bbox: # ul = center - Point2D(bbox["x"], bbox["z"]) * 0.5 # br = center + Point2D(bbox["x"], bbox["z"]) * 0.5 # polys_2d = Box2D(ul, br) polys_2d = Polygon2D(bbox) # TODO Box2D rotate ISSUE # polys_2d.rotate(360 - rotation, origin=(center.x, center.y)) children = {} if ( "receptacleObjectIds" in obj_data and obj_data["receptacleObjectIds"] is not None and len(obj_data["receptacleObjectIds"]) > 0 ): children_id = deepcopy(obj_data["receptacleObjectIds"]) while len(children_id) > 0: c_id = children_id.pop(0) for object_c in objs_data: if object_c["objectId"] == c_id: children[c_id] = TeachObject.create(object_c, objs_data) break return cls( object_id, geometry=polys_2d, asset_id=asset_id, position=center, rotation=rotation, children=children, props=props, ) def plot(self, axes=None): if self.geometry is None: return x, y = self.geometry.shapely_geo.exterior.xy axes.fill(x, y) if len(self.children) > 0: for c in self.children: self.children[c].plot(axes=axes) def render(self, fig): if self.geometry is None: return x, y = self.geometry.shapely_geo.exterior.xy fig.add_trace( go.Scatter( mode="lines", x=np.array(x), y=np.array(y), fill="toself", name=self.id, fillcolor=self.color, line=dict(width=0), ) ) if len(self.children) > 0: for c in self.children: self.children[c].render(fig) def find_all_children(self): children = [] if len(self.children) > 0: for child in self.children.values(): children.append(child) children.extend(child.find_all_children()) return children def del_child(self, child_id): if child_id in self.children: del self.children[child_id] return True else: for child in self.children.values(): if child.del_children(child_id): return True return False def get_obj_pose_info(self): if "openable" in self.props and self.props["openable"]: openness = self.props["openness"] openable = True else: openness = None openable = False if "pickupable" in self.props: pickupable = self.props["pickupable"] else: pickupable = False if "isBroken" in self.props: isBroken = self.props["isBroken"] else: isBroken = False return { "type": self.id.split("|")[0], "position": self.position, "rotation": self.rotation, "openable": openable, "openness": openness, "pickupable": pickupable, "broken": isBroken, "objectId": self.id, "name": self.id, "parentReceptacles": [], "bounding_box": None, } @WORLD_REGISTRY.register()
class TeachWorld(World):
10
2023-11-01 01:47:00+00:00
12k
radekd91/inferno
inferno/models/EmoSwinModule.py
[ { "identifier": "class_from_str", "path": "inferno/utils/other.py", "snippet": "def class_from_str(str, module=None, none_on_fail = False) -> type:\n if module is None:\n module = sys.modules[__name__]\n if hasattr(module, str):\n cl = getattr(module, str)\n return cl\n eli...
import sys import torch import pytorch_lightning as pl import numpy as np import torch.nn.functional as F import pytorch_lightning.plugins.environments.lightning_environment as le from inferno.utils.other import class_from_str from omegaconf import DictConfig, OmegaConf from pytorch_lightning.loggers import WandbLogger from inferno.datasets.AffectNetDataModule import AffectNetExpressions from inferno.datasets.AffWild2Dataset import Expression7 from pathlib import Path from inferno.utils.lightning_logging import _log_array_image, _log_wandb_image, _torch_image2np from inferno.models.EmotionRecognitionModuleBase import EmotionRecognitionBaseModule from omegaconf import open_dict from .Swin import create_swin_backbone
9,122
self.config.model.swin_type ) self.num_classes = self.n_expression def get_last_feature_size(self): return self.swin.num_features def _forward(self, images): output, emo_feat_2 = self.swin(images, include_features=True) out_idx = 0 if self.predicts_expression(): expr_classification = output[:, out_idx:(out_idx + self.n_expression)] if self.exp_activation is not None: expr_classification = self.exp_activation(expr_classification, dim=1) out_idx += self.n_expression else: expr_classification = None if self.predicts_valence(): valence = output[:, out_idx:(out_idx + 1)] if self.v_activation is not None: valence = self.v_activation(valence) out_idx += 1 else: valence = None if self.predicts_arousal(): arousal = output[:, out_idx:(out_idx + 1)] if self.a_activation is not None: arousal = self.a_activation(arousal) out_idx += 1 else: arousal = None if self.predicts_AUs(): num_AUs = self.config.model.predict_AUs AUs = output[:, out_idx:(out_idx + num_AUs)] if self.AU_activation is not None: AUs = self.AU_activation(AUs) out_idx += num_AUs else: AUs = None assert out_idx == output.shape[1] values = {} values["emo_feat_2"] = emo_feat_2 values["valence"] = valence values["arousal"] = arousal values["expr_classification"] = expr_classification values["AUs"] = AUs return values def forward(self, batch): images = batch['image'] if len(images.shape) == 5: K = images.shape[1] elif len(images.shape) == 4: K = 1 else: raise RuntimeError("Invalid image batch dimensions.") # print("Batch size!") # print(images.shape) images = images.view(-1, images.shape[-3], images.shape[-2], images.shape[-1]) emotion = self._forward(images) valence = emotion['valence'] arousal = emotion['arousal'] # emotion['expression'] = emotion['expression'] # classes_probs = F.softmax(emotion['expression']) # expression = self.exp_activation(emotion['expr_classification'], dim=1) values = {} if self.predicts_valence(): values['valence'] = valence.view(-1,1) if self.predicts_arousal(): values['arousal'] = arousal.view(-1,1) # values['expr_classification'] = expression values['expr_classification'] = emotion['expr_classification'] if self.predicts_AUs(): values['AUs'] = emotion['AUs'] values['emo_feat_2'] = emotion['emo_feat_2'] # TODO: WARNING: HACK if 'n_expression' not in self.config.data.keys(): if self.n_expression == 8: raise NotImplementedError("This here should not be called") values['expr_classification'] = torch.cat([ values['expr_classification'], torch.zeros_like(values['expr_classification'][:, 0:1]) + 2*values['expr_classification'].min()], dim=1) return values def _get_trainable_parameters(self): return list(self.swin.parameters()) ## we can leave the default implementation # def train(self, mode=True): # pass def _vae_2_str(self, valence=None, arousal=None, affnet_expr=None, expr7=None, prefix=""): caption = "" if len(prefix) > 0: prefix += "_" if valence is not None and not np.isnan(valence).any(): caption += prefix + "valence= %.03f\n" % valence if arousal is not None and not np.isnan(arousal).any(): caption += prefix + "arousal= %.03f\n" % arousal if affnet_expr is not None and not np.isnan(affnet_expr).any(): caption += prefix + "expression= %s \n" % AffectNetExpressions(affnet_expr).name if expr7 is not None and not np.isnan(expr7).any():
""" Author: Radek Danecek Copyright (c) 2022, Radek Danecek All rights reserved. # Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is # holder of all proprietary rights on this computer program. # Using this computer program means that you agree to the terms # in the LICENSE file included with this software distribution. # Any use not explicitly granted by the LICENSE is prohibited. # # Copyright©2022 Max-Planck-Gesellschaft zur Förderung # der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute # for Intelligent Systems. All rights reserved. # # For comments or questions, please email us at emoca@tue.mpg.de # For commercial licensing contact, please contact ps-license@tuebingen.mpg.de """ class EmoSwinModule(EmotionRecognitionBaseModule): """ Emotion Recognitition module which uses Swin Transformer as its backbone. Currently Resnet-50 and VGG are supported. """ def __init__(self, config): super().__init__(config) # self.n_expression = 9 # we use all affectnet classes (included none) for now self.n_expression = self.config.data.n_expression if 'n_expression' in self.config.data.keys() else 9 # we use all affectnet classes (included none) for now self.num_outputs = 0 if self.config.model.predict_expression: self.num_outputs += self.n_expression self.num_classes = self.n_expression if self.config.model.predict_valence: self.num_outputs += 1 if self.config.model.predict_arousal: self.num_outputs += 1 if 'predict_AUs' in self.config.model.keys() and self.config.model.predict_AUs: self.num_outputs += self.config.model.predict_AUs with open_dict(config.model.swin_cfg): self.swin = create_swin_backbone(config.model.swin_cfg, self.num_outputs, config.data.image_size, config.model.load_pretrained_swin, self.config.model.swin_type ) self.num_classes = self.n_expression def get_last_feature_size(self): return self.swin.num_features def _forward(self, images): output, emo_feat_2 = self.swin(images, include_features=True) out_idx = 0 if self.predicts_expression(): expr_classification = output[:, out_idx:(out_idx + self.n_expression)] if self.exp_activation is not None: expr_classification = self.exp_activation(expr_classification, dim=1) out_idx += self.n_expression else: expr_classification = None if self.predicts_valence(): valence = output[:, out_idx:(out_idx + 1)] if self.v_activation is not None: valence = self.v_activation(valence) out_idx += 1 else: valence = None if self.predicts_arousal(): arousal = output[:, out_idx:(out_idx + 1)] if self.a_activation is not None: arousal = self.a_activation(arousal) out_idx += 1 else: arousal = None if self.predicts_AUs(): num_AUs = self.config.model.predict_AUs AUs = output[:, out_idx:(out_idx + num_AUs)] if self.AU_activation is not None: AUs = self.AU_activation(AUs) out_idx += num_AUs else: AUs = None assert out_idx == output.shape[1] values = {} values["emo_feat_2"] = emo_feat_2 values["valence"] = valence values["arousal"] = arousal values["expr_classification"] = expr_classification values["AUs"] = AUs return values def forward(self, batch): images = batch['image'] if len(images.shape) == 5: K = images.shape[1] elif len(images.shape) == 4: K = 1 else: raise RuntimeError("Invalid image batch dimensions.") # print("Batch size!") # print(images.shape) images = images.view(-1, images.shape[-3], images.shape[-2], images.shape[-1]) emotion = self._forward(images) valence = emotion['valence'] arousal = emotion['arousal'] # emotion['expression'] = emotion['expression'] # classes_probs = F.softmax(emotion['expression']) # expression = self.exp_activation(emotion['expr_classification'], dim=1) values = {} if self.predicts_valence(): values['valence'] = valence.view(-1,1) if self.predicts_arousal(): values['arousal'] = arousal.view(-1,1) # values['expr_classification'] = expression values['expr_classification'] = emotion['expr_classification'] if self.predicts_AUs(): values['AUs'] = emotion['AUs'] values['emo_feat_2'] = emotion['emo_feat_2'] # TODO: WARNING: HACK if 'n_expression' not in self.config.data.keys(): if self.n_expression == 8: raise NotImplementedError("This here should not be called") values['expr_classification'] = torch.cat([ values['expr_classification'], torch.zeros_like(values['expr_classification'][:, 0:1]) + 2*values['expr_classification'].min()], dim=1) return values def _get_trainable_parameters(self): return list(self.swin.parameters()) ## we can leave the default implementation # def train(self, mode=True): # pass def _vae_2_str(self, valence=None, arousal=None, affnet_expr=None, expr7=None, prefix=""): caption = "" if len(prefix) > 0: prefix += "_" if valence is not None and not np.isnan(valence).any(): caption += prefix + "valence= %.03f\n" % valence if arousal is not None and not np.isnan(arousal).any(): caption += prefix + "arousal= %.03f\n" % arousal if affnet_expr is not None and not np.isnan(affnet_expr).any(): caption += prefix + "expression= %s \n" % AffectNetExpressions(affnet_expr).name if expr7 is not None and not np.isnan(expr7).any():
caption += prefix +"expression= %s \n" % Expression7(expr7).name
2
2023-11-07 20:13:32+00:00
12k
hxz393/ConfigCenterComparer
ui/dialog_settings_main.py
[ { "identifier": "LANG_DICTS", "path": "config/lang_dict_all.py", "snippet": "LANG_DICTS = {\n 'English': {\n 'main_1': 'Ready',\n 'main_2': ' &Start ',\n 'main_3': ' &Edit ',\n 'main_4': ' &Options',\n 'main_5': ' &Help ',\n 'label_status_error': 'Error ...
import logging from typing import List, Tuple from PyQt5.QtCore import Qt, pyqtSignal from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QDialog, QLineEdit, QDialogButtonBox, QHBoxLayout, QVBoxLayout, QGroupBox, QLabel, QComboBox from config.lang_dict_all import LANG_DICTS from config.settings import CONFIG_CENTER_LIST, APOLLO_NAME_LIST, COLOR_SET_LIST from lib.get_resource_path import get_resource_path from ui.config_manager import ConfigManager from ui.lang_manager import LangManager
7,562
""" 此模块提供了一个对话框界面,用于处理应用程序的主要设置。 包括语言设置、配置中心类型选择、服务名替换规则等功能。用户可以通过此对话框修改各项设置,并将其保存到配置文件中。 :author: assassing :contact: https://github.com/hxz393 :copyright: Copyright 2023, hxz393. 保留所有权利。 """ logger = logging.getLogger(__name__) class DialogSettingsMain(QDialog): """ 主设置对话框类。 此类提供了一个对话框界面,供用户修改应用程序的主要设置,例如语言、配置中心类型、服务名替换规则等。 它允许用户对这些设置进行更改,并通过按下确定按钮来保存这些更改。 :param lang_manager: 语言管理器实例。 :type lang_manager: LangManager :param config_manager: 配置管理器实例。 :type config_manager: ConfigManager :ivar status_updated: 用于发出状态更新信号的pyqtSignal实例。 :vartype status_updated: pyqtSignal """ status_updated = pyqtSignal(str) def __init__(self, lang_manager: LangManager, config_manager: ConfigManager): super().__init__(flags=Qt.Dialog | Qt.WindowCloseButtonHint) # 初始化两个管理器 self.lang_manager = lang_manager self.config_manager = config_manager # 获取管理器中的配置 self.config_main = self.config_manager.get_config_main() # 获取语言字典 self.lang = self.lang_manager.get_lang() self.initUI() def initUI(self) -> None: """ 初始化用户界面。 此方法设置对话框的标题、图标、样式和大小,并创建主布局。在主布局中,它添加了主要设置组和额外设置组的布局,并在两者之间添加了弹性空间。最后,添加了按钮布局。 主要设置组包括语言选择、配置中心类型选择等,而额外设置组包括服务名替换规则的设置。此方法利用私有方法 `_create_main_group` 和 `_create_extra_group` 来创建这些组。 :return: 无返回值。 :rtype: None """ # 主窗口 self.setWindowTitle(self.lang['ui.dialog_settings_main_1']) self.setWindowIcon(QIcon(get_resource_path('media/icons8-setting-26'))) self.setStyleSheet("font-size: 14px;") self.setMinimumSize(370, 490) # 主布局 layout = QVBoxLayout() # 上层布局 layout.addWidget(self._create_main_group()) # 下层布局 layout.addWidget(self._create_extra_group()) # 在两个组件之间添加弹性空间 layout.addStretch() # 按钮布局 layout.addLayout(self._create_buttons()) self.setLayout(layout) def _create_main_group(self) -> QGroupBox: """ 创建并返回主要设置组的布局。 此私有方法用于构建对话框中的主要设置组,包括语言选择、配置中心类型选择等。 :return: 配置好的主要设置组。 :rtype: QGroupBox """ main_layout = QVBoxLayout() # 下拉框:选择语言
""" 此模块提供了一个对话框界面,用于处理应用程序的主要设置。 包括语言设置、配置中心类型选择、服务名替换规则等功能。用户可以通过此对话框修改各项设置,并将其保存到配置文件中。 :author: assassing :contact: https://github.com/hxz393 :copyright: Copyright 2023, hxz393. 保留所有权利。 """ logger = logging.getLogger(__name__) class DialogSettingsMain(QDialog): """ 主设置对话框类。 此类提供了一个对话框界面,供用户修改应用程序的主要设置,例如语言、配置中心类型、服务名替换规则等。 它允许用户对这些设置进行更改,并通过按下确定按钮来保存这些更改。 :param lang_manager: 语言管理器实例。 :type lang_manager: LangManager :param config_manager: 配置管理器实例。 :type config_manager: ConfigManager :ivar status_updated: 用于发出状态更新信号的pyqtSignal实例。 :vartype status_updated: pyqtSignal """ status_updated = pyqtSignal(str) def __init__(self, lang_manager: LangManager, config_manager: ConfigManager): super().__init__(flags=Qt.Dialog | Qt.WindowCloseButtonHint) # 初始化两个管理器 self.lang_manager = lang_manager self.config_manager = config_manager # 获取管理器中的配置 self.config_main = self.config_manager.get_config_main() # 获取语言字典 self.lang = self.lang_manager.get_lang() self.initUI() def initUI(self) -> None: """ 初始化用户界面。 此方法设置对话框的标题、图标、样式和大小,并创建主布局。在主布局中,它添加了主要设置组和额外设置组的布局,并在两者之间添加了弹性空间。最后,添加了按钮布局。 主要设置组包括语言选择、配置中心类型选择等,而额外设置组包括服务名替换规则的设置。此方法利用私有方法 `_create_main_group` 和 `_create_extra_group` 来创建这些组。 :return: 无返回值。 :rtype: None """ # 主窗口 self.setWindowTitle(self.lang['ui.dialog_settings_main_1']) self.setWindowIcon(QIcon(get_resource_path('media/icons8-setting-26'))) self.setStyleSheet("font-size: 14px;") self.setMinimumSize(370, 490) # 主布局 layout = QVBoxLayout() # 上层布局 layout.addWidget(self._create_main_group()) # 下层布局 layout.addWidget(self._create_extra_group()) # 在两个组件之间添加弹性空间 layout.addStretch() # 按钮布局 layout.addLayout(self._create_buttons()) self.setLayout(layout) def _create_main_group(self) -> QGroupBox: """ 创建并返回主要设置组的布局。 此私有方法用于构建对话框中的主要设置组,包括语言选择、配置中心类型选择等。 :return: 配置好的主要设置组。 :rtype: QGroupBox """ main_layout = QVBoxLayout() # 下拉框:选择语言
self.language_combo_box = self._create_combo_box(main_layout, LANG_DICTS.keys(), self.lang['ui.dialog_settings_main_2'], self.config_main.get('lang', 'English'))
0
2023-11-07 01:02:38+00:00
12k
pytorch-labs/ao
test/test.py
[ { "identifier": "DynamicallyPerAxisQuantizedLinear", "path": "torchao/quantization/dynamic_quant.py", "snippet": "class DynamicallyPerAxisQuantizedLinear(torch.nn.Linear):\n \"\"\"\n This class is a replacement for `torch.nn.Linear`. It implements a\n quantized matmul using int8 dynamic symmetr...
import copy import unittest import torch import torch.nn as nn import os from torch._inductor.utils import run_and_get_code from torch._dynamo import config from torch.ao.quantization import MinMaxObserver, QConfigMapping from torchao.quantization.dynamic_quant import ( DynamicallyPerAxisQuantizedLinear, ) from torchao.quantization.quant_api import ( apply_dynamic_quant, apply_weight_only_int8_quant, change_linear_weights_to_int8_dqtensors, change_linear_weights_to_int8_woqtensors, change_linear_weights_to_int4_woqtensors, _replace_with_custom_fn_if_matches_filter, ) from torchao.quantization.quant_primitives import ( dequantize_per_channel, dequantize_per_tensor, dynamically_quantize_per_channel, dynamically_quantize_per_tensor, quant_int8_dynamic_linear, quant_int8_dynamic_per_token_linear, quantize_activation_per_token_absmax, safe_int_mm, ) from torchao.quantization.smoothquant import ( get_scale, smooth_fq_linear_to_inference, SmoothFakeDynamicallyQuantizedLinear, swap_linear_with_smooth_fq_linear, ) from torchao.quantization.subclass import ( Int8DynamicallyQuantizedLinearWeight, Int8WeightOnlyQuantizedLinearWeight, Int4WeightOnlyQuantizedLinearWeight ) from torchao.quantization.utils import ( _apply_logging_hook, compute_error, compute_error as SQNR, _fqn_to_op_to_shape_to_count, LoggingTensorMode, ) from torch.ao.quantization.quantize_fx import convert_to_reference_fx, prepare_fx from transformers import ( # type: ignore[import-untyped] DistilBertModel, DistilBertTokenizer, )
9,994
w_shape = (7, 9) for i in range(3): X = torch.randn(x_shape) * 10 W = torch.randn(w_shape) s = get_scale( torch.amax(torch.abs(X), dim=(0, 1)), torch.amax(torch.abs(W), dim=1), alpha=0.5, ) Y = torch.matmul(X, W) Y_ref = torch.matmul( X / s.reshape(1, 1, -1), torch.matmul(torch.diag(s), W), ) assert torch.allclose(Y, Y_ref, atol=1e-3, rtol=1e-3), "not close!" def _test_smooth_linear_impl(self, x_shape, lin_shape, device): # so we can use the full range torch.backends.quantized.engine = "qnnpack" x = torch.randn(*x_shape, device=device) * 9 + 10 lin_fp32 = nn.Linear(*lin_shape, device=device) # misc: ignore lin_smooth = SmoothFakeDynamicallyQuantizedLinear.from_float( copy.deepcopy(lin_fp32), alpha=0.25 ) lin_smooth_skip_scaling = SmoothFakeDynamicallyQuantizedLinear.from_float( copy.deepcopy(lin_fp32), alpha=0.25 ) lin_fp32_copy = copy.deepcopy(lin_fp32) # assignment: ignore lin_fp32_copy.qconfig = torch.ao.quantization.QConfig( # assignment: ignore activation=None, weight=torch.ao.quantization.default_per_channel_weight_observer, ) lin_dynamic_q = torch.ao.nn.quantized.dynamic.Linear.from_float( lin_fp32_copy.cpu() ) y_ref = lin_fp32(x) # calibrate the smoothquant versions y_smooth_nocalib = lin_smooth(x) _ = lin_smooth_skip_scaling(x) lin_smooth.to_inference() lin_smooth_skip_scaling.debug_skip_scaling = True lin_smooth_skip_scaling.to_inference() # verify that with scaling turned off, numerics match quantized version y_smooth_fq_only = lin_smooth_skip_scaling(x) y_smooth_fq = lin_smooth(x) y_dynamic_q = lin_dynamic_q(x.cpu()).to(device) # print('y_ref', y_ref) # print('y_smooth_nocalib', y_smooth_nocalib) # print('y_smooth_fq', y_smooth_fq) # print('y_smooth_fq_only', y_smooth_fq_only) # print('y_dynamic_q', y_dynamic_q) sqnr_smooth_fq = compute_error(y_ref, y_smooth_fq) sqnr_dynamic_q = compute_error(y_ref, y_dynamic_q) sqnr_fq = compute_error(y_smooth_fq_only, y_dynamic_q) # print('sqnr_smooth', sqnr_smooth_fq, 'sqnr_dynamic', sqnr_dynamic_q, 'sqnr_fq', sqnr_fq) assert torch.allclose( y_ref, y_smooth_nocalib ), "y_ref not close to y_smooth_nocalib" # after https://github.com/pytorch-labs/ao_benchmarks/pull/32, # numerics do not match exactly between production c++ code # and this Python code # assert torch.allclose( # y_smooth_fq_only, y_dynamic_q, # atol=torch.max(y_smooth_fq_only).item()*0.01, # rtol=0.00001), \ # 'y_smooth_fq_only not close to y_dynamic_q' self.assertTrue(sqnr_smooth_fq.item() >= 40.0) self.assertTrue(sqnr_dynamic_q.item() >= 40.0) self.assertTrue(sqnr_fq.item() >= 40.0) def test_smooth_linear_cpu(self): self._test_smooth_linear_impl((1, 5, 3), (3, 4), "cpu") def test_smooth_linear_cuda(self): if not torch.cuda.is_available(): print("no cuda, skip") return self._test_smooth_linear_impl((1, 32, 32), (32, 16), "cuda") def test_smooth_linear_edge_cases(self): # so we can use the full range torch.backends.quantized.engine = "qnnpack" lin_fp32 = nn.Linear(3, 4) lin_smooth = SmoothFakeDynamicallyQuantizedLinear.from_float( lin_fp32, alpha=0.25 ) # test different ranks x0 = torch.randn(4, 5, 3) x1 = torch.randn(1, 8, 5, 3) x2 = torch.randn(2, 3, 7, 5, 3) # calibrate _ = lin_smooth(x0) _ = lin_smooth(x1) _ = lin_smooth(x2) # inference lin_smooth.to_inference() _ = lin_smooth(x0) _ = lin_smooth(x1) _ = lin_smooth(x2) def test_swap(self): m = nn.Sequential( nn.Sequential(nn.Linear(4, 4), nn.ReLU(), nn.Linear(4, 4)), nn.Linear(4, 4), ) m_copy = copy.deepcopy(m)
# 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. # mypy: ignore-errors torch.manual_seed(0) config.cache_size_limit = 100 class SmoothquantUnitTest(unittest.TestCase): # first, let's reproduce the graphic from the paper, Figure 4, to ensure # we are calculating the scales correctly def test_figure_4(self): X = torch.FloatTensor([1, -16, 2, 6, -2, 8, -1, -9]).reshape(1, 2, 4) W = torch.FloatTensor([2, 1, -2, 1, -1, -1, 2, -1, -2, -1, -1, 1]).reshape(4, 3) X_mul_W = torch.matmul(X, W) smoothquant_scale = get_scale( torch.amax(torch.abs(X), dim=(0, 1)), torch.amax(torch.abs(W), dim=1), alpha=0.5, ) # reproduce scaled calculation X_scaled = X / smoothquant_scale.reshape(1, 1, -1) W_scaled = torch.matmul(torch.diag(smoothquant_scale), W) X_scaled_mul_scaled_W = torch.matmul(X_scaled, W_scaled) assert torch.allclose(X_mul_W, X_scaled_mul_scaled_W), "not close!" assert X_mul_W.shape == X_scaled_mul_scaled_W.shape # next, run the above test on a sample of representative inputs def test_tensors(self): x_shape = (1, 5, 7) w_shape = (7, 9) for i in range(3): X = torch.randn(x_shape) * 10 W = torch.randn(w_shape) s = get_scale( torch.amax(torch.abs(X), dim=(0, 1)), torch.amax(torch.abs(W), dim=1), alpha=0.5, ) Y = torch.matmul(X, W) Y_ref = torch.matmul( X / s.reshape(1, 1, -1), torch.matmul(torch.diag(s), W), ) assert torch.allclose(Y, Y_ref, atol=1e-3, rtol=1e-3), "not close!" def _test_smooth_linear_impl(self, x_shape, lin_shape, device): # so we can use the full range torch.backends.quantized.engine = "qnnpack" x = torch.randn(*x_shape, device=device) * 9 + 10 lin_fp32 = nn.Linear(*lin_shape, device=device) # misc: ignore lin_smooth = SmoothFakeDynamicallyQuantizedLinear.from_float( copy.deepcopy(lin_fp32), alpha=0.25 ) lin_smooth_skip_scaling = SmoothFakeDynamicallyQuantizedLinear.from_float( copy.deepcopy(lin_fp32), alpha=0.25 ) lin_fp32_copy = copy.deepcopy(lin_fp32) # assignment: ignore lin_fp32_copy.qconfig = torch.ao.quantization.QConfig( # assignment: ignore activation=None, weight=torch.ao.quantization.default_per_channel_weight_observer, ) lin_dynamic_q = torch.ao.nn.quantized.dynamic.Linear.from_float( lin_fp32_copy.cpu() ) y_ref = lin_fp32(x) # calibrate the smoothquant versions y_smooth_nocalib = lin_smooth(x) _ = lin_smooth_skip_scaling(x) lin_smooth.to_inference() lin_smooth_skip_scaling.debug_skip_scaling = True lin_smooth_skip_scaling.to_inference() # verify that with scaling turned off, numerics match quantized version y_smooth_fq_only = lin_smooth_skip_scaling(x) y_smooth_fq = lin_smooth(x) y_dynamic_q = lin_dynamic_q(x.cpu()).to(device) # print('y_ref', y_ref) # print('y_smooth_nocalib', y_smooth_nocalib) # print('y_smooth_fq', y_smooth_fq) # print('y_smooth_fq_only', y_smooth_fq_only) # print('y_dynamic_q', y_dynamic_q) sqnr_smooth_fq = compute_error(y_ref, y_smooth_fq) sqnr_dynamic_q = compute_error(y_ref, y_dynamic_q) sqnr_fq = compute_error(y_smooth_fq_only, y_dynamic_q) # print('sqnr_smooth', sqnr_smooth_fq, 'sqnr_dynamic', sqnr_dynamic_q, 'sqnr_fq', sqnr_fq) assert torch.allclose( y_ref, y_smooth_nocalib ), "y_ref not close to y_smooth_nocalib" # after https://github.com/pytorch-labs/ao_benchmarks/pull/32, # numerics do not match exactly between production c++ code # and this Python code # assert torch.allclose( # y_smooth_fq_only, y_dynamic_q, # atol=torch.max(y_smooth_fq_only).item()*0.01, # rtol=0.00001), \ # 'y_smooth_fq_only not close to y_dynamic_q' self.assertTrue(sqnr_smooth_fq.item() >= 40.0) self.assertTrue(sqnr_dynamic_q.item() >= 40.0) self.assertTrue(sqnr_fq.item() >= 40.0) def test_smooth_linear_cpu(self): self._test_smooth_linear_impl((1, 5, 3), (3, 4), "cpu") def test_smooth_linear_cuda(self): if not torch.cuda.is_available(): print("no cuda, skip") return self._test_smooth_linear_impl((1, 32, 32), (32, 16), "cuda") def test_smooth_linear_edge_cases(self): # so we can use the full range torch.backends.quantized.engine = "qnnpack" lin_fp32 = nn.Linear(3, 4) lin_smooth = SmoothFakeDynamicallyQuantizedLinear.from_float( lin_fp32, alpha=0.25 ) # test different ranks x0 = torch.randn(4, 5, 3) x1 = torch.randn(1, 8, 5, 3) x2 = torch.randn(2, 3, 7, 5, 3) # calibrate _ = lin_smooth(x0) _ = lin_smooth(x1) _ = lin_smooth(x2) # inference lin_smooth.to_inference() _ = lin_smooth(x0) _ = lin_smooth(x1) _ = lin_smooth(x2) def test_swap(self): m = nn.Sequential( nn.Sequential(nn.Linear(4, 4), nn.ReLU(), nn.Linear(4, 4)), nn.Linear(4, 4), ) m_copy = copy.deepcopy(m)
swap_linear_with_smooth_fq_linear(m_copy, skip_fqn_list=["0.2"])
18
2023-11-03 21:27:36+00:00
12k
google-research/semivl
semivl.py
[ { "identifier": "get_palette", "path": "datasets/palettes.py", "snippet": "def get_palette(dataset):\n if dataset == 'pascal':\n return VOC_PALETTE\n elif dataset == 'cityscapes':\n return CITYSCAPES_PALETTE\n elif dataset == 'coco':\n return COCO_PALETTE\n elif dataset ...
import argparse import logging import math import os import pprint import shutil import uuid import time import mmcv import torch import torch.backends.cudnn as cudnn import yaml from datetime import datetime from matplotlib import pyplot as plt from mmseg.core import build_optimizer from torch import nn from torch.optim import SGD from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter from datasets.palettes import get_palette from experiments import get_git_revision from model.builder import build_model from third_party.unimatch.supervised import evaluate from third_party.unimatch.dataset.semi import SemiDataset from datasets.classes import CLASSES from third_party.unimatch.util.ohem import ProbOhemCrossEntropy2d from third_party.unimatch.util.dist_helper import setup_distributed from third_party.unimatch.util.utils import count_params, count_training_params, init_log from utils.gen_code_archive import gen_code_archive from utils.plot_utils import plot_data from utils.train_utils import (DictAverageMeter, confidence_weighted_loss, cutmix_img_, cutmix_mask) from version import __version__
7,944
rank, world_size = setup_distributed(port=args.port) if cfg['nccl_p2p_disable']: os.environ["NCCL_P2P_DISABLE"] = str(1) if rank == 0: timestr = datetime.now().strftime("%y%m%d-%H%M") uid = str(uuid.uuid4())[:5] run_name = f'{timestr}_{cfg["name"]}_v{__version__}_{uid}'.replace('.', '-') save_path = f'exp/exp-{cfg["exp"]}/{run_name}' os.makedirs(save_path, exist_ok=True) formatter = logging.Formatter(fmt='[%(asctime)s] [%(levelname)-8s] %(message)s') fileHandler = logging.FileHandler(f'{save_path}/debug.log') fileHandler.setFormatter(formatter) logger.addHandler(fileHandler) all_args = {**cfg, **vars(args), 'labeled_id_path': labeled_id_path, 'unlabeled_id_path': unlabeled_id_path, 'ngpus': world_size, 'run_name': run_name, 'save_path': save_path, 'exec_git_rev': get_git_revision(), 'exec_version': __version__} logger.info('{}\n'.format(pprint.pformat(all_args))) writer = SummaryWriter(save_path) shutil.copyfile(args.config, os.path.join(save_path, 'config.yaml')) with open(os.path.join(save_path, 'all_args.yaml'), 'w') as f: yaml.dump(all_args, f, default_flow_style=None, sort_keys=False, indent=2) gen_code_archive(save_path) cudnn.enabled = True cudnn.benchmark = True maskclip_consistency_lambda = cfg['maskclip_consistency_lambda'] mcc_conf_thresh = cfg['mcc_conf_thresh'] mcc_loss_reduce = cfg['mcc_loss_reduce'] assert mcc_loss_reduce in ['mean', 'mean_valid', 'mean_all'] assert cfg['use_fp'] assert cfg['pleval'] model = build_model(cfg) if 'optimizer' not in cfg: optimizer = SGD([{'params': model.backbone.parameters(), 'lr': cfg['lr']}, {'params': [param for name, param in model.named_parameters() if 'backbone' not in name], 'lr': cfg['lr'] * cfg['lr_multi']}], lr=cfg['lr'], momentum=0.9, weight_decay=1e-4) else: optimizer = build_optimizer(model, cfg['optimizer']) for group in optimizer.param_groups: group.setdefault('initial_lr', group['lr']) if rank == 0: logger.info(model) logger.info(f'Total params: {count_params(model):.1f}M\n') if hasattr(model, 'backbone'): logger.info(f'Backbone params (training/total): {count_training_params(model.backbone):.1f}M/{count_params(model.backbone):.1f}M\n') if hasattr(model, 'decode_head'): logger.info(f'Decoder params (training/total): {count_training_params(model.decode_head):.1f}M/{count_params(model.decode_head):.1f}M\n') local_rank = int(os.environ["LOCAL_RANK"]) model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) model.cuda() model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank], broadcast_buffers=False, output_device=local_rank, find_unused_parameters=True) if cfg['criterion']['name'] == 'CELoss': criterion_l = nn.CrossEntropyLoss(**cfg['criterion']['kwargs']).cuda(local_rank) elif cfg['criterion']['name'] == 'OHEM': criterion_l = ProbOhemCrossEntropy2d(**cfg['criterion']['kwargs']).cuda(local_rank) elif cfg['criterion']['name'] == 'mmseg': criterion_l = None else: raise ValueError(cfg['criterion_u']['name']) if cfg['criterion_u'] == 'CELoss': criterion_u = nn.CrossEntropyLoss(reduction='none').cuda(local_rank) elif cfg['criterion_u'] == 'mmseg': criterion_u = None else: raise ValueError(cfg['criterion_u']) if maskclip_consistency_lambda != 0: if mcc_loss_reduce == 'mean': criterion_mc = nn.CrossEntropyLoss(ignore_index=255).cuda(local_rank) elif mcc_loss_reduce in ['mean_valid', 'mean_all']: criterion_mc = nn.CrossEntropyLoss(ignore_index=255, reduction='none').cuda(local_rank) else: raise ValueError(mcc_loss_reduce) trainset_u = SemiDataset(cfg, 'train_u', id_path=unlabeled_id_path) trainset_l = SemiDataset(cfg, 'train_l', id_path=labeled_id_path, nsample=len(trainset_u.ids)) valset = SemiDataset(cfg, 'val') trainsampler_l = torch.utils.data.distributed.DistributedSampler(trainset_l) trainloader_l = DataLoader(trainset_l, batch_size=cfg['batch_size'], pin_memory=True, num_workers=1, drop_last=True, sampler=trainsampler_l) trainsampler_u = torch.utils.data.distributed.DistributedSampler(trainset_u) trainloader_u = DataLoader(trainset_u, batch_size=cfg['batch_size'], pin_memory=True, num_workers=1, drop_last=True, sampler=trainsampler_u) valsampler = torch.utils.data.distributed.DistributedSampler(valset) valloader = DataLoader(valset, batch_size=1, pin_memory=True, num_workers=1, drop_last=False, sampler=valsampler) palette = get_palette(cfg['dataset']) if cfg['iters'] is not None: assert cfg['epochs'] is None cfg['epochs'] = math.ceil(cfg['iters'] / len(trainloader_u)) total_iters = len(trainloader_u) * cfg['epochs'] scheduler_max_iters = cfg.get('scheduler_max_iters', total_iters) assert scheduler_max_iters >= total_iters if rank == 0: logger.info(f'Train for {cfg["epochs"]} epochs / {total_iters} iterations.') previous_best = 0.0 epoch = -1 for epoch in range(epoch + 1, cfg['epochs']): if rank == 0: logger.info('===========> Epoch: {:}, LR: {:.5f}, Previous best: {:.2f}'.format( epoch, optimizer.param_groups[0]['lr'], previous_best))
# Copyright 2023 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def compute_mc_loss(pred, mask, ign): l_mc = criterion_mc(pred, mask) if mcc_loss_reduce == 'mean_valid': l_mc = l_mc.sum() / (ign != 255).sum() if mcc_loss_reduce == 'mean_all': l_mc = l_mc.sum() / ign.numel() return l_mc if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--config', type=str, required=True) parser.add_argument('--local_rank', default=0, type=int) parser.add_argument('--port', default=None, type=int) args = parser.parse_args() with open(args.config, "r") as fp: cfg = yaml.load(fp, Loader=yaml.Loader) labeled_id_path = f'splits/{cfg["dataset"]}/{cfg["split"]}/labeled.txt' unlabeled_id_path = f'splits/{cfg["dataset"]}/{cfg["split"]}/unlabeled.txt' logger = init_log('global', logging.INFO) logger.propagate = 0 mmcv.utils.get_logger('mmcv').setLevel('WARNING') rank, world_size = setup_distributed(port=args.port) if cfg['nccl_p2p_disable']: os.environ["NCCL_P2P_DISABLE"] = str(1) if rank == 0: timestr = datetime.now().strftime("%y%m%d-%H%M") uid = str(uuid.uuid4())[:5] run_name = f'{timestr}_{cfg["name"]}_v{__version__}_{uid}'.replace('.', '-') save_path = f'exp/exp-{cfg["exp"]}/{run_name}' os.makedirs(save_path, exist_ok=True) formatter = logging.Formatter(fmt='[%(asctime)s] [%(levelname)-8s] %(message)s') fileHandler = logging.FileHandler(f'{save_path}/debug.log') fileHandler.setFormatter(formatter) logger.addHandler(fileHandler) all_args = {**cfg, **vars(args), 'labeled_id_path': labeled_id_path, 'unlabeled_id_path': unlabeled_id_path, 'ngpus': world_size, 'run_name': run_name, 'save_path': save_path, 'exec_git_rev': get_git_revision(), 'exec_version': __version__} logger.info('{}\n'.format(pprint.pformat(all_args))) writer = SummaryWriter(save_path) shutil.copyfile(args.config, os.path.join(save_path, 'config.yaml')) with open(os.path.join(save_path, 'all_args.yaml'), 'w') as f: yaml.dump(all_args, f, default_flow_style=None, sort_keys=False, indent=2) gen_code_archive(save_path) cudnn.enabled = True cudnn.benchmark = True maskclip_consistency_lambda = cfg['maskclip_consistency_lambda'] mcc_conf_thresh = cfg['mcc_conf_thresh'] mcc_loss_reduce = cfg['mcc_loss_reduce'] assert mcc_loss_reduce in ['mean', 'mean_valid', 'mean_all'] assert cfg['use_fp'] assert cfg['pleval'] model = build_model(cfg) if 'optimizer' not in cfg: optimizer = SGD([{'params': model.backbone.parameters(), 'lr': cfg['lr']}, {'params': [param for name, param in model.named_parameters() if 'backbone' not in name], 'lr': cfg['lr'] * cfg['lr_multi']}], lr=cfg['lr'], momentum=0.9, weight_decay=1e-4) else: optimizer = build_optimizer(model, cfg['optimizer']) for group in optimizer.param_groups: group.setdefault('initial_lr', group['lr']) if rank == 0: logger.info(model) logger.info(f'Total params: {count_params(model):.1f}M\n') if hasattr(model, 'backbone'): logger.info(f'Backbone params (training/total): {count_training_params(model.backbone):.1f}M/{count_params(model.backbone):.1f}M\n') if hasattr(model, 'decode_head'): logger.info(f'Decoder params (training/total): {count_training_params(model.decode_head):.1f}M/{count_params(model.decode_head):.1f}M\n') local_rank = int(os.environ["LOCAL_RANK"]) model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) model.cuda() model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[local_rank], broadcast_buffers=False, output_device=local_rank, find_unused_parameters=True) if cfg['criterion']['name'] == 'CELoss': criterion_l = nn.CrossEntropyLoss(**cfg['criterion']['kwargs']).cuda(local_rank) elif cfg['criterion']['name'] == 'OHEM': criterion_l = ProbOhemCrossEntropy2d(**cfg['criterion']['kwargs']).cuda(local_rank) elif cfg['criterion']['name'] == 'mmseg': criterion_l = None else: raise ValueError(cfg['criterion_u']['name']) if cfg['criterion_u'] == 'CELoss': criterion_u = nn.CrossEntropyLoss(reduction='none').cuda(local_rank) elif cfg['criterion_u'] == 'mmseg': criterion_u = None else: raise ValueError(cfg['criterion_u']) if maskclip_consistency_lambda != 0: if mcc_loss_reduce == 'mean': criterion_mc = nn.CrossEntropyLoss(ignore_index=255).cuda(local_rank) elif mcc_loss_reduce in ['mean_valid', 'mean_all']: criterion_mc = nn.CrossEntropyLoss(ignore_index=255, reduction='none').cuda(local_rank) else: raise ValueError(mcc_loss_reduce) trainset_u = SemiDataset(cfg, 'train_u', id_path=unlabeled_id_path) trainset_l = SemiDataset(cfg, 'train_l', id_path=labeled_id_path, nsample=len(trainset_u.ids)) valset = SemiDataset(cfg, 'val') trainsampler_l = torch.utils.data.distributed.DistributedSampler(trainset_l) trainloader_l = DataLoader(trainset_l, batch_size=cfg['batch_size'], pin_memory=True, num_workers=1, drop_last=True, sampler=trainsampler_l) trainsampler_u = torch.utils.data.distributed.DistributedSampler(trainset_u) trainloader_u = DataLoader(trainset_u, batch_size=cfg['batch_size'], pin_memory=True, num_workers=1, drop_last=True, sampler=trainsampler_u) valsampler = torch.utils.data.distributed.DistributedSampler(valset) valloader = DataLoader(valset, batch_size=1, pin_memory=True, num_workers=1, drop_last=False, sampler=valsampler) palette = get_palette(cfg['dataset']) if cfg['iters'] is not None: assert cfg['epochs'] is None cfg['epochs'] = math.ceil(cfg['iters'] / len(trainloader_u)) total_iters = len(trainloader_u) * cfg['epochs'] scheduler_max_iters = cfg.get('scheduler_max_iters', total_iters) assert scheduler_max_iters >= total_iters if rank == 0: logger.info(f'Train for {cfg["epochs"]} epochs / {total_iters} iterations.') previous_best = 0.0 epoch = -1 for epoch in range(epoch + 1, cfg['epochs']): if rank == 0: logger.info('===========> Epoch: {:}, LR: {:.5f}, Previous best: {:.2f}'.format( epoch, optimizer.param_groups[0]['lr'], previous_best))
log_avg = DictAverageMeter()
13
2023-11-02 14:49:38+00:00
12k
intellerce/controlanimate
animatediff/models/unet.py
[ { "identifier": "CrossAttnDownBlock3D", "path": "animatediff/models/unet_blocks.py", "snippet": "class CrossAttnDownBlock3D(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n temb_channels: int,\n dropout: float = 0.0,\n num_layers...
from dataclasses import dataclass from typing import List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.models.modeling_utils import ModelMixin from diffusers.loaders import UNet2DConditionLoadersMixin from diffusers.utils import BaseOutput, logging from diffusers.models.embeddings import TimestepEmbedding, Timesteps from .unet_blocks import ( CrossAttnDownBlock3D, CrossAttnUpBlock3D, DownBlock3D, UNetMidBlock3DCrossAttn, UpBlock3D, get_down_block, get_up_block, ) from .resnet import InflatedConv3d, InflatedGroupNorm from typing import Any, Dict, List, Optional, Tuple, Union from diffusers.models.attention_processor import ( ADDED_KV_ATTENTION_PROCESSORS, CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnAddedKVProcessor, AttnProcessor, ) from diffusers.utils import WEIGHTS_NAME, SAFETENSORS_WEIGHTS_NAME import os import json import pdb import torch import torch.nn as nn import torch.utils.checkpoint import safetensors
8,470
time_embedding_type: str = "positional", time_embedding_dim: Optional[int] = None, time_embedding_act_fn: Optional[str] = None, timestep_post_act: Optional[str] = None, time_cond_proj_dim: Optional[int] = None, # Additional use_motion_module = False, motion_module_resolutions = ( 1,2,4,8 ), motion_module_mid_block = False, motion_module_decoder_only = False, motion_module_type = None, motion_module_kwargs = {}, unet_use_cross_frame_attention = None, unet_use_temporal_attention = None, ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] # self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) self.time_embedding = TimestepEmbedding( timestep_input_dim, time_embed_dim, act_fn=act_fn, post_act_fn=timestep_post_act, cond_proj_dim=time_cond_proj_dim, ) # 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) if class_embeddings_concat: # The time embeddings are concatenated with the class embeddings. The dimension of the # time embeddings passed to the down, middle, and up blocks is twice the dimension of the # regular time embeddings blocks_time_embed_dim = time_embed_dim * 2 else: blocks_time_embed_dim = time_embed_dim # self.time_embedding = TimestepEmbedding( # timestep_input_dim, # time_embed_dim, # act_fn=act_fn, # post_act_fn=timestep_post_act, # cond_proj_dim=time_cond_proj_dim, # ) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): res = 2 ** i input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block, in_channels=input_channel, out_channels=output_channel, temb_channels=time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_inflated_groupnorm=use_inflated_groupnorm, use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock3DCrossAttn":
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet3DConditionOutput(BaseOutput): sample: torch.FloatTensor class UNet3DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin): _supports_gradient_checkpointing = True @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ( "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D", ), mid_block_type: str = "UNetMidBlock3DCrossAttn", up_block_types: Tuple[str] = ( "UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D" ), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", use_inflated_groupnorm=False, addition_embed_type: Optional[str] = None, addition_time_embed_dim: Optional[int] = None, dropout: float = 0.0, encoder_hid_dim: Optional[int] = None, encoder_hid_dim_type: Optional[str] = None, conv_in_kernel: int = 3, conv_out_kernel: int = 3, attention_type: str = "default", class_embeddings_concat: bool = False, mid_block_only_cross_attention: Optional[bool] = None, cross_attention_norm: Optional[str] = None, addition_embed_type_num_heads=64, transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1, time_embedding_type: str = "positional", time_embedding_dim: Optional[int] = None, time_embedding_act_fn: Optional[str] = None, timestep_post_act: Optional[str] = None, time_cond_proj_dim: Optional[int] = None, # Additional use_motion_module = False, motion_module_resolutions = ( 1,2,4,8 ), motion_module_mid_block = False, motion_module_decoder_only = False, motion_module_type = None, motion_module_kwargs = {}, unet_use_cross_frame_attention = None, unet_use_temporal_attention = None, ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] # self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) self.time_embedding = TimestepEmbedding( timestep_input_dim, time_embed_dim, act_fn=act_fn, post_act_fn=timestep_post_act, cond_proj_dim=time_cond_proj_dim, ) # 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) if class_embeddings_concat: # The time embeddings are concatenated with the class embeddings. The dimension of the # time embeddings passed to the down, middle, and up blocks is twice the dimension of the # regular time embeddings blocks_time_embed_dim = time_embed_dim * 2 else: blocks_time_embed_dim = time_embed_dim # self.time_embedding = TimestepEmbedding( # timestep_input_dim, # time_embed_dim, # act_fn=act_fn, # post_act_fn=timestep_post_act, # cond_proj_dim=time_cond_proj_dim, # ) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): res = 2 ** i input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block, in_channels=input_channel, out_channels=output_channel, temb_channels=time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_inflated_groupnorm=use_inflated_groupnorm, use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock3DCrossAttn":
self.mid_block = UNetMidBlock3DCrossAttn(
3
2023-11-04 01:35:44+00:00
12k
Zaczero/openstreetmap-ng
src/services/user_signup_service.py
[ { "identifier": "DB", "path": "src/db.py", "snippet": "DB = async_sessionmaker(\n DB_ENGINE,\n expire_on_commit=False,\n)" }, { "identifier": "auth_user", "path": "src/lib/auth.py", "snippet": "def auth_user() -> User | None:\n \"\"\"\n Get the authenticated user.\n \"\"\"...
from fastapi import Request from src.db import DB from src.lib.auth import auth_user, manual_auth_context from src.lib.email import Email from src.lib.message_collector import MessageCollector from src.lib.password_hash import PasswordHash from src.lib.translation import t, translation_languages from src.models.db.user import User from src.models.mail_from_type import MailFromType from src.models.msgspec.user_token_struct import UserTokenStruct from src.models.str import EmailStr, PasswordStr, UserNameStr from src.models.user_status import UserStatus from src.repositories.user_repository import UserRepository from src.services.auth_service import AuthService from src.services.mail_service import MailService from src.services.user_token_account_confirm_service import UserTokenAccountConfirmService from src.utils import parse_request_ip
7,364
class UserSignupService: @staticmethod async def signup( request: Request, collector: MessageCollector, *, display_name: UserNameStr, email: EmailStr, password: PasswordStr, ) -> UserTokenStruct: """ Create a new user. Returns a new user session token. """ # some early validation if not await UserRepository.check_display_name_available(display_name): collector.raise_error('display_name', t('user.display_name_already_taken')) if not await UserRepository.check_email_available(email): collector.raise_error('email', t('user.email_already_taken')) if not await Email.validate_dns(email): collector.raise_error('email', t('user.invalid_email')) # precompute values to reduce transaction time password_hashed = PasswordHash.default().hash(password) created_ip = parse_request_ip(request) languages = translation_languages() # create user async with DB() as session: user = User( email=email, display_name=display_name, password_hashed=password_hashed, created_ip=created_ip, status=UserStatus.pending, auth_provider=None, # TODO: support auth_uid=None, languages=languages, ) session.add(user) with manual_auth_context(user): await UserSignupService.send_confirm_email() return await AuthService.create_session(user.id) @staticmethod async def send_confirm_email() -> None: """ Send a confirmation email for the account. """ token = await UserTokenAccountConfirmService.create() await MailService.schedule( from_user=None,
class UserSignupService: @staticmethod async def signup( request: Request, collector: MessageCollector, *, display_name: UserNameStr, email: EmailStr, password: PasswordStr, ) -> UserTokenStruct: """ Create a new user. Returns a new user session token. """ # some early validation if not await UserRepository.check_display_name_available(display_name): collector.raise_error('display_name', t('user.display_name_already_taken')) if not await UserRepository.check_email_available(email): collector.raise_error('email', t('user.email_already_taken')) if not await Email.validate_dns(email): collector.raise_error('email', t('user.invalid_email')) # precompute values to reduce transaction time password_hashed = PasswordHash.default().hash(password) created_ip = parse_request_ip(request) languages = translation_languages() # create user async with DB() as session: user = User( email=email, display_name=display_name, password_hashed=password_hashed, created_ip=created_ip, status=UserStatus.pending, auth_provider=None, # TODO: support auth_uid=None, languages=languages, ) session.add(user) with manual_auth_context(user): await UserSignupService.send_confirm_email() return await AuthService.create_session(user.id) @staticmethod async def send_confirm_email() -> None: """ Send a confirmation email for the account. """ token = await UserTokenAccountConfirmService.create() await MailService.schedule( from_user=None,
from_type=MailFromType.system,
9
2023-11-04 01:12:13+00:00
12k
codefuse-ai/Collinear-Constrained-Attention
train/trainer/atorch_trainer.py
[ { "identifier": "print_rank_0", "path": "utils/common_utils.py", "snippet": "TASK2ID = {}\nID2TASK = {}\n L = args.num_hidden_layers\n V = args.vocab_size\ndef get_rank():\ndef get_local_rank():\ndef is_main_process():\ndef is_local_main_process():\ndef print_rank_0(*message):\ndef get_world_size(...
import datetime import json import logging import math import os import random import re import shutil import time import warnings import gc import numpy as np import atorch import torch from functools import partial from pathlib import Path from deepspeed.ops.adam import DeepSpeedCPUAdam from torch.distributed.fsdp import FullStateDictConfig from torch.distributed.fsdp import FullyShardedDataParallel as FSDP from torch.distributed.fsdp import StateDictType from torch.optim.lr_scheduler import LambdaLR, CosineAnnealingLR, CosineAnnealingWarmRestarts from torch.utils.data import DataLoader from torch.utils.data.distributed import DistributedSampler from torch.utils.tensorboard import SummaryWriter from tqdm.auto import tqdm from transformers import get_scheduler as get_scheduler_trans from transformers.modeling_utils import PreTrainedModel, unwrap_model from transformers.trainer import ( OPTIMIZER_NAME, SCHEDULER_NAME, TRAINER_STATE_NAME, TRAINING_ARGS_NAME ) from transformers.trainer_pt_utils import reissue_pt_warnings from transformers.trainer_utils import ( PREFIX_CHECKPOINT_DIR, ) from transformers.utils import WEIGHTS_NAME from torch.nn import CrossEntropyLoss from utils.common_utils import print_rank_0, get_tflops_megatron, get_computation_speed, TASK2ID, ID2TASK, EarlyStopping, logger from utils.auto_accelerate_utils import FAMO, get_ltor_masks_and_position_ids, SelfPacedStatus from atorch.auto import auto_accelerate from atorch.utils.version import torch_version from model.gpt_neox.modeling_gpt_neox import GPTNeoXLayer, GPTNeoXAttention, GPTNeoXMLP from model.llama.modeling_llama import LlamaDecoderLayer, LlamaAttention, LlamaMLP from model.glm.modeling_glm import GLMBlock from torch.cuda.amp import GradScaler from apex.optimizers import FusedSGD from model.peft.modeling_peft import PeftModel
9,788
# 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. HYPER_PARAMETER_NAME = 'hyper_parameters.json' ATORCH_CHECKPOINT_NAME = 'atorch_checkpoint.bin' EPOCH_CHECKPOINT_NAME = 'epoch' FAMO_CHECKPOINT_NAME = 'famo_checkpoint' EMA_CHECKPOINT_NAME = 'ema_checkpoint' # logger = logging.getLogger(__name__) def is_local_main_process(): return atorch.local_rank() == 0 def is_global_main_process(): return atorch.rank() == 0 def has_inf_or_nan(x): try: # if x is half, the .float() incurs an additional deep copy, but it's necessary if # Pytorch's .sum() creates a one-element tensor of the same type as x # (which is true for some recent version of pytorch). cpu_sum = float(x.float().sum()) # More efficient version that can be used if .sum() returns a Python scalar # cpu_sum = float(x.sum()) except RuntimeError as instance: # We want to check if inst is actually an overflow exception. # RuntimeError could come from a different error. # If so, we still want the exception to propagate. if "value cannot be converted" not in instance.args[0]: raise return True else: if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum: return True return False def count_model_params(model): trainable_params = 0 all_params = 0 for param in model.parameters(): num_params = param.numel() all_params += num_params if param.requires_grad: trainable_params += num_params return all_params, trainable_params class AtorchArguments: def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) def get_linear_schedule_with_log_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1): def lr_lambda(current_step: int): inverse_log_warm_up = 1.0 / math.log(num_warmup_steps) if current_step == 0: return 0.0 if current_step < num_warmup_steps: return inverse_log_warm_up * math.log(current_step) return max( 0.0, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)) ) return LambdaLR(optimizer, lr_lambda, last_epoch) def get_scheduler(name, optimizer, num_warmup_steps, num_training_steps): scheduler_map = { 'log_warmup_linear_decay': get_linear_schedule_with_log_warmup} try: lr_scheduler = get_scheduler_trans( name, optimizer, num_warmup_steps, num_training_steps) return lr_scheduler except Exception: schedule_func = scheduler_map[name] return schedule_func(optimizer, num_warmup_steps, num_training_steps) class AtorchTrainer: def __init__(self, model, args, train_dataset, valid_dataset, tokenizer=None, callbacks=None, no_save_atorch_checkpoint=None, save_pytorch_model_bin_checkpoint=True, train_peft=False, rank=0, max_shard_size='10GB', files_to_save=None, args_to_save=None, data_collator=None, my_loss_func=None, **kwargs, ): self.args = args self.TASK2ID = TASK2ID
#!/usr/bin/env python # coding=utf-8 # Copyright (c) 2023 Ant Group. 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. HYPER_PARAMETER_NAME = 'hyper_parameters.json' ATORCH_CHECKPOINT_NAME = 'atorch_checkpoint.bin' EPOCH_CHECKPOINT_NAME = 'epoch' FAMO_CHECKPOINT_NAME = 'famo_checkpoint' EMA_CHECKPOINT_NAME = 'ema_checkpoint' # logger = logging.getLogger(__name__) def is_local_main_process(): return atorch.local_rank() == 0 def is_global_main_process(): return atorch.rank() == 0 def has_inf_or_nan(x): try: # if x is half, the .float() incurs an additional deep copy, but it's necessary if # Pytorch's .sum() creates a one-element tensor of the same type as x # (which is true for some recent version of pytorch). cpu_sum = float(x.float().sum()) # More efficient version that can be used if .sum() returns a Python scalar # cpu_sum = float(x.sum()) except RuntimeError as instance: # We want to check if inst is actually an overflow exception. # RuntimeError could come from a different error. # If so, we still want the exception to propagate. if "value cannot be converted" not in instance.args[0]: raise return True else: if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum: return True return False def count_model_params(model): trainable_params = 0 all_params = 0 for param in model.parameters(): num_params = param.numel() all_params += num_params if param.requires_grad: trainable_params += num_params return all_params, trainable_params class AtorchArguments: def __init__(self, **kwargs): for key, value in kwargs.items(): setattr(self, key, value) def get_linear_schedule_with_log_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1): def lr_lambda(current_step: int): inverse_log_warm_up = 1.0 / math.log(num_warmup_steps) if current_step == 0: return 0.0 if current_step < num_warmup_steps: return inverse_log_warm_up * math.log(current_step) return max( 0.0, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)) ) return LambdaLR(optimizer, lr_lambda, last_epoch) def get_scheduler(name, optimizer, num_warmup_steps, num_training_steps): scheduler_map = { 'log_warmup_linear_decay': get_linear_schedule_with_log_warmup} try: lr_scheduler = get_scheduler_trans( name, optimizer, num_warmup_steps, num_training_steps) return lr_scheduler except Exception: schedule_func = scheduler_map[name] return schedule_func(optimizer, num_warmup_steps, num_training_steps) class AtorchTrainer: def __init__(self, model, args, train_dataset, valid_dataset, tokenizer=None, callbacks=None, no_save_atorch_checkpoint=None, save_pytorch_model_bin_checkpoint=True, train_peft=False, rank=0, max_shard_size='10GB', files_to_save=None, args_to_save=None, data_collator=None, my_loss_func=None, **kwargs, ): self.args = args self.TASK2ID = TASK2ID
self.ID2TASK = ID2TASK
0
2023-11-02 01:37:01+00:00
12k
bytedance/cryostar
projects/star/train_density.py
[ { "identifier": "StarfileDataSet", "path": "cryostar/utils/dataio.py", "snippet": "class StarfileDataSet(Dataset):\n\n def __init__(self, cfg: StarfileDatasetConfig):\n super().__init__()\n self.cfg = cfg\n self.df = starfile.read(Path(cfg.starfile_path))\n\n if \"optics\"...
import os import os.path as osp import einops import lightning.pytorch as pl import numpy as np import torch from lightning.pytorch.strategies import DDPStrategy from lightning.pytorch.utilities import rank_zero_only from torch.utils.data import DataLoader from tqdm import tqdm from mmengine import mkdir_or_exist from cryostar.utils.dataio import StarfileDataSet, StarfileDatasetConfig from cryostar.nerf.volume_utils import ImplicitFourierVolume from cryostar.utils.transforms import SpatialGridTranslate, FourierGridTranslate from cryostar.utils.ctf_utils import CTFRelion, CTFCryoDRGN from cryostar.utils.fft_utils import (fourier_to_primal_2d, primal_to_fourier_2d) from cryostar.utils.latent_space_utils import sample_along_pca, get_nearest_point, cluster_kmeans from cryostar.utils.misc import (pl_init_exp, create_circular_mask, log_to_current, pretty_dict) from cryostar.utils.losses import calc_kl_loss from cryostar.utils.ml_modules import VAEEncoder, reparameterize from cryostar.utils.mrc_tools import save_mrc from miscs import infer_ctf_params_from_config
10,366
log_to_current = rank_zero_only(log_to_current) TASK_NAME = "density" class CryoModel(pl.LightningModule): def __init__(self, cfg, dataset): super().__init__() self.cfg = cfg self.dataset = dataset self.z_dim = cfg.model.z_dim self.history_saved_dirs = [] if cfg.extra_input_data_attr.given_z is None and self.z_dim != 0: if cfg.model.enc_space == "real": self.encoder = VAEEncoder(self.cfg.data_process.down_side_shape**2, cfg.model.hidden, self.z_dim, num_hidden_layers=4) elif cfg.model.enc_space == "fourier": self.encoder = VAEEncoder(2 * self.cfg.data_process.down_side_shape**2, cfg.model.hidden, self.z_dim, num_hidden_layers=4) else: raise NotImplementedError if cfg.model.shift_method == "interp": self.translate = SpatialGridTranslate(self.cfg.data_process.down_side_shape, ) log_to_current("We will deprecate `model.shift_method=interp` in a future version, use `model.shift_method=fft` instead.") elif cfg.model.shift_method == "fft": self.f_translate = FourierGridTranslate(self.cfg.data_process.down_side_shape, ) else: raise NotImplementedError ctf_params = infer_ctf_params_from_config(cfg) if cfg.model.ctf == "v1": self.ctf = CTFRelion(**ctf_params, num_particles=len(dataset)) log_to_current("We will deprecate `model.ctf=v1` in a future version, use `model.ctf=v2` instead.") elif cfg.model.ctf == "v2": self.ctf = CTFCryoDRGN(**ctf_params, num_particles=len(dataset)) else: raise NotImplementedError log_to_current(ctf_params) self.vol = ImplicitFourierVolume( self.z_dim, self.cfg.data_process.down_side_shape, self.cfg.loss.mask_rad_for_image_loss, { "net_type": cfg.model.net_type, "pe_dim": self.cfg.data_process.down_side_shape, "D": self.cfg.data_process.down_side_shape, "pe_type": cfg.model.pe_type, "force_symmetry": False, "hidden": cfg.model.hidden, })
log_to_current = rank_zero_only(log_to_current) TASK_NAME = "density" class CryoModel(pl.LightningModule): def __init__(self, cfg, dataset): super().__init__() self.cfg = cfg self.dataset = dataset self.z_dim = cfg.model.z_dim self.history_saved_dirs = [] if cfg.extra_input_data_attr.given_z is None and self.z_dim != 0: if cfg.model.enc_space == "real": self.encoder = VAEEncoder(self.cfg.data_process.down_side_shape**2, cfg.model.hidden, self.z_dim, num_hidden_layers=4) elif cfg.model.enc_space == "fourier": self.encoder = VAEEncoder(2 * self.cfg.data_process.down_side_shape**2, cfg.model.hidden, self.z_dim, num_hidden_layers=4) else: raise NotImplementedError if cfg.model.shift_method == "interp": self.translate = SpatialGridTranslate(self.cfg.data_process.down_side_shape, ) log_to_current("We will deprecate `model.shift_method=interp` in a future version, use `model.shift_method=fft` instead.") elif cfg.model.shift_method == "fft": self.f_translate = FourierGridTranslate(self.cfg.data_process.down_side_shape, ) else: raise NotImplementedError ctf_params = infer_ctf_params_from_config(cfg) if cfg.model.ctf == "v1": self.ctf = CTFRelion(**ctf_params, num_particles=len(dataset)) log_to_current("We will deprecate `model.ctf=v1` in a future version, use `model.ctf=v2` instead.") elif cfg.model.ctf == "v2": self.ctf = CTFCryoDRGN(**ctf_params, num_particles=len(dataset)) else: raise NotImplementedError log_to_current(ctf_params) self.vol = ImplicitFourierVolume( self.z_dim, self.cfg.data_process.down_side_shape, self.cfg.loss.mask_rad_for_image_loss, { "net_type": cfg.model.net_type, "pe_dim": self.cfg.data_process.down_side_shape, "D": self.cfg.data_process.down_side_shape, "pe_type": cfg.model.pe_type, "force_symmetry": False, "hidden": cfg.model.hidden, })
mask = create_circular_mask(self.cfg.data_process.down_side_shape, self.cfg.data_process.down_side_shape, None,
12
2023-11-06 07:15:26+00:00
12k
xyongLu/SBCFormer
main.py
[ { "identifier": "Mixup", "path": "mixup.py", "snippet": "class Mixup:\n \"\"\" Mixup/Cutmix that applies different params to each element or whole batch\n\n Args:\n mixup_alpha (float): mixup alpha value, mixup is active if > 0.\n cutmix_alpha (float): cutmix alpha value, cutmix is a...
import argparse import datetime import numpy as np import time import torch import torch.backends.cudnn as cudnn import json import utils from pathlib import Path from mixup import Mixup from timm.models import create_model from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy from timm.scheduler import create_scheduler from timm.optim import create_optimizer from timm.utils import NativeScaler, get_state_dict, ModelEma from datasets import build_dataset from engine import train_one_epoch, evaluate from losses import DistillationLoss from samplers import RASampler from models import *
8,424
data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: mixup_fn = Mixup( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.nb_classes) print(f"Creating model: {args.model}") model = create_model( args.model, pretrained=False, num_classes=args.nb_classes, drop_rate=args.drop, drop_path_rate=args.drop_path, drop_block_rate=None,) if args.finetune: if args.finetune.startswith('https'): checkpoint = torch.hub.load_state_dict_from_url( args.finetune, map_location='cpu', check_hash=True) else: checkpoint = torch.load(args.finetune, map_location='cpu') checkpoint_model = checkpoint['model'] state_dict = model.state_dict() for k in ['head.weight', 'head.bias', 'head_dist.weight', 'head_dist.bias']: if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape: print(f"Removing key {k} from pretrained checkpoint") del checkpoint_model[k] # interpolate position embedding pos_embed_checkpoint = checkpoint_model['pos_embed'] embedding_size = pos_embed_checkpoint.shape[-1] num_patches = model.patch_embed.num_patches num_extra_tokens = model.pos_embed.shape[-2] - num_patches # height (== width) for the checkpoint position embedding orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) # height (== width) for the new position embedding new_size = int(num_patches ** 0.5) # class_token and dist_token are kept unchanged extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] # only the position tokens are interpolated pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) pos_tokens = torch.nn.functional.interpolate( pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) checkpoint_model['pos_embed'] = new_pos_embed model.load_state_dict(checkpoint_model, strict=False) model.to(device) # flops, params = get_model_complexity_info(model, (3,args.input_size, args.input_size),as_strings=True,print_per_layer_stat=False) # print("flops: %s |params: %s" % (flops,params)) model_ema = None if args.model_ema: # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper model_ema = ModelEma( model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else '', resume='') model_without_ddp = model if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True) model_without_ddp = model.module n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print('number of params:', n_parameters) linear_scaled_lr = args.lr * args.batch_size * utils.get_world_size() / 512.0 args.lr = linear_scaled_lr optimizer = create_optimizer(args, model_without_ddp) loss_scaler = NativeScaler() lr_scheduler, _ = create_scheduler(args, optimizer) criterion = LabelSmoothingCrossEntropy() if args.mixup > 0.: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif args.smoothing: criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing) else: criterion = torch.nn.CrossEntropyLoss() teacher_model = None # if args.distillation_type != 'none': # assert args.teacher_path, 'need to specify teacher-path when using distillation' # print(f"Creating teacher model: {args.teacher_model}") # teacher_model = create_model( # args.teacher_model, # pretrained=False, # num_classes=args.nb_classes, # global_pool='avg', # ) # teacher_model = RegNetY_200MF() # if args.teacher_path.startswith('https'): # checkpoint = torch.hub.load_state_dict_from_url( # args.teacher_path, map_location='cpu', check_hash=True) # else: # checkpoint = torch.load(args.teacher_path, map_location='cpu') # teacher_model.load_state_dict(checkpoint['model']) # teacher_model.to(device) # teacher_model.eval() # wrap the criterion in our custom DistillationLoss, which # just dispatches to the original criterion if args.distillation_type is 'none'
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. # from ptflops import get_model_complexity_info device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print("running on {} device.".format(device)) def get_args_parser(): parser = argparse.ArgumentParser('SlenderViT training and evaluation script', add_help=False) # Model parameters parser.add_argument('--uni-note', default='', type=str, help='unique note on the name of model to train') parser.add_argument('--model', default='SBCFormer_B', type=str, metavar='MODEL', help='Name of model to train.') parser.add_argument('--epochs', default=300, type=int) parser.add_argument('--input-size', default=224, type=int, help='images input size') parser.add_argument('--in-chans', type=int, default=3, help='the channel of inputs ') parser.add_argument('--batch-size', default=30, type=int) parser.add_argument('--drop', type=float, default=0., metavar='PCT', help='Dropout rate (default: 0.)') parser.add_argument('--drop-path', type=float, default=0.1, metavar='PCT', help='Drop path rate (default: 0.1)') parser.add_argument('--model-ema', action='store_true') parser.add_argument('--no-model-ema', action='store_false', dest='model_ema') parser.set_defaults(model_ema=False) parser.add_argument('--model-ema-decay', type=float, default=0.99996, help='') parser.add_argument('--model-ema-force-cpu', action='store_true', default=False, help='') # Optimizer parameters parser.add_argument('--opt', default='adamw', type=str, metavar='OPTIMIZER', help='Optimizer (default: "adamw"') parser.add_argument('--opt-eps', default=1e-8, type=float, metavar='EPSILON', help='Optimizer Epsilon (defaudevice = torch.device(args.device)ult: None, no clipping)') parser.add_argument('--clip-grad', type=float, default=5, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_argument('--momentum', type=float, default=0.9, metavar='M', help='SGD momentum (default: 0.9)') parser.add_argument('--weight-decay', type=float, default=0.05, help='weight decay (default: 0.05)') # Learning rate schedule parameters parser.add_argument('--sched', default='cosine', type=str, metavar='SCHEDULER', help='LR scheduler (default: "cosine"') parser.add_argument('--lr', type=float, default=2.5e-4, metavar='LR', help='learning rate (default: 5e-4)') parser.add_argument('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct', help='learning rate noise on/off epoch percentages') parser.add_argument('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT', help='learning rate noise limit percent (default: 0.67)') parser.add_argument('--lr-noise-std', type=float, default=1.0, metavar='STDDEV', help='learning rate noise std-dev (default: 1.0)') parser.add_argument('--warmup-lr', type=float, default=1e-6, metavar='LR', help='warmup learning rate (default: 1e-6)') parser.add_argument('--min-lr', type=float, default=1e-5, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0 (1e-5)') parser.add_argument('--decay-epochs', type=float, default=30, metavar='N', help='epoch interval to decay LR') parser.add_argument('--warmup-epochs', type=int, default=5, metavar='N', help='epochs to warmup LR, if scheduler supports') parser.add_argument('--cooldown-epochs', type=int, default=10, metavar='N', help='epochs to cooldown LR at min_lr, after cyclic schedule ends') parser.add_argument('--patience-epochs', type=int, default=10, metavar='N', help='patience epochs for Plateau LR scheduler (default: 10') parser.add_argument('--decay-rate', '--dr', type=float, default=0.1, metavar='RATE', help='LR decay rate (default: 0.1)') # Augmentation parameters parser.add_argument('--color-jitter', type=float, default=0.4, metavar='PCT', help='Color jitter factor (default: 0.4)') parser.add_argument('--aa', type=str, default='rand-m9-mstd0.5-inc1', metavar='NAME', help='Use AutoAugment policy. "v0" or "original". " + "(default: rand-m9-mstd0.5-inc1)'), parser.add_argument('--smoothing', type=float, default=0.1, help='Label smoothing (default: 0.1)') parser.add_argument('--train-interpolation', type=str, default='bicubic', help='Training interpolation (random, bilinear, bicubic default: "bicubic")') parser.add_argument('--repeated-aug', action='store_true') parser.add_argument('--no-repeated-aug', action='store_false', dest='repeated_aug') parser.set_defaults(repeated_aug=False) # * Random Erase params parser.add_argument('--reprob', type=float, default=0.25, metavar='PCT', help='Random erase prob (default: 0.25)') parser.add_argument('--remode', type=str, default='pixel', help='Random erase mode (default: "pixel")') parser.add_argument('--recount', type=int, default=1, help='Random erase count (default: 1)') parser.add_argument('--resplit', action='store_true', default=False, help='Do not random erase first (clean) augmentation split') # * Mixup params parser.add_argument('--mixup', type=float, default=0.8, help='mixup alpha, mixup enabled if > 0. (default: 0.8)') parser.add_argument('--cutmix', type=float, default=1.0, help='cutmix alpha, cutmix enabled if > 0. (default: 1.0)') parser.add_argument('--cutmix-minmax', type=float, nargs='+', default=None, help='cutmix min/max ratio, overrides alpha and enables cutmix if set (default: None)') parser.add_argument('--mixup-prob', type=float, default=1.0, help='Probability of performing mixup or cutmix when either/both is enabled') parser.add_argument('--mixup-switch-prob', type=float, default=0.5, help='Probability of switching to cutmix when both mixup and cutmix enabled') parser.add_argument('--mixup-mode', type=str, default='batch', help='How to apply mixup/cutmix params. Per "batch", "pair", or "elem"') # Distillation parameters distilled parser.add_argument('--distilled', action='store_true', default=False, help='Perform distilled ') parser.add_argument('--teacher-model', default='regnety_200mf', type=str, metavar='MODEL', help='Name of teacher model to train (default: "regnety_160"') parser.add_argument('--teacher-path', type=str, default='') parser.add_argument('--distillation-type', default='none', choices=['none', 'soft', 'hard'], type=str, help="") parser.add_argument('--distillation-alpha', default=0.5, type=float, help="") parser.add_argument('--distillation-tau', default=1.0, type=float, help="") # Finetuning params parser.add_argument('--finetune', default='', help='finetune from checkpoint') # Dataset parameters parser.add_argument('--data-path', default= '../../PythonWork_E/Data/ImageNet_2012',#'./data', type=str, help='dataset path') parser.add_argument('--data-set', default='IMNET', choices=['CIFAR10', 'CIFAR100' , 'IMNET'], type=str, help='Image Net dataset path') parser.add_argument('--inat-category', default='name', choices=['kingdom', 'phylum', 'class', 'order', 'supercategory', 'family', 'genus', 'name'], type=str, help='semantic granularity') parser.add_argument('--output_dir', default='./outputs', help='path where to save, empty for no saving') parser.add_argument('--device', default='cuda', help='device to use for training / testing') parser.add_argument('--seed', default=0, type=int) parser.add_argument('--resume', default= '', help='resume from checkpoint') parser.add_argument('--start_epoch', default=0, type=int, metavar='N', help='start epoch') parser.add_argument('--eval', action='store_true', default=False, help='Perform evaluation only') parser.add_argument('--dist-eval', action='store_true', default=False, help='Enabling distributed evaluation') parser.add_argument('--num_workers', default=10, type=int) parser.add_argument('--pin-mem', action='store_true', help='Pin CPU memory in DataLoader for more efficient (sometimes) transfer to GPU.') parser.add_argument('--no-pin-mem', action='store_false', dest='pin_mem', help='') parser.set_defaults(pin_mem=True) # distributed training parameters parser.add_argument('--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') # test throught parser.add_argument('--throughout', action='store_true', help='Perform throughout only') return parser @torch.no_grad() def throughput(data_loader, model, logger): model.eval() for _, (images, _) in enumerate(data_loader): images = images.cuda(non_blocking=True) batch_size = images.shape[0] for i in range(50): model(images) torch.cuda.synchronize() logger.info(f"throughput averaged with 30 times") tic1 = time.time() for i in range(30): model(images) torch.cuda.synchronize() tic2 = time.time() logger.info(f"batch_size {batch_size} throughput {30 * batch_size / (tic2 - tic1)}") return def main(args): utils.init_distributed_mode(args) print('------------ Options -------------') for key, value in sorted(vars(args).items()): print('%16.16s: %16.16s' % (str(key), str(value))) print('-------------- End ----------------') if args.distillation_type != 'none' and args.finetune and not args.eval: raise NotImplementedError("Finetuning with distillation not yet supported") # fix the seed for reproducibility seed = args.seed + utils.get_rank() torch.manual_seed(seed) np.random.seed(seed) cudnn.benchmark = True dataset_train, args.nb_classes = build_dataset(is_train=True, args=args) dataset_val, args.nb_classes = build_dataset(is_train=False, args=args) if args.distributed: num_tasks = utils.get_world_size() global_rank = utils.get_rank() if args.repeated_aug: sampler_train = RASampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) else: sampler_train = torch.utils.data.DistributedSampler( dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True ) if args.dist_eval: if len(dataset_val) % num_tasks != 0: print('Warning: Enabling distributed evaluation with an eval dataset not divisible by process number. ' 'This will slightly alter validation results as extra duplicate entries are added to achieve ' 'equal num of samples per-process.') sampler_val = torch.utils.data.DistributedSampler( dataset_val, num_replicas=num_tasks, rank=global_rank, shuffle=False) else: sampler_val = torch.utils.data.SequentialSampler(dataset_val) else: sampler_train = torch.utils.data.RandomSampler(dataset_train) sampler_val = torch.utils.data.SequentialSampler(dataset_val) data_loader_train = torch.utils.data.DataLoader( dataset_train, sampler=sampler_train, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=True, ) data_loader_val = torch.utils.data.DataLoader( dataset_val, sampler=sampler_val, batch_size=args.batch_size, num_workers=args.num_workers, pin_memory=args.pin_mem, drop_last=False ) mixup_fn = None mixup_active = args.mixup > 0 or args.cutmix > 0. or args.cutmix_minmax is not None if mixup_active: mixup_fn = Mixup( mixup_alpha=args.mixup, cutmix_alpha=args.cutmix, cutmix_minmax=args.cutmix_minmax, prob=args.mixup_prob, switch_prob=args.mixup_switch_prob, mode=args.mixup_mode, label_smoothing=args.smoothing, num_classes=args.nb_classes) print(f"Creating model: {args.model}") model = create_model( args.model, pretrained=False, num_classes=args.nb_classes, drop_rate=args.drop, drop_path_rate=args.drop_path, drop_block_rate=None,) if args.finetune: if args.finetune.startswith('https'): checkpoint = torch.hub.load_state_dict_from_url( args.finetune, map_location='cpu', check_hash=True) else: checkpoint = torch.load(args.finetune, map_location='cpu') checkpoint_model = checkpoint['model'] state_dict = model.state_dict() for k in ['head.weight', 'head.bias', 'head_dist.weight', 'head_dist.bias']: if k in checkpoint_model and checkpoint_model[k].shape != state_dict[k].shape: print(f"Removing key {k} from pretrained checkpoint") del checkpoint_model[k] # interpolate position embedding pos_embed_checkpoint = checkpoint_model['pos_embed'] embedding_size = pos_embed_checkpoint.shape[-1] num_patches = model.patch_embed.num_patches num_extra_tokens = model.pos_embed.shape[-2] - num_patches # height (== width) for the checkpoint position embedding orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5) # height (== width) for the new position embedding new_size = int(num_patches ** 0.5) # class_token and dist_token are kept unchanged extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens] # only the position tokens are interpolated pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:] pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2) pos_tokens = torch.nn.functional.interpolate( pos_tokens, size=(new_size, new_size), mode='bicubic', align_corners=False) pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2) new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1) checkpoint_model['pos_embed'] = new_pos_embed model.load_state_dict(checkpoint_model, strict=False) model.to(device) # flops, params = get_model_complexity_info(model, (3,args.input_size, args.input_size),as_strings=True,print_per_layer_stat=False) # print("flops: %s |params: %s" % (flops,params)) model_ema = None if args.model_ema: # Important to create EMA model after cuda(), DP wrapper, and AMP but before SyncBN and DDP wrapper model_ema = ModelEma( model, decay=args.model_ema_decay, device='cpu' if args.model_ema_force_cpu else '', resume='') model_without_ddp = model if args.distributed: model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu], find_unused_parameters=True) model_without_ddp = model.module n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) print('number of params:', n_parameters) linear_scaled_lr = args.lr * args.batch_size * utils.get_world_size() / 512.0 args.lr = linear_scaled_lr optimizer = create_optimizer(args, model_without_ddp) loss_scaler = NativeScaler() lr_scheduler, _ = create_scheduler(args, optimizer) criterion = LabelSmoothingCrossEntropy() if args.mixup > 0.: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif args.smoothing: criterion = LabelSmoothingCrossEntropy(smoothing=args.smoothing) else: criterion = torch.nn.CrossEntropyLoss() teacher_model = None # if args.distillation_type != 'none': # assert args.teacher_path, 'need to specify teacher-path when using distillation' # print(f"Creating teacher model: {args.teacher_model}") # teacher_model = create_model( # args.teacher_model, # pretrained=False, # num_classes=args.nb_classes, # global_pool='avg', # ) # teacher_model = RegNetY_200MF() # if args.teacher_path.startswith('https'): # checkpoint = torch.hub.load_state_dict_from_url( # args.teacher_path, map_location='cpu', check_hash=True) # else: # checkpoint = torch.load(args.teacher_path, map_location='cpu') # teacher_model.load_state_dict(checkpoint['model']) # teacher_model.to(device) # teacher_model.eval() # wrap the criterion in our custom DistillationLoss, which # just dispatches to the original criterion if args.distillation_type is 'none'
criterion = DistillationLoss(
4
2023-11-06 03:31:47+00:00
12k
zamaniamin/fastapi-shop
apps/accounts/tests/test_user.py
[ { "identifier": "FakeUser", "path": "apps/accounts/faker/data.py", "snippet": "class FakeUser(BaseFakeAccount):\n\n @classmethod\n def populate_members(cls):\n \"\"\"\n Create an admin and a user.\n \"\"\"\n\n # --- admin ---\n user, access_token = FakeAccount.ve...
from fastapi import status from fastapi.testclient import TestClient from apps.accounts.faker.data import FakeUser from apps.accounts.models import UserVerification from apps.accounts.services.authenticate import AccountService from apps.accounts.services.password import PasswordManager from apps.accounts.services.token import TokenService from apps.accounts.services.user import UserManager from apps.core.base_test_case import BaseTestCase from apps.main import app from config.database import DatabaseManager
8,397
assert expected_user['user_id'] == user.id assert expected_user['email'] == user.email assert expected_user['first_name'] == user.first_name assert expected_user['last_name'] == user.last_name assert expected_user['is_verified_email'] == user.is_verified_email self.assert_datetime_format(expected_user['date_joined']) self.assert_datetime_format(expected_user['updated_at']) self.assert_datetime_format(expected_user['last_login']) assert 'password' not in expected_user assert 'is_active' not in expected_user assert 'otp_key' not in expected_user def test_retrieve_me_protected(self): """ Test endpoint is protected. """ response = self.client.get(self.current_user_endpoint) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_retrieve_single_user(self): """ Test retrieve a single user by ID with admin role. only 'admin' can access to it. """ # --- create an admin with access-token --- admin, access_token = FakeUser.populate_admin() user, _ = FakeUser.populate_user() headers = { "Authorization": f"Bearer {access_token}" } # --- request to fetch user data from token --- response = self.client.get(f"{self.accounts_endpoint}{user.id}", headers=headers) assert response.status_code == status.HTTP_200_OK def test_retrieve_single_user_403(self): """ Test retrieve a single user by ID with user role. only 'admin' can access to it. """ # --- create user with access-token --- user_1, access_token = FakeUser.populate_user() user_2, _ = FakeUser.populate_user() headers = { "Authorization": f"Bearer {access_token}" } # --- request to fetch user data from token --- response = self.client.get(f"{self.accounts_endpoint}{user_2.id}", headers=headers) assert response.status_code == status.HTTP_403_FORBIDDEN # --------------------- # --- Test Payloads --- # --------------------- class TestUpdateUser(UserTestBase): def test_update_current_user(self): """ Test update the current user with "user" role. """ # --- create user --- user, access_token = FakeUser.populate_user() headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } payload = { 'first_name': FakeUser.fake.first_name(), 'last_name': FakeUser.fake.last_name() } # --- request --- response = self.client.put(self.current_user_endpoint, headers=headers, json=payload) assert response.status_code == status.HTTP_200_OK # --- expected --- expected_user = response.json().get('user') assert expected_user['first_name'] == payload['first_name'] assert expected_user['last_name'] == payload['last_name'] self.assert_datetime_format(expected_user['updated_at']) # TODO update current admin # --------------------- # --- Test Payloads --- # --------------------- class TestChanges(UserTestBase): def test_change_password(self): """ Test change password by current user. """ # --- create a user --- user, access_token = FakeUser.populate_user() header = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } # --- request --- payload = { 'current_password': FakeUser.password, 'password': FakeUser.password + "test", 'password_confirm': FakeUser.password + "test" } response = self.client.patch(self.change_password_endpoint, headers=header, json=payload) assert response.status_code == status.HTTP_200_OK # --- expected --- expected = response.json() assert expected['message'] == 'Your password has been changed.' # --- expected user data, ensure other info wasn't changed ---
class UserTestBase(BaseTestCase): current_user_endpoint = "/accounts/me/" change_password_endpoint = "/accounts/me/password/" change_email_endpoint = "/accounts/me/email/" verify_change_email_endpoint = "/accounts/me/email/verify/" accounts_endpoint = "/accounts/" @classmethod def setup_class(cls): cls.client = TestClient(app) DatabaseManager.create_test_database() @classmethod def teardown_class(cls): DatabaseManager.drop_all_tables() class TestRetrieveUser(UserTestBase): def test_successful_retrieve_me(self): """ Test retrieving a current user. """ # --- create user and generate token --- user, access_token = FakeUser.populate_user() headers = { "Authorization": f"Bearer {access_token}" } # --- request to fetch user data from token --- response = self.client.get(self.current_user_endpoint, headers=headers) assert response.status_code == status.HTTP_200_OK # --- expected user --- expected_user = response.json().get('user') assert expected_user['user_id'] == user.id assert expected_user['email'] == user.email assert expected_user['first_name'] == user.first_name assert expected_user['last_name'] == user.last_name assert expected_user['is_verified_email'] == user.is_verified_email self.assert_datetime_format(expected_user['date_joined']) self.assert_datetime_format(expected_user['updated_at']) self.assert_datetime_format(expected_user['last_login']) assert 'password' not in expected_user assert 'is_active' not in expected_user assert 'otp_key' not in expected_user def test_retrieve_me_protected(self): """ Test endpoint is protected. """ response = self.client.get(self.current_user_endpoint) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_retrieve_single_user(self): """ Test retrieve a single user by ID with admin role. only 'admin' can access to it. """ # --- create an admin with access-token --- admin, access_token = FakeUser.populate_admin() user, _ = FakeUser.populate_user() headers = { "Authorization": f"Bearer {access_token}" } # --- request to fetch user data from token --- response = self.client.get(f"{self.accounts_endpoint}{user.id}", headers=headers) assert response.status_code == status.HTTP_200_OK def test_retrieve_single_user_403(self): """ Test retrieve a single user by ID with user role. only 'admin' can access to it. """ # --- create user with access-token --- user_1, access_token = FakeUser.populate_user() user_2, _ = FakeUser.populate_user() headers = { "Authorization": f"Bearer {access_token}" } # --- request to fetch user data from token --- response = self.client.get(f"{self.accounts_endpoint}{user_2.id}", headers=headers) assert response.status_code == status.HTTP_403_FORBIDDEN # --------------------- # --- Test Payloads --- # --------------------- class TestUpdateUser(UserTestBase): def test_update_current_user(self): """ Test update the current user with "user" role. """ # --- create user --- user, access_token = FakeUser.populate_user() headers = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } payload = { 'first_name': FakeUser.fake.first_name(), 'last_name': FakeUser.fake.last_name() } # --- request --- response = self.client.put(self.current_user_endpoint, headers=headers, json=payload) assert response.status_code == status.HTTP_200_OK # --- expected --- expected_user = response.json().get('user') assert expected_user['first_name'] == payload['first_name'] assert expected_user['last_name'] == payload['last_name'] self.assert_datetime_format(expected_user['updated_at']) # TODO update current admin # --------------------- # --- Test Payloads --- # --------------------- class TestChanges(UserTestBase): def test_change_password(self): """ Test change password by current user. """ # --- create a user --- user, access_token = FakeUser.populate_user() header = { "Authorization": f"Bearer {access_token}", "Content-Type": "application/json" } # --- request --- payload = { 'current_password': FakeUser.password, 'password': FakeUser.password + "test", 'password_confirm': FakeUser.password + "test" } response = self.client.patch(self.change_password_endpoint, headers=header, json=payload) assert response.status_code == status.HTTP_200_OK # --- expected --- expected = response.json() assert expected['message'] == 'Your password has been changed.' # --- expected user data, ensure other info wasn't changed ---
expected_user = UserManager.get_user(user.id)
5
2023-11-06 04:46:03+00:00
12k
lukas-clarke/eight_sleep
custom_components/eight_sleep/pyEight/eight.py
[ { "identifier": "NotAuthenticatedError", "path": "custom_components/eight_sleep/pyEight/exceptions.py", "snippet": "class NotAuthenticatedError(BaseEightSleepError):\n \"\"\"Exception for eight sleep authentication errors..\"\"\"" }, { "identifier": "RequestError", "path": "custom_compone...
import asyncio import atexit import logging import time import httpx from datetime import datetime from typing import Any from aiohttp.client import ClientError, ClientSession, ClientTimeout from .constants import * from .exceptions import NotAuthenticatedError, RequestError from .user import EightUser from .structs import Token
8,450
""" from __future__ import annotations _LOGGER = logging.getLogger(__name__) CLIENT_TIMEOUT = ClientTimeout(total=DEFAULT_TIMEOUT) class EightSleep: """Eight sleep API object.""" def __init__( self, email: str, password: str, timezone: str, client_id: str = None, client_secret: str = None, client_session: ClientSession | None = None, check_auth: bool = False, ) -> None: """Initialize eight sleep class.""" self._email = email self._password = password # If client_id isn't set, use the default value if not client_id: client_id = "0894c7f33bb94800a03f1f4df13a4f38" self._client_id = client_id # client_secret isn't required for current Eight Sleep API auth # but can't be empty value, so setting random string if not set if not client_secret: client_secret = "ASDF" self._client_secret = client_secret self.timezone = timezone self.users: dict[str, EightUser] = {} self._user_id: str | None = None self._token: str | None = None self._token_expiration: datetime | None = None self._device_ids: list[str] = [] self._is_pod: bool = False # Setup 10 element list self._device_json_list: list[dict] = [] self._api_session = client_session self._internal_session: bool = False if check_auth: self._get_auth() # Stop on exit atexit.register(self.at_exit) def at_exit(self) -> None: """Run at exit.""" try: loop = asyncio.get_running_loop() asyncio.run_coroutine_threadsafe(self.stop(), loop).result() except RuntimeError: asyncio.run(self.stop()) @property def token(self) -> str | None: """Return session token.""" return self._token @property def user_id(self) -> str | None: """Return user ID of the logged in user.""" return self._user_id @property def device_id(self) -> str | None: """Return devices id.""" return self._device_ids[0] @property def device_data(self) -> dict: """Return current raw device_data json.""" return self._device_json_list[0] @property def device_data_history(self) -> list[dict]: """Return full raw device_data json list.""" return self._device_json_list @property def is_pod(self) -> bool: """Return if device is a POD.""" return self._is_pod async def _get_auth(self) -> Token: data = { "client_id": self._client_id, "client_secret": self._client_secret, "grant_type": "password", "username": self._email, "password": self._password, } async with httpx.AsyncClient() as client: response = await client.post( AUTH_URL, headers=DEFAULT_AUTH_HEADERS, json=data, timeout=DEFAULT_TIMEOUT, ) if response.status_code == 200: access_token_str = response.json()["access_token"] expiration_seconds_int = ( float(response.json()["expires_in"]) + time.time() ) main_id = response.json()["userId"] return Token(access_token_str, expiration_seconds_int, main_id) else:
""" pyeight.eight ~~~~~~~~~~~~~~~~~~~~ Provides api for Eight Sleep Copyright (c) 2022-2023 <https://github.com/lukas-clarke/pyEight> Licensed under the MIT license. """ from __future__ import annotations _LOGGER = logging.getLogger(__name__) CLIENT_TIMEOUT = ClientTimeout(total=DEFAULT_TIMEOUT) class EightSleep: """Eight sleep API object.""" def __init__( self, email: str, password: str, timezone: str, client_id: str = None, client_secret: str = None, client_session: ClientSession | None = None, check_auth: bool = False, ) -> None: """Initialize eight sleep class.""" self._email = email self._password = password # If client_id isn't set, use the default value if not client_id: client_id = "0894c7f33bb94800a03f1f4df13a4f38" self._client_id = client_id # client_secret isn't required for current Eight Sleep API auth # but can't be empty value, so setting random string if not set if not client_secret: client_secret = "ASDF" self._client_secret = client_secret self.timezone = timezone self.users: dict[str, EightUser] = {} self._user_id: str | None = None self._token: str | None = None self._token_expiration: datetime | None = None self._device_ids: list[str] = [] self._is_pod: bool = False # Setup 10 element list self._device_json_list: list[dict] = [] self._api_session = client_session self._internal_session: bool = False if check_auth: self._get_auth() # Stop on exit atexit.register(self.at_exit) def at_exit(self) -> None: """Run at exit.""" try: loop = asyncio.get_running_loop() asyncio.run_coroutine_threadsafe(self.stop(), loop).result() except RuntimeError: asyncio.run(self.stop()) @property def token(self) -> str | None: """Return session token.""" return self._token @property def user_id(self) -> str | None: """Return user ID of the logged in user.""" return self._user_id @property def device_id(self) -> str | None: """Return devices id.""" return self._device_ids[0] @property def device_data(self) -> dict: """Return current raw device_data json.""" return self._device_json_list[0] @property def device_data_history(self) -> list[dict]: """Return full raw device_data json list.""" return self._device_json_list @property def is_pod(self) -> bool: """Return if device is a POD.""" return self._is_pod async def _get_auth(self) -> Token: data = { "client_id": self._client_id, "client_secret": self._client_secret, "grant_type": "password", "username": self._email, "password": self._password, } async with httpx.AsyncClient() as client: response = await client.post( AUTH_URL, headers=DEFAULT_AUTH_HEADERS, json=data, timeout=DEFAULT_TIMEOUT, ) if response.status_code == 200: access_token_str = response.json()["access_token"] expiration_seconds_int = ( float(response.json()["expires_in"]) + time.time() ) main_id = response.json()["userId"] return Token(access_token_str, expiration_seconds_int, main_id) else:
raise RequestError(
1
2023-11-01 16:15:52+00:00
12k
gickowtf/pixoo-homeassistant
custom_components/divoom_pixoo/pixoo64/_pixoo.py
[ { "identifier": "Palette", "path": "custom_components/divoom_pixoo/pixoo64/_colors.py", "snippet": "class Palette:\n BLACK = COLOR_BLACK\n WHITE = COLOR_WHITE" }, { "identifier": "retrieve_glyph", "path": "custom_components/divoom_pixoo/pixoo64/_font.py", "snippet": "def retrieve_g...
import base64 import json import requests from enum import IntEnum from PIL import Image, ImageOps from ._colors import Palette from ._font import retrieve_glyph, FONT_GICKO, FONT_PICO_8
10,780
def draw_filled_rectangle_from_top_left_to_bottom_right_rgb(self, top_left_x=0, top_left_y=0, bottom_right_x=1, bottom_right_y=1, r=0, g=0, b=0): self.draw_filled_rectangle((top_left_x, top_left_y), (bottom_right_x, bottom_right_y), (r, g, b)) def draw_image(self, image_path_or_object, xy=(0, 0), image_resample_mode=ImageResampleMode.PIXEL_ART, pad_resample=False): image = image_path_or_object if isinstance(image_path_or_object, Image.Image) else Image.open( image_path_or_object) size = image.size width = size[0] height = size[1] # See if it needs to be scaled/resized to fit the display if width > self.size or height > self.size: if pad_resample: image = ImageOps.pad(image, (self.size, self.size), image_resample_mode) else: image.thumbnail((self.size, self.size), image_resample_mode) if self.debug: print( f'[.] Resized image to fit on screen (saving aspect ratio): "{image_path_or_object}" ({width}, {height}) ' f'-> ({image.size[0]}, {image.size[1]})') # Convert the loaded image to RGB rgb_image = image.convert('RGB') # Iterate over all pixels in the image that are left and buffer them for y in range(image.size[1]): for x in range(image.size[0]): location = (x, y) placed_x = x + xy[0] if self.size - 1 < placed_x or placed_x < 0: continue placed_y = y + xy[1] if self.size - 1 < placed_y or placed_y < 0: continue self.draw_pixel((placed_x, placed_y), rgb_image.getpixel(location)) def draw_image_at_location(self, image_path_or_object, x, y, image_resample_mode=ImageResampleMode.PIXEL_ART): self.draw_image(image_path_or_object, (x, y), image_resample_mode) def draw_line(self, start_xy, stop_xy, rgb=Palette.WHITE): line = set() # Calculate the amount of steps needed between the points to draw a nice line amount_of_steps = minimum_amount_of_steps(start_xy, stop_xy) # Iterate over them and create a nice set of pixels for step in range(amount_of_steps): if amount_of_steps == 0: interpolant = 0 else: interpolant = step / amount_of_steps # Add a pixel as a rounded location line.add( round_location(lerp_location(start_xy, stop_xy, interpolant))) # Draw the actual pixel line for pixel in line: self.draw_pixel(pixel, rgb) def draw_line_from_start_to_stop_rgb(self, start_x, start_y, stop_x, stop_y, r=255, g=255, b=255): self.draw_line((start_x, start_y), (stop_x, stop_y), (r, g, b)) def draw_pixel(self, xy, rgb): # If it's not on the screen, we're not going to bother if xy[0] < 0 or xy[0] >= self.size or xy[1] < 0 or xy[1] >= self.size: if self.debug: limit = self.size - 1 print( f'[!] Invalid coordinates given: ({xy[0]}, {xy[1]}) (maximum coordinates are ({limit}, {limit})') return # Calculate the index index = xy[0] + (xy[1] * self.size) # Color it self.draw_pixel_at_index(index, rgb) def draw_pixel_at_index(self, index, rgb): # Validate the index if index < 0 or index >= self.pixel_count: if self.debug: print(f'[!] Invalid index given: {index} (maximum index is {self.pixel_count - 1})') return # Clamp the color, just to be safe rgb = clamp_color(rgb) # Move to place in array index = index * 3 self.__buffer[index] = rgb[0] self.__buffer[index + 1] = rgb[1] self.__buffer[index + 2] = rgb[2] def draw_pixel_at_index_rgb(self, index, r, g, b): self.draw_pixel_at_index(index, (r, g, b)) def draw_pixel_at_location_rgb(self, x, y, r, g, b): self.draw_pixel((x, y), (r, g, b)) def draw_character(self, character, xy=(0, 0), rgb=Palette.WHITE, font=None): if font is None:
def clamp(value, minimum=0, maximum=255): if value > maximum: return maximum if value < minimum: return minimum return value def clamp_color(rgb): return clamp(rgb[0]), clamp(rgb[1]), clamp(rgb[2]) def lerp(start, end, interpolant): return start + interpolant * (end - start) def lerp_location(xy1, xy2, interpolant): return lerp(xy1[0], xy2[0], interpolant), lerp(xy1[1], xy2[1], interpolant) def minimum_amount_of_steps(xy1, xy2): return max(abs(xy1[0] - xy2[0]), abs(xy1[1] - xy2[1])) def rgb_to_hex_color(rgb): return f'#{rgb[0]:0>2X}{rgb[1]:0>2X}{rgb[2]:0>2X}' def round_location(xy): return round(xy[0]), round(xy[1]) class Channel(IntEnum): FACES = 0 CLOUD = 1 VISUALIZER = 2 CUSTOM = 3 class ImageResampleMode(IntEnum): PIXEL_ART = Image.NEAREST class TextScrollDirection(IntEnum): LEFT = 0 RIGHT = 1 class Pixoo: __buffer = [] __buffers_send = 0 __counter = 0 __refresh_counter_limit = 32 def __init__(self, address, size=64, debug=False, refresh_connection_automatically=True): assert size in [16, 32, 64], \ 'Invalid screen size in pixels given. ' \ 'Valid options are 16, 32, and 64' self.refresh_connection_automatically = refresh_connection_automatically self.address = address self.debug = debug self.size = size # Total number of pixels self.pixel_count = self.size * self.size # Generate URL self.__url = 'http://{0}/post'.format(address) # Prefill the buffer self.fill() # Retrieve the counter self.__load_counter() # Resetting if needed if self.refresh_connection_automatically and self.__counter > self.__refresh_counter_limit: self.__reset_counter() def clear(self, rgb: object = Palette.BLACK) -> object: self.fill(rgb) def clear_rgb(self, r, g, b): self.fill_rgb(r, g, b) def draw_character_at_location_rgb(self, character, x=0, y=0, r=255, g=255, b=255): self.draw_character(character, (x, y), (r, g, b)) def draw_filled_rectangle(self, top_left_xy=(0, 0), bottom_right_xy=(1, 1), rgb=Palette.BLACK): for y in range(top_left_xy[1], bottom_right_xy[1] + 1): for x in range(top_left_xy[0], bottom_right_xy[0] + 1): self.draw_pixel((x, y), rgb) def draw_filled_rectangle_from_top_left_to_bottom_right_rgb(self, top_left_x=0, top_left_y=0, bottom_right_x=1, bottom_right_y=1, r=0, g=0, b=0): self.draw_filled_rectangle((top_left_x, top_left_y), (bottom_right_x, bottom_right_y), (r, g, b)) def draw_image(self, image_path_or_object, xy=(0, 0), image_resample_mode=ImageResampleMode.PIXEL_ART, pad_resample=False): image = image_path_or_object if isinstance(image_path_or_object, Image.Image) else Image.open( image_path_or_object) size = image.size width = size[0] height = size[1] # See if it needs to be scaled/resized to fit the display if width > self.size or height > self.size: if pad_resample: image = ImageOps.pad(image, (self.size, self.size), image_resample_mode) else: image.thumbnail((self.size, self.size), image_resample_mode) if self.debug: print( f'[.] Resized image to fit on screen (saving aspect ratio): "{image_path_or_object}" ({width}, {height}) ' f'-> ({image.size[0]}, {image.size[1]})') # Convert the loaded image to RGB rgb_image = image.convert('RGB') # Iterate over all pixels in the image that are left and buffer them for y in range(image.size[1]): for x in range(image.size[0]): location = (x, y) placed_x = x + xy[0] if self.size - 1 < placed_x or placed_x < 0: continue placed_y = y + xy[1] if self.size - 1 < placed_y or placed_y < 0: continue self.draw_pixel((placed_x, placed_y), rgb_image.getpixel(location)) def draw_image_at_location(self, image_path_or_object, x, y, image_resample_mode=ImageResampleMode.PIXEL_ART): self.draw_image(image_path_or_object, (x, y), image_resample_mode) def draw_line(self, start_xy, stop_xy, rgb=Palette.WHITE): line = set() # Calculate the amount of steps needed between the points to draw a nice line amount_of_steps = minimum_amount_of_steps(start_xy, stop_xy) # Iterate over them and create a nice set of pixels for step in range(amount_of_steps): if amount_of_steps == 0: interpolant = 0 else: interpolant = step / amount_of_steps # Add a pixel as a rounded location line.add( round_location(lerp_location(start_xy, stop_xy, interpolant))) # Draw the actual pixel line for pixel in line: self.draw_pixel(pixel, rgb) def draw_line_from_start_to_stop_rgb(self, start_x, start_y, stop_x, stop_y, r=255, g=255, b=255): self.draw_line((start_x, start_y), (stop_x, stop_y), (r, g, b)) def draw_pixel(self, xy, rgb): # If it's not on the screen, we're not going to bother if xy[0] < 0 or xy[0] >= self.size or xy[1] < 0 or xy[1] >= self.size: if self.debug: limit = self.size - 1 print( f'[!] Invalid coordinates given: ({xy[0]}, {xy[1]}) (maximum coordinates are ({limit}, {limit})') return # Calculate the index index = xy[0] + (xy[1] * self.size) # Color it self.draw_pixel_at_index(index, rgb) def draw_pixel_at_index(self, index, rgb): # Validate the index if index < 0 or index >= self.pixel_count: if self.debug: print(f'[!] Invalid index given: {index} (maximum index is {self.pixel_count - 1})') return # Clamp the color, just to be safe rgb = clamp_color(rgb) # Move to place in array index = index * 3 self.__buffer[index] = rgb[0] self.__buffer[index + 1] = rgb[1] self.__buffer[index + 2] = rgb[2] def draw_pixel_at_index_rgb(self, index, r, g, b): self.draw_pixel_at_index(index, (r, g, b)) def draw_pixel_at_location_rgb(self, x, y, r, g, b): self.draw_pixel((x, y), (r, g, b)) def draw_character(self, character, xy=(0, 0), rgb=Palette.WHITE, font=None): if font is None:
font = FONT_PICO_8
3
2023-11-05 19:16:34+00:00
12k
jkulhanek/nerfbaselines
nerfbaselines/datasets/colmap.py
[ { "identifier": "Dataset", "path": "nerfbaselines/types.py", "snippet": "NB_PREFIX = os.path.expanduser(os.environ.get(\"NB_PREFIX\", \"~/.cache/nerfbaselines\"))\nclass Dataset:\nclass CurrentProgress:\n class RenderOutput(TypedDict):\nclass MethodInfo:\nclass Method(Protocol):\nclass RayMethod(Meth...
import typing import logging import numpy as np from collections import OrderedDict from pathlib import Path from typing import Tuple, Optional, Dict from ..types import Dataset, DatasetFeature, FrozenSet from ..utils import Indices from ..cameras import CameraModel, Cameras from ._colmap_utils import read_cameras_binary, read_images_binary, read_points3D_binary, qvec2rotmat from ._colmap_utils import read_cameras_text, read_images_text, read_points3D_text, Image, Camera, Point3D from ._common import DatasetNotFoundError, padded_stack
7,486
elif camera.model == "FULL_OPENCV": # fx, fy, cx, cy, k1, k2, p1, p2, k3, k4, k5, k6 # u2 = u ** 2 # uv = u * v # v2 = v ** 2 # r2 = u2 + v2 # r4 = r2 * r2 # r6 = r4 * r2 # radial = (1 + k1 * r2 + k2 * r4 + k3 * r6) / # (1 + k4 * r2 + k5 * r4 + k6 * r6) # du = u * radial + 2 * p1 * uv + p2 * (r2 + 2 * u2) - u # dv = v * radial + 2 * p2 * uv + p1 * (r2 + 2 * v2) - v fl_x = float(camera_params[0]) fl_y = float(camera_params[1]) cx = float(camera_params[2]) cy = float(camera_params[3]) out["k1"] = float(camera_params[4]) out["k2"] = float(camera_params[5]) out["p1"] = float(camera_params[6]) out["p2"] = float(camera_params[7]) out["k3"] = float(camera_params[8]) out["k4"] = float(camera_params[9]) out["k5"] = float(camera_params[10]) out["k6"] = float(camera_params[11]) raise NotImplementedError(f"{camera.model} camera model is not supported yet!") elif camera.model == "FOV": # fx, fy, cx, cy, omega fl_x = float(camera_params[0]) fl_y = float(camera_params[1]) cx = float(camera_params[2]) cy = float(camera_params[3]) out["omega"] = float(camera_params[4]) raise NotImplementedError(f"{camera.model} camera model is not supported yet!") elif camera.model == "SIMPLE_RADIAL_FISHEYE": # f, cx, cy, k # r = sqrt(u ** 2 + v ** 2) # if r > eps: # theta = atan(r) # theta2 = theta ** 2 # thetad = theta * (1 + k * theta2) # du = u * thetad / r - u; # dv = v * thetad / r - v; # else: # du = dv = 0 fl_x = float(camera_params[0]) fl_y = float(camera_params[0]) cx = float(camera_params[1]) cy = float(camera_params[2]) out["k1"] = float(camera_params[3]) camera_model = CameraModel.OPENCV_FISHEYE elif camera.model == "RADIAL_FISHEYE": # f, cx, cy, k1, k2 # r = sqrt(u ** 2 + v ** 2) # if r > eps: # theta = atan(r) # theta2 = theta ** 2 # theta4 = theta2 ** 2 # thetad = theta * (1 + k * theta2) # thetad = theta * (1 + k1 * theta2 + k2 * theta4) # du = u * thetad / r - u; # dv = v * thetad / r - v; # else: # du = dv = 0 fl_x = float(camera_params[0]) fl_y = float(camera_params[0]) cx = float(camera_params[1]) cy = float(camera_params[2]) out["k1"] = float(camera_params[3]) out["k2"] = float(camera_params[4]) out["k3"] = 0.0 out["k4"] = 0.0 camera_model = CameraModel.OPENCV_FISHEYE else: # THIN_PRISM_FISHEYE not supported! raise NotImplementedError(f"{camera.model} camera model is not supported yet!") image_width: int = camera.width image_height: int = camera.height intrinsics = np.array([fl_x, fl_y, cx, cy], dtype=np.float32) / float(image_width) distortion_params = np.array([out.get(k, 0.0) for k in ("k1", "k2", "p1", "p2", "k3", "k4")], dtype=np.float32) return intrinsics, camera_model.value, distortion_params, (image_width, image_height) def load_colmap_dataset(path: Path, images_path: Optional[Path] = None, split: Optional[str] = None, test_indices: Optional[Indices] = None, features: Optional[FrozenSet[DatasetFeature]] = None): if features is None: features = typing.cast(FrozenSet[DatasetFeature], {}) load_points = "points3D_xyz" in features or "points3D_rgb" in features if split: assert split in {"train", "test"} # Load COLMAP dataset colmap_path = path / "sparse" / "0" if images_path is None: images_path = Path("images") images_path = path / images_path if not colmap_path.exists(): raise DatasetNotFoundError("Missing 'sparse/0' folder in COLMAP dataset") if not (colmap_path / "cameras.bin").exists() and not (colmap_path / "cameras.txt").exists(): raise DatasetNotFoundError("Missing 'sparse/0/cameras.{bin,txt}' file in COLMAP dataset") if not images_path.exists(): raise DatasetNotFoundError("Missing 'images' folder in COLMAP dataset") if (colmap_path / "cameras.bin").exists(): cameras = read_cameras_binary(colmap_path / "cameras.bin") elif (colmap_path / "cameras.txt").exists(): cameras = read_cameras_text(colmap_path / "cameras.txt") else: raise DatasetNotFoundError("Missing 'sparse/0/cameras.{bin,txt}' file in COLMAP dataset") if not (colmap_path / "images.bin").exists() and not (colmap_path / "images.txt").exists(): raise DatasetNotFoundError("Missing 'sparse/0/images.{bin,txt}' file in COLMAP dataset") if (colmap_path / "images.bin").exists(): images = read_images_binary(colmap_path / "images.bin") elif (colmap_path / "images.txt").exists(): images = read_images_text(colmap_path / "images.txt") else: raise DatasetNotFoundError("Missing 'sparse/0/images.{bin,txt}' file in COLMAP dataset")
def _parse_colmap_camera_params(camera: Camera) -> Tuple[np.ndarray, int, np.ndarray, Tuple[int, int]]: """ Parses all currently supported COLMAP cameras into the transforms.json metadata Args: camera: COLMAP camera Returns: transforms.json metadata containing camera's intrinsics and distortion parameters """ # Parameters match https://github.com/colmap/colmap/blob/dev/src/base/camera_models.h out = OrderedDict() # Default in Python 3.7+ camera_params = camera.params camera_model: CameraModel if camera.model == "SIMPLE_PINHOLE": # du = 0 # dv = 0 fl_x = float(camera_params[0]) fl_y = float(camera_params[0]) cx = float(camera_params[1]) cy = float(camera_params[2]) camera_model = CameraModel.PINHOLE elif camera.model == "PINHOLE": # f, cx, cy, k # du = 0 # dv = 0 fl_x = float(camera_params[0]) fl_y = float(camera_params[1]) cx = float(camera_params[2]) cy = float(camera_params[3]) camera_model = CameraModel.PINHOLE elif camera.model == "SIMPLE_RADIAL": # f, cx, cy, k # r2 = u**2 + v**2; # radial = k * r2 # du = u * radial # dv = u * radial fl_x = float(camera_params[0]) fl_y = float(camera_params[0]) cx = float(camera_params[1]) cy = float(camera_params[2]) out["k1"] = float(camera_params[3]) camera_model = CameraModel.OPENCV elif camera.model == "RADIAL": # f, cx, cy, k1, k2 # r2 = u**2 + v**2; # radial = k1 * r2 + k2 * r2 ** 2 # du = u * radial # dv = v * radial fl_x = float(camera_params[0]) fl_y = float(camera_params[0]) cx = float(camera_params[1]) cy = float(camera_params[2]) out["k1"] = float(camera_params[3]) out["k2"] = float(camera_params[4]) camera_model = CameraModel.OPENCV elif camera.model == "OPENCV": # fx, fy, cx, cy, k1, k2, p1, p2 # uv = u * v; # r2 = u**2 + v**2 # radial = k1 * r2 + k2 * r2 ** 2 # du = u * radial + 2 * p1 * u*v + p2 * (r2 + 2 * u**2) # dv = v * radial + 2 * p2 * u*v + p1 * (r2 + 2 * v**2) fl_x = float(camera_params[0]) fl_y = float(camera_params[1]) cx = float(camera_params[2]) cy = float(camera_params[3]) out["k1"] = float(camera_params[4]) out["k2"] = float(camera_params[5]) out["p1"] = float(camera_params[6]) out["p2"] = float(camera_params[7]) camera_model = CameraModel.OPENCV elif camera.model == "OPENCV_FISHEYE": # fx, fy, cx, cy, k1, k2, k3, k4 # r = sqrt(u**2 + v**2) # if r > eps: # theta = atan(r) # theta2 = theta ** 2 # theta4 = theta2 ** 2 # theta6 = theta4 * theta2 # theta8 = theta4 ** 2 # thetad = theta * (1 + k1 * theta2 + k2 * theta4 + k3 * theta6 + k4 * theta8) # du = u * thetad / r - u; # dv = v * thetad / r - v; # else: # du = dv = 0 fl_x = float(camera_params[0]) fl_y = float(camera_params[1]) cx = float(camera_params[2]) cy = float(camera_params[3]) out["k1"] = float(camera_params[4]) out["k2"] = float(camera_params[5]) out["k3"] = float(camera_params[6]) out["k4"] = float(camera_params[7]) camera_model = CameraModel.OPENCV_FISHEYE elif camera.model == "FULL_OPENCV": # fx, fy, cx, cy, k1, k2, p1, p2, k3, k4, k5, k6 # u2 = u ** 2 # uv = u * v # v2 = v ** 2 # r2 = u2 + v2 # r4 = r2 * r2 # r6 = r4 * r2 # radial = (1 + k1 * r2 + k2 * r4 + k3 * r6) / # (1 + k4 * r2 + k5 * r4 + k6 * r6) # du = u * radial + 2 * p1 * uv + p2 * (r2 + 2 * u2) - u # dv = v * radial + 2 * p2 * uv + p1 * (r2 + 2 * v2) - v fl_x = float(camera_params[0]) fl_y = float(camera_params[1]) cx = float(camera_params[2]) cy = float(camera_params[3]) out["k1"] = float(camera_params[4]) out["k2"] = float(camera_params[5]) out["p1"] = float(camera_params[6]) out["p2"] = float(camera_params[7]) out["k3"] = float(camera_params[8]) out["k4"] = float(camera_params[9]) out["k5"] = float(camera_params[10]) out["k6"] = float(camera_params[11]) raise NotImplementedError(f"{camera.model} camera model is not supported yet!") elif camera.model == "FOV": # fx, fy, cx, cy, omega fl_x = float(camera_params[0]) fl_y = float(camera_params[1]) cx = float(camera_params[2]) cy = float(camera_params[3]) out["omega"] = float(camera_params[4]) raise NotImplementedError(f"{camera.model} camera model is not supported yet!") elif camera.model == "SIMPLE_RADIAL_FISHEYE": # f, cx, cy, k # r = sqrt(u ** 2 + v ** 2) # if r > eps: # theta = atan(r) # theta2 = theta ** 2 # thetad = theta * (1 + k * theta2) # du = u * thetad / r - u; # dv = v * thetad / r - v; # else: # du = dv = 0 fl_x = float(camera_params[0]) fl_y = float(camera_params[0]) cx = float(camera_params[1]) cy = float(camera_params[2]) out["k1"] = float(camera_params[3]) camera_model = CameraModel.OPENCV_FISHEYE elif camera.model == "RADIAL_FISHEYE": # f, cx, cy, k1, k2 # r = sqrt(u ** 2 + v ** 2) # if r > eps: # theta = atan(r) # theta2 = theta ** 2 # theta4 = theta2 ** 2 # thetad = theta * (1 + k * theta2) # thetad = theta * (1 + k1 * theta2 + k2 * theta4) # du = u * thetad / r - u; # dv = v * thetad / r - v; # else: # du = dv = 0 fl_x = float(camera_params[0]) fl_y = float(camera_params[0]) cx = float(camera_params[1]) cy = float(camera_params[2]) out["k1"] = float(camera_params[3]) out["k2"] = float(camera_params[4]) out["k3"] = 0.0 out["k4"] = 0.0 camera_model = CameraModel.OPENCV_FISHEYE else: # THIN_PRISM_FISHEYE not supported! raise NotImplementedError(f"{camera.model} camera model is not supported yet!") image_width: int = camera.width image_height: int = camera.height intrinsics = np.array([fl_x, fl_y, cx, cy], dtype=np.float32) / float(image_width) distortion_params = np.array([out.get(k, 0.0) for k in ("k1", "k2", "p1", "p2", "k3", "k4")], dtype=np.float32) return intrinsics, camera_model.value, distortion_params, (image_width, image_height) def load_colmap_dataset(path: Path, images_path: Optional[Path] = None, split: Optional[str] = None, test_indices: Optional[Indices] = None, features: Optional[FrozenSet[DatasetFeature]] = None): if features is None: features = typing.cast(FrozenSet[DatasetFeature], {}) load_points = "points3D_xyz" in features or "points3D_rgb" in features if split: assert split in {"train", "test"} # Load COLMAP dataset colmap_path = path / "sparse" / "0" if images_path is None: images_path = Path("images") images_path = path / images_path if not colmap_path.exists(): raise DatasetNotFoundError("Missing 'sparse/0' folder in COLMAP dataset") if not (colmap_path / "cameras.bin").exists() and not (colmap_path / "cameras.txt").exists(): raise DatasetNotFoundError("Missing 'sparse/0/cameras.{bin,txt}' file in COLMAP dataset") if not images_path.exists(): raise DatasetNotFoundError("Missing 'images' folder in COLMAP dataset") if (colmap_path / "cameras.bin").exists(): cameras = read_cameras_binary(colmap_path / "cameras.bin") elif (colmap_path / "cameras.txt").exists(): cameras = read_cameras_text(colmap_path / "cameras.txt") else: raise DatasetNotFoundError("Missing 'sparse/0/cameras.{bin,txt}' file in COLMAP dataset") if not (colmap_path / "images.bin").exists() and not (colmap_path / "images.txt").exists(): raise DatasetNotFoundError("Missing 'sparse/0/images.{bin,txt}' file in COLMAP dataset") if (colmap_path / "images.bin").exists(): images = read_images_binary(colmap_path / "images.bin") elif (colmap_path / "images.txt").exists(): images = read_images_text(colmap_path / "images.txt") else: raise DatasetNotFoundError("Missing 'sparse/0/images.{bin,txt}' file in COLMAP dataset")
points3D: Optional[Dict[str, Point3D]] = None
8
2023-11-07 20:22:35+00:00
12k
microsoft/Everything-of-Thoughts-XoT
xot_all_in_one/xot/controller/controller.py
[ { "identifier": "IO_Solver", "path": "xot_all_in_one/xot/controller/solver/io_solver.py", "snippet": "class IO_Solver:\n def __init__(self, args, gpt, game, prompter, parser, to_print=False):\n self.args = args\n self.gpt = gpt\n self.game = game\n self.prompter = prompter...
import os import json import itertools import random import ast import re import numpy as np import pandas as pd from collections import Counter from .utils import * from .solver.io_solver import IO_Solver from .solver.cot_solver import CoT_Solver from .solver.tot_solver import ToT_Solver from .solver.got_solver import GoT_Solver from .solver.xot_solver import XoT_Solver
9,463
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. class Controller: """ Controller class to manage the execution flow This involves language models, operations, prompting, and parsing. """ def __init__(self, config, gpt, game, prompter, parser): self.config = config self.gpt = gpt self.game = game self.prompter = prompter self.parser = parser def initial_logs(self, config): if config.method == 'io' or config.method == 'cot': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_sample{config.param.n_generate_sample}_multi{config.multi_solution}_start{config.task.task_start_index}_end{config.task.task_end_index}.json' elif config.method == 'tot': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_propose{config.param.n_generate_sample}_value{config.param.n_evaluate_sample}_greedy{config.param.n_select_sample}_start{config.task.task_start_index}_end{config.task.task_end_index}_laststep{config.param.last_step}.json' elif config.method == 'got': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_multi{config.multi_solution}_propose{config.param.n_generate_sample}_value{config.param.n_evaluate_sample}_greedy{config.param.n_select_sample}_start{config.task.task_start_index}_end{config.task.task_end_index}_laststep{config.param.last_step}.json' elif config.method == 'xot': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_multi{config.multi_solution}_revised{config.xot.revised}_reviseTimes{config.xot.revise_times}_start{config.task.task_start_index}_end{config.task.task_end_index}_laststep{config.param.last_step}.json' else: raise ValueError("invalid method") os.makedirs(os.path.dirname(file), exist_ok=True) return file def initial_solver(self, config): if config.method == 'io': return IO_Solver(config, self.gpt, self.game, self.prompter, self.parser) elif config.method == 'cot':
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. class Controller: """ Controller class to manage the execution flow This involves language models, operations, prompting, and parsing. """ def __init__(self, config, gpt, game, prompter, parser): self.config = config self.gpt = gpt self.game = game self.prompter = prompter self.parser = parser def initial_logs(self, config): if config.method == 'io' or config.method == 'cot': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_sample{config.param.n_generate_sample}_multi{config.multi_solution}_start{config.task.task_start_index}_end{config.task.task_end_index}.json' elif config.method == 'tot': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_propose{config.param.n_generate_sample}_value{config.param.n_evaluate_sample}_greedy{config.param.n_select_sample}_start{config.task.task_start_index}_end{config.task.task_end_index}_laststep{config.param.last_step}.json' elif config.method == 'got': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_multi{config.multi_solution}_propose{config.param.n_generate_sample}_value{config.param.n_evaluate_sample}_greedy{config.param.n_select_sample}_start{config.task.task_start_index}_end{config.task.task_end_index}_laststep{config.param.last_step}.json' elif config.method == 'xot': file = f'logs/{config.env}/{config.gpt.backend}_{config.gpt.temperature}_{config.method}_multi{config.multi_solution}_revised{config.xot.revised}_reviseTimes{config.xot.revise_times}_start{config.task.task_start_index}_end{config.task.task_end_index}_laststep{config.param.last_step}.json' else: raise ValueError("invalid method") os.makedirs(os.path.dirname(file), exist_ok=True) return file def initial_solver(self, config): if config.method == 'io': return IO_Solver(config, self.gpt, self.game, self.prompter, self.parser) elif config.method == 'cot':
return CoT_Solver(config, self.gpt, self.game, self.prompter, self.parser)
1
2023-11-08 09:48:34+00:00
12k
UMass-Foundation-Model/CoVLM
open_flamingo/eval/evaluate_llava.py
[ { "identifier": "create_model_and_transforms", "path": "open_flamingo/src/factory.py", "snippet": "def create_model_and_transforms(\n clip_vision_encoder_path: str,\n clip_vision_encoder_pretrained: str,\n lang_encoder_path: str,\n tokenizer_path: str,\n use_local_files: bool = False,\n ...
import argparse import json import os import random import uuid import time import cv2 import webdataset as wds import transformers import more_itertools import numpy as np import torch import base64 import string import spacy import hashlib import pdb; pdb.set_trace() from math import ceil from collections import defaultdict from typing import Callable from accelerate import init_empty_weights, load_checkpoint_and_dispatch from sklearn.metrics import recall_score, average_precision_score from coco_metric import compute_cider, postprocess_captioning_generation from eval_datasets import VQADataset from tqdm import tqdm from collections import Counter from vqa_metric import compute_vqa_accuracy, compute_gqa_accuracy from open_flamingo.src.factory import create_model_and_transforms from PIL import Image from io import BytesIO from open_flamingo.train.distributed import init_distributed_device, world_info_from_env from open_flamingo.eval.task.reg import evaluate_reg from open_flamingo.eval.task.gqa import GQADataset from open_flamingo.eval.task.vl_checklist import evaluate_vlc from open_flamingo.eval.task.crepe import evaluate_crepe from open_flamingo.eval.task.caption import evaluate_coco_flickr from open_flamingo.eval.task.utils import is_correct, get_iou from open_flamingo.eval.task.cola import evaluate_cola from open_flamingo.eval.task.gqa import evaluate_gqa from open_flamingo.eval.dataset_zoo import VG_Relation, VG_Attribution
8,289
) parser.add_argument( "--use_sam", default=None, type=str, required=False, ) parser.add_argument( "--add_visual_token", default=False, action="store_true", ) parser.add_argument( "--use_format_v2", default=False, action="store_true", ) parser.add_argument( "--eval_aro", default=False, action="store_true", ) parser.add_argument( "--eval_pisc", default=False, action="store_true", ) parser.add_argument( "--eval_reg", default=False, action="store_true", ) parser.add_argument( "--eval_vlc", default=False, action="store_true", ) parser.add_argument( "--eval_crepe", default=False, action="store_true", ) parser.add_argument( "--eval_cola", default=False, action="store_true", ) parser.add_argument( "--level", default=4, type=int, ) parser.add_argument( "--type", default="swap", type=str, ) parser.add_argument( "--choose_left_right", default=False, action="store_true", ) parser.add_argument( "--eval_exp", default=False, action="store_true", ) def preprocess_image(sample, image_processor): image = image_processor(sample) if isinstance(image, transformers.image_processing_utils.BatchFeature): image = torch.tensor(image["pixel_values"][0]) return image class OKVQAPostProcess(): def __init__(self): self._lemmatizer = None def _lemmatize(self, answers): def apply(answer): doc = self.lemmatizer(answer) words = [] for token in doc: if token.pos_ in ["NOUN", "VERB"]: words.append(token.lemma_) else: words.append(token.text) answer = " ".join(words) return answer return [apply(answer) for answer in answers] @property def lemmatizer(self): if self._lemmatizer is None: try: self._lemmatizer = spacy.load("en_core_web_sm") except ImportError: logging.error( """ Please install spacy and en_core_web_sm model to apply lemmatization. python -m spacy download en_core_web_sm OR import spacy.cli spacy.cli.download("en_core_web_sm") """ ) exit(1) return self._lemmatizer def main(): args = parser.parse_args() if args.dist:
def expand2square(pil_img, background_color): width, height = pil_img.size if width == height: return pil_img elif width > height: result = Image.new(pil_img.mode, (width, width), background_color) result.paste(pil_img, (0, (width - height) // 2)) return result else: result = Image.new(pil_img.mode, (height, height), background_color) result.paste(pil_img, ((height - width) // 2, 0)) return result parser = argparse.ArgumentParser() parser.add_argument("--lm_path", type=str, default="facebook/opt-1.3b") parser.add_argument("--lm_tokenizer_path", type=str, default="facebook/opt-30b") parser.add_argument("--vision_encoder_path", default="ViT-L-14", type=str) parser.add_argument("--vision_encoder_pretrained", default="openai", type=str) parser.add_argument("--checkpoint_path", type=str, required=True) parser.add_argument( "--results_file", type=str, default=None, help="JSON file to save results" ) # Trial arguments parser.add_argument("--shots", nargs="+", default=[0, 4, 8, 16, 32], type=int) parser.add_argument( "--num_trials", type=int, default=1, help="Number of trials to run for each shot using different demonstrations", ) parser.add_argument( "--trial_seeds", nargs="+", default=[0], help="Seeds to use for each trial for picking demonstrations and eval sets", ) parser.add_argument( "--num_samples", type=int, default=5000, help="Number of samples to evaluate on" ) parser.add_argument("--batch_size", type=int, default=8) # Per-dataset evaluation flags parser.add_argument( "--eval_coco", action="store_true", default=False, help="Whether to evaluate on COCO.", ) parser.add_argument( "--eval_vqav2", action="store_true", default=False, help="Whether to evaluate on VQAV2.", ) parser.add_argument( "--eval_ok_vqa", action="store_true", default=False, help="Whether to evaluate on OK-VQA.", ) parser.add_argument( "--eval_imagenet", action="store_true", default=False, help="Whether to evaluate on ImageNet.", ) parser.add_argument( "--eval_flickr30", action="store_true", default=False, help="Whether to evaluate on Flickr30.", ) parser.add_argument( "--eval_refcoco", action="store_true", default=False, help="Whether to evaluate on RefCOCO.", ) # Dataset arguments ## Flickr30 Dataset parser.add_argument( "--flickr_image_dir_path", type=str, help="Path to the flickr30/flickr30k_images directory.", default=None, ) parser.add_argument( "--flickr_annotations_json_path", type=str, help="Path to the dataset_flickr30k_coco_style.json file.", default=None, ) ## COCO Dataset parser.add_argument( "--coco_image_dir_path", type=str, help="Path to the flickr30/flickr30k_images directory.", default=None, ) parser.add_argument( "--coco_annotations_json_path", type=str, default=None, ) ## VQAV2 Dataset parser.add_argument( "--vqav2_image_dir_path", type=str, default=None, ) parser.add_argument( "--vqav2_questions_json_path", type=str, default=None, ) parser.add_argument( "--vqav2_annotations_json_path", type=str, default=None, ) ## OK-VQA Dataset parser.add_argument( "--ok_vqa_image_dir_path", type=str, help="Path to the vqav2/train2014 directory.", default=None, ) parser.add_argument( "--ok_vqa_questions_json_path", type=str, help="Path to the v2_OpenEnded_mscoco_train2014_questions.json file.", default=None, ) parser.add_argument( "--ok_vqa_annotations_json_path", type=str, help="Path to the v2_mscoco_train2014_annotations.json file.", default=None, ) ## Imagenet dataset parser.add_argument("--imagenet_root", type=str, default="/tmp") ## RefCOCO dataset parser.add_argument("--refcoco_tsvfile", type=str, default=None) parser.add_argument( "--location_token_num", default=1000, type=int, ) # distributed training parser.add_argument( "--dist-url", default="env://", type=str, help="url used to set up distributed training", ) parser.add_argument( "--dist-backend", default="nccl", type=str, help="distributed backend" ) parser.add_argument( "--horovod", default=False, action="store_true", help="Use horovod for distributed training.", ) parser.add_argument( "--no-set-device-rank", default=False, action="store_true", help="Don't set device index from local rank (when CUDA_VISIBLE_DEVICES restricted to one per proc).", ) parser.add_argument( "--dist", default=False, action="store_true", ) parser.add_argument( "--lora", default=False, action="store_true", ) parser.add_argument( "--lora_r", default=16, type=int, required=False, ) parser.add_argument( "--legacy", default=False, action="store_true", ) parser.add_argument( "--special", default=False, action="store_true", ) parser.add_argument( "--id", default=0, type=int, required=False, ) parser.add_argument( "--eval_gqa", default=False, action="store_true", ) parser.add_argument( "--use_sam", default=None, type=str, required=False, ) parser.add_argument( "--add_visual_token", default=False, action="store_true", ) parser.add_argument( "--use_format_v2", default=False, action="store_true", ) parser.add_argument( "--eval_aro", default=False, action="store_true", ) parser.add_argument( "--eval_pisc", default=False, action="store_true", ) parser.add_argument( "--eval_reg", default=False, action="store_true", ) parser.add_argument( "--eval_vlc", default=False, action="store_true", ) parser.add_argument( "--eval_crepe", default=False, action="store_true", ) parser.add_argument( "--eval_cola", default=False, action="store_true", ) parser.add_argument( "--level", default=4, type=int, ) parser.add_argument( "--type", default="swap", type=str, ) parser.add_argument( "--choose_left_right", default=False, action="store_true", ) parser.add_argument( "--eval_exp", default=False, action="store_true", ) def preprocess_image(sample, image_processor): image = image_processor(sample) if isinstance(image, transformers.image_processing_utils.BatchFeature): image = torch.tensor(image["pixel_values"][0]) return image class OKVQAPostProcess(): def __init__(self): self._lemmatizer = None def _lemmatize(self, answers): def apply(answer): doc = self.lemmatizer(answer) words = [] for token in doc: if token.pos_ in ["NOUN", "VERB"]: words.append(token.lemma_) else: words.append(token.text) answer = " ".join(words) return answer return [apply(answer) for answer in answers] @property def lemmatizer(self): if self._lemmatizer is None: try: self._lemmatizer = spacy.load("en_core_web_sm") except ImportError: logging.error( """ Please install spacy and en_core_web_sm model to apply lemmatization. python -m spacy download en_core_web_sm OR import spacy.cli spacy.cli.download("en_core_web_sm") """ ) exit(1) return self._lemmatizer def main(): args = parser.parse_args() if args.dist:
args.local_rank, args.rank, args.world_size = world_info_from_env()
2
2023-11-07 04:23:57+00:00
12k
HKU-BAL/ClairS-TO
src/extract_candidates_calling.py
[ { "identifier": "VcfReader", "path": "shared/vcf.py", "snippet": "class VcfReader(object):\n def __init__(self, vcf_fn,\n ctg_name=None,\n ctg_start=None,\n ctg_end=None,\n is_var_format=False,\n is_happy_format=False,\n ...
import sys import shlex import os import logging import subprocess import shared.param as param from argparse import ArgumentParser, SUPPRESS from collections import Counter, defaultdict from shared.vcf import VcfReader, VcfWriter from shared.utils import subprocess_popen, file_path_from, region_from, \ reference_sequence_from, str2bool, str_none from shared.interval_tree import bed_tree_from, is_region_in
7,954
split_bed_size = param.split_bed_size candidates_folder = args.candidates_folder min_coverage = args.min_coverage platform = args.platform store_tumor_infos = args.store_tumor_infos alt_fn = args.alt_fn confident_bed_fn = file_path_from(args.bed_fn, allow_none=True, exit_on_not_found=False) is_confident_bed_file_given = confident_bed_fn is not None min_mapping_quality = args.min_mq min_base_quality = args.min_bq flankingBaseNum = param.flankingBaseNum if args.flanking is None else args.flanking no_of_positions = 2 * flankingBaseNum + 1 genotyping_mode_vcf_fn = args.genotyping_mode_vcf_fn hybrid_mode_vcf_fn = args.hybrid_mode_vcf_fn truth_vcf_fn = args.truth_vcf_fn is_truth_vcf_provided = truth_vcf_fn is not None select_indel_candidates = args.select_indel_candidates candidates_set = set() indel_candidates_list = [] snv_candidates_set = set() indel_candidates_set = set() truths_variant_dict = {} if is_truth_vcf_provided: unified_vcf_reader = VcfReader(vcf_fn=truth_vcf_fn, ctg_name=ctg_name, is_var_format=False) unified_vcf_reader.read_vcf() truths_variant_dict = unified_vcf_reader.variant_dict candidates_pos_set = set() add_read_regions = True hybrid_candidate_set = set() indel_hybrid_candidate_set = set() if hybrid_mode_vcf_fn is not None or genotyping_mode_vcf_fn is not None: vcf_fn = hybrid_mode_vcf_fn if hybrid_mode_vcf_fn is not None else genotyping_mode_vcf_fn vcf_reader = VcfReader(vcf_fn=vcf_fn, ctg_name=ctg_name, is_var_format=False) vcf_reader.read_vcf() hybrid_variant_dict = vcf_reader.variant_dict for k, v in hybrid_variant_dict.items(): ref_base, alt_base = v.reference_bases, v.alternate_bases[0] if len(ref_base) > 1 or len(alt_base) > 1: if select_indel_candidates: indel_hybrid_candidate_set.add(k) candidates_set.add(k) hybrid_candidate_set.add(k) hybrid_info_dict = defaultdict(AltInfo) fai_fn = file_path_from(fasta_file_path, suffix=".fai", exit_on_not_found=True, sep='.') if chunk_id is not None: """ Whole genome calling option, acquire contig start end position from reference fasta index(.fai), then split the reference accroding to chunk id and total chunk numbers. """ if is_confident_bed_file_given: # consistent with pileup generation, faster to extract tensor using bed region tree, bed_start, bed_end = bed_tree_from(bed_file_path=confident_bed_fn, contig_name=ctg_name, return_bed_region=True) chunk_size = (bed_end - bed_start) // chunk_num + 1 if (bed_end - bed_start) % chunk_num else ( bed_end - bed_start) // chunk_num ctg_start = bed_start + 1 + chunk_size * chunk_id # 0-base to 1-base ctg_end = ctg_start + chunk_size else: contig_length = 0 with open(fai_fn, 'r') as fai_fp: for row in fai_fp: columns = row.strip().split("\t") contig_name = columns[0] if contig_name != ctg_name: continue contig_length = int(columns[1]) chunk_size = contig_length // chunk_num + 1 if contig_length % chunk_num else contig_length // chunk_num ctg_start = chunk_size * chunk_id # 0-base to 1-base ctg_end = ctg_start + chunk_size candidates_pos_set = set([item for item in candidates_pos_set if item >= ctg_start and item <= ctg_end]) # 1-based regions [start, end] (start and end inclusive) ref_regions = [] reads_regions = [] is_ctg_name_given = ctg_name is not None is_ctg_range_given = is_ctg_name_given and ctg_start is not None and ctg_end is not None if is_ctg_range_given: extend_start = max(ctg_start - ( no_of_positions), 1) extend_end = ctg_end + no_of_positions reads_regions.append(region_from(ctg_name=ctg_name, ctg_start=extend_start, ctg_end=extend_end)) reference_start, reference_end = ctg_start - param.expandReferenceRegion, ctg_end + param.expandReferenceRegion reference_start = 1 if reference_start < 1 else reference_start ref_regions.append(region_from(ctg_name=ctg_name, ctg_start=reference_start, ctg_end=reference_end)) elif is_ctg_name_given: reads_regions.append(region_from(ctg_name=ctg_name)) ref_regions.append(region_from(ctg_name=ctg_name)) reference_start = 1 reference_sequence = reference_sequence_from( samtools_execute_command=samtools_execute_command, fasta_file_path=fasta_file_path, regions=ref_regions ) if reference_sequence is None or len(reference_sequence) == 0: sys.exit("[ERROR] Failed to load reference sequence from file ({}).".format(fasta_file_path)) mq_option = ' --min-MQ {}'.format(min_mapping_quality) bq_option = ' --min-BQ {}'.format(min_base_quality) read_name_option = ' --output-QNAME' if store_tumor_infos else ' ' bed_option = ' -l {}'.format( confident_bed_fn) if is_confident_bed_file_given else "" flags_option = ' --excl-flags {} '.format(param.SAMTOOLS_VIEW_FILTER_FLAG) max_depth_option = ' --max-depth {} '.format(args.max_depth) if args.max_depth is not None else " " reads_regions_option = ' -r {}'.format(" ".join(reads_regions)) if add_read_regions else "" stdin = None if tumor_bam_file_path != "PIPE" else sys.stdin tumor_bam_file_path = tumor_bam_file_path if tumor_bam_file_path != "PIPE" else "-" samtools_command = samtools_execute_command + " mpileup --reverse-del" + read_name_option + reads_regions_option + \ mq_option + bq_option + bed_option + flags_option + max_depth_option
# BSD 3-Clause License # # Copyright 2023 The University of Hong Kong, Department of Computer Science # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. logging.basicConfig(format='%(message)s', level=logging.INFO) class AltInfo(object): def __init__(self, ref_base='', tumor_alt_info=""): self.ref_base = ref_base self.tumor_alt_info = tumor_alt_info def decode_pileup_bases(pileup_bases, reference_base, min_coverage, minimum_snv_af_for_candidate, minimum_indel_af_for_candidate, alternative_base_num, has_pileup_candidates, read_name_list, is_tumor, select_indel_candidates=False, platform="ont"): """ Decode mpileup input string. pileup_bases: pileup base string for each position, include all mapping information. reference_base: upper reference base for cigar calculation. pileup_dict: dictionary (pos: pos info) which keep read information that cover specific position. ref_seq: chunked reference sequence in window, start: center pos - flankingBaseNum, end: center + flankingBaseNum + 1. reference_sequence: reference sequence index by contig:start-end. 0-based. minimum_af_for_candidate: default minimum alleic frequency for candidate filtering, filter if below specific thredshold. has_pileup_candidates: if the candidate is directly obtained from pileup output, then no need to check the af filtering. """ base_idx = 0 base_list = [] while base_idx < len(pileup_bases): base = pileup_bases[base_idx] if base == '+' or base == '-': base_idx += 1 advance = 0 while True: num = pileup_bases[base_idx] if num.isdigit(): advance = advance * 10 + int(num) base_idx += 1 else: break base_list[-1][1] = base + pileup_bases[base_idx: base_idx + advance] # add indel seq base_idx += advance - 1 elif base in "ACGTNacgtn#*": base_list.append([base, ""]) elif base == '^': # start of read, next base is mq, update mq info base_idx += 1 # skip $, the end of read base_idx += 1 pileup_dict = defaultdict(int) base_counter = Counter([''.join(item) for item in base_list]) alt_dict = dict(Counter([''.join(item).upper() for item in base_list])) tumor_alt_dict = dict(Counter([''.join(item).upper() for item, read_name in zip(base_list, read_name_list) if read_name.startswith('t')])) if is_tumor else None depth = 0 for key, count in base_counter.items(): if key[0].upper() in 'ACGT': pileup_dict[key[0].upper()] += count depth += count elif key[0] in "#*": depth += count if len(key) > 1 and key[1] == '+': if select_indel_candidates: pileup_dict['I' + key[0].upper() + key[2:].upper()] += count else: pileup_dict['I'] += count elif len(key) > 1 and key[1] == '-': if select_indel_candidates: pileup_dict['D' + len(key[2:]) * "N"] += count else: pileup_dict['D'] += count denominator = depth if depth > 0 else 1 pileup_list = sorted(list(pileup_dict.items()), key=lambda x: x[1], reverse=True) pass_snv_af = False pass_indel_af = False pass_depth = depth > min_coverage for item, count in pileup_list: if item == reference_base: continue elif item[0] in 'ID': if select_indel_candidates: pass_indel_af = (pass_indel_af or (float(count) / denominator >= minimum_indel_af_for_candidate and ( alternative_base_num is not None and count >= alternative_base_num))) continue pass_snv_af = pass_snv_af or (float(count) / denominator >= minimum_snv_af_for_candidate) and ( alternative_base_num is not None and count >= alternative_base_num) af = (float(pileup_list[1][1]) / denominator) if len(pileup_list) > 1 else 0.0 af = (float(pileup_list[0][1]) / denominator) if len(pileup_list) >= 1 and pileup_list[0][ 0] != reference_base else af pass_af = (pass_snv_af or pass_indel_af) and pass_depth alt_list = sorted(list(alt_dict.items()), key=lambda x: x[1], reverse=True) alt_list = [[item[0], str(round(item[1] / denominator, 3))] for item in alt_list if item[0].upper() != reference_base] if not pass_af: return base_list, depth, pass_af, af, "", "", "", alt_list, pass_snv_af, pass_indel_af, pileup_list pileup_list = [[item[0], str(round(item[1] / denominator, 3))] for item in pileup_list] af_infos = ','.join([item[1] for item in pileup_list if item[0] != reference_base]) pileup_infos = ' '.join([item[0] + ':' + item[1] for item in alt_list]) if tumor_alt_dict is not None: tumor_alt_list = sorted(list(tumor_alt_dict.items()), key=lambda x: x[1], reverse=True) tumor_alt_list = [[item[0], str(round(item[1] / denominator, 3))] for item in tumor_alt_list] tumor_pileup_infos = ' '.join([item[0] + ':' + item[1] for item in tumor_alt_list]) else: tumor_pileup_infos = "" return base_list, depth, pass_af, af, af_infos, pileup_infos, tumor_pileup_infos, alt_list, pass_snv_af, pass_indel_af, pileup_list def extract_pair_candidates(args): ctg_start = args.ctg_start ctg_end = args.ctg_end fasta_file_path = args.ref_fn ctg_name = args.ctg_name samtools_execute_command = args.samtools output_depth = args.output_depth output_alt_info = args.output_alt_info tumor_bam_file_path = args.tumor_bam_fn chunk_id = args.chunk_id - 1 if args.chunk_id else None # 1-base to 0-base chunk_num = args.chunk_num minimum_snv_af_for_candidate = args.snv_min_af minimum_indel_af_for_candidate = args.indel_min_af minimum_snv_af_for_truth = args.min_truth_snv_af minimum_indel_af_for_truth = args.min_truth_snv_af alternative_base_num = args.alternative_base_num split_bed_size = param.split_bed_size candidates_folder = args.candidates_folder min_coverage = args.min_coverage platform = args.platform store_tumor_infos = args.store_tumor_infos alt_fn = args.alt_fn confident_bed_fn = file_path_from(args.bed_fn, allow_none=True, exit_on_not_found=False) is_confident_bed_file_given = confident_bed_fn is not None min_mapping_quality = args.min_mq min_base_quality = args.min_bq flankingBaseNum = param.flankingBaseNum if args.flanking is None else args.flanking no_of_positions = 2 * flankingBaseNum + 1 genotyping_mode_vcf_fn = args.genotyping_mode_vcf_fn hybrid_mode_vcf_fn = args.hybrid_mode_vcf_fn truth_vcf_fn = args.truth_vcf_fn is_truth_vcf_provided = truth_vcf_fn is not None select_indel_candidates = args.select_indel_candidates candidates_set = set() indel_candidates_list = [] snv_candidates_set = set() indel_candidates_set = set() truths_variant_dict = {} if is_truth_vcf_provided: unified_vcf_reader = VcfReader(vcf_fn=truth_vcf_fn, ctg_name=ctg_name, is_var_format=False) unified_vcf_reader.read_vcf() truths_variant_dict = unified_vcf_reader.variant_dict candidates_pos_set = set() add_read_regions = True hybrid_candidate_set = set() indel_hybrid_candidate_set = set() if hybrid_mode_vcf_fn is not None or genotyping_mode_vcf_fn is not None: vcf_fn = hybrid_mode_vcf_fn if hybrid_mode_vcf_fn is not None else genotyping_mode_vcf_fn vcf_reader = VcfReader(vcf_fn=vcf_fn, ctg_name=ctg_name, is_var_format=False) vcf_reader.read_vcf() hybrid_variant_dict = vcf_reader.variant_dict for k, v in hybrid_variant_dict.items(): ref_base, alt_base = v.reference_bases, v.alternate_bases[0] if len(ref_base) > 1 or len(alt_base) > 1: if select_indel_candidates: indel_hybrid_candidate_set.add(k) candidates_set.add(k) hybrid_candidate_set.add(k) hybrid_info_dict = defaultdict(AltInfo) fai_fn = file_path_from(fasta_file_path, suffix=".fai", exit_on_not_found=True, sep='.') if chunk_id is not None: """ Whole genome calling option, acquire contig start end position from reference fasta index(.fai), then split the reference accroding to chunk id and total chunk numbers. """ if is_confident_bed_file_given: # consistent with pileup generation, faster to extract tensor using bed region tree, bed_start, bed_end = bed_tree_from(bed_file_path=confident_bed_fn, contig_name=ctg_name, return_bed_region=True) chunk_size = (bed_end - bed_start) // chunk_num + 1 if (bed_end - bed_start) % chunk_num else ( bed_end - bed_start) // chunk_num ctg_start = bed_start + 1 + chunk_size * chunk_id # 0-base to 1-base ctg_end = ctg_start + chunk_size else: contig_length = 0 with open(fai_fn, 'r') as fai_fp: for row in fai_fp: columns = row.strip().split("\t") contig_name = columns[0] if contig_name != ctg_name: continue contig_length = int(columns[1]) chunk_size = contig_length // chunk_num + 1 if contig_length % chunk_num else contig_length // chunk_num ctg_start = chunk_size * chunk_id # 0-base to 1-base ctg_end = ctg_start + chunk_size candidates_pos_set = set([item for item in candidates_pos_set if item >= ctg_start and item <= ctg_end]) # 1-based regions [start, end] (start and end inclusive) ref_regions = [] reads_regions = [] is_ctg_name_given = ctg_name is not None is_ctg_range_given = is_ctg_name_given and ctg_start is not None and ctg_end is not None if is_ctg_range_given: extend_start = max(ctg_start - ( no_of_positions), 1) extend_end = ctg_end + no_of_positions reads_regions.append(region_from(ctg_name=ctg_name, ctg_start=extend_start, ctg_end=extend_end)) reference_start, reference_end = ctg_start - param.expandReferenceRegion, ctg_end + param.expandReferenceRegion reference_start = 1 if reference_start < 1 else reference_start ref_regions.append(region_from(ctg_name=ctg_name, ctg_start=reference_start, ctg_end=reference_end)) elif is_ctg_name_given: reads_regions.append(region_from(ctg_name=ctg_name)) ref_regions.append(region_from(ctg_name=ctg_name)) reference_start = 1 reference_sequence = reference_sequence_from( samtools_execute_command=samtools_execute_command, fasta_file_path=fasta_file_path, regions=ref_regions ) if reference_sequence is None or len(reference_sequence) == 0: sys.exit("[ERROR] Failed to load reference sequence from file ({}).".format(fasta_file_path)) mq_option = ' --min-MQ {}'.format(min_mapping_quality) bq_option = ' --min-BQ {}'.format(min_base_quality) read_name_option = ' --output-QNAME' if store_tumor_infos else ' ' bed_option = ' -l {}'.format( confident_bed_fn) if is_confident_bed_file_given else "" flags_option = ' --excl-flags {} '.format(param.SAMTOOLS_VIEW_FILTER_FLAG) max_depth_option = ' --max-depth {} '.format(args.max_depth) if args.max_depth is not None else " " reads_regions_option = ' -r {}'.format(" ".join(reads_regions)) if add_read_regions else "" stdin = None if tumor_bam_file_path != "PIPE" else sys.stdin tumor_bam_file_path = tumor_bam_file_path if tumor_bam_file_path != "PIPE" else "-" samtools_command = samtools_execute_command + " mpileup --reverse-del" + read_name_option + reads_regions_option + \ mq_option + bq_option + bed_option + flags_option + max_depth_option
samtools_mpileup_process = subprocess_popen(
2
2023-11-07 04:39:16+00:00
12k
sb-ai-lab/HypEx
tests/test_aa.py
[ { "identifier": "AATest", "path": "hypex/ab_test/aa_tester.py", "snippet": "class AATest:\n \"\"\"\n A class for conducting AA testing (random split testing) to assess the\n statistical uniform of two samples.\n\n AA testing is used to validate that the splitting mechanism of an A/B test\n ...
import pandas as pd import pytest import sys from pathlib import Path from hypex import AATest from hypex.utils.tutorial_data_creation import create_test_data
9,049
sys.path.append(str(Path(".").absolute().parent)) @pytest.fixture def data():
sys.path.append(str(Path(".").absolute().parent)) @pytest.fixture def data():
return create_test_data(rs=52)
1
2023-11-01 08:58:57+00:00
12k
mileswyn/SAMIHS
models/segment_anything_samihs/automatic_mask_generator.py
[ { "identifier": "Samihs", "path": "models/segment_anything_samihs/modeling/samihs.py", "snippet": "class Samihs(nn.Module):\n mask_threshold: float = 0.0\n image_format: str = \"RGB\"\n\n def __init__(\n self,\n image_encoder: ImageEncoderViT,\n prompt_encoder: PromptEncode...
import numpy as np import torch import cv2 # type: ignore # noqa: F401 from torchvision.ops.boxes import batched_nms, box_area # type: ignore from typing import Any, Dict, List, Optional, Tuple from .modeling import Samihs from .utils.amg import ( MaskData, area_from_rle, batch_iterator, batched_mask_to_box, box_xyxy_to_xywh, build_all_layer_point_grids, calculate_stability_score, coco_encode_rle, generate_crop_boxes, is_box_near_crop_edge, mask_to_rle_pytorch, remove_small_regions, rle_to_mask, uncrop_boxes_xyxy, uncrop_masks, uncrop_points, ) from pycocotools import mask as mask_utils # type: ignore # noqa: F401
8,058
point sampling. points_per_batch (int): Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU memory. pred_iou_thresh (float): A filtering threshold in [0,1], using the model's predicted mask quality. stability_score_thresh (float): A filtering threshold in [0,1], using the stability of the mask under changes to the cutoff used to binarize the model's mask predictions. stability_score_offset (float): The amount to shift the cutoff when calculated the stability score. box_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks. crop_n_layers (int): If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2**i_layer number of image crops. crop_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks between different crops. crop_overlap_ratio (float): Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. crop_n_points_downscale_factor (int): The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n. point_grids (list(np.ndarray) or None): A list over explicit grids of points used for sampling, normalized to [0,1]. The nth grid in the list is used in the nth crop layer. Exclusive with points_per_side. min_mask_region_area (int): If >0, postprocessing will be applied to remove disconnected regions and holes in masks with area smaller than min_mask_region_area. Requires opencv. output_mode (str): The form masks are returned in. Can be 'binary_mask', 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. For large resolutions, 'binary_mask' may consume large amounts of memory. """ assert (points_per_side is None) != ( point_grids is None ), "Exactly one of points_per_side or point_grid must be provided." if points_per_side is not None: self.point_grids = build_all_layer_point_grids( points_per_side, crop_n_layers, crop_n_points_downscale_factor, ) elif point_grids is not None: self.point_grids = point_grids else: raise ValueError("Can't have both points_per_side and point_grid be None.") assert output_mode in [ "binary_mask", "uncompressed_rle", "coco_rle", ], f"Unknown output_mode {output_mode}." if output_mode == "coco_rle": if min_mask_region_area > 0: self.points_per_batch = points_per_batch self.pred_iou_thresh = pred_iou_thresh self.stability_score_thresh = stability_score_thresh self.stability_score_offset = stability_score_offset self.box_nms_thresh = box_nms_thresh self.crop_n_layers = crop_n_layers self.crop_nms_thresh = crop_nms_thresh self.crop_overlap_ratio = crop_overlap_ratio self.crop_n_points_downscale_factor = crop_n_points_downscale_factor self.min_mask_region_area = min_mask_region_area self.output_mode = output_mode @torch.no_grad() def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: """ Generates masks for the given image. Arguments: image (np.ndarray): The image to generate masks for, in HWC uint8 format. Returns: list(dict(str, any)): A list over records for masks. Each record is a dict containing the following keys: segmentation (dict(str, any) or np.ndarray): The mask. If output_mode='binary_mask', is an array of shape HW. Otherwise, is a dictionary containing the RLE. bbox (list(float)): The box around the mask, in XYWH format. area (int): The area in pixels of the mask. predicted_iou (float): The model's own prediction of the mask's quality. This is filtered by the pred_iou_thresh parameter. point_coords (list(list(float))): The point coordinates input to the model to generate this mask. stability_score (float): A measure of the mask's quality. This is filtered on using the stability_score_thresh parameter. crop_box (list(float)): The crop of the image used to generate the mask, given in XYWH format. """ # Generate masks mask_data = self._generate_masks(image) # Filter small disconnected regions and holes in masks if self.min_mask_region_area > 0: mask_data = self.postprocess_small_regions( mask_data, self.min_mask_region_area, max(self.box_nms_thresh, self.crop_nms_thresh), ) # Encode masks if self.output_mode == "coco_rle": mask_data["segmentations"] = [coco_encode_rle(rle) for rle in mask_data["rles"]] elif self.output_mode == "binary_mask": mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]] else: mask_data["segmentations"] = mask_data["rles"] # Write mask records curr_anns = [] for idx in range(len(mask_data["segmentations"])): ann = { "segmentation": mask_data["segmentations"][idx], "area": area_from_rle(mask_data["rles"][idx]),
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. class SamAutomaticMaskGenerator: def __init__( self, model: Samihs, points_per_side: Optional[int] = 32, points_per_batch: int = 64, pred_iou_thresh: float = 0.88, stability_score_thresh: float = 0.95, stability_score_offset: float = 1.0, box_nms_thresh: float = 0.7, crop_n_layers: int = 0, crop_nms_thresh: float = 0.7, crop_overlap_ratio: float = 512 / 1500, crop_n_points_downscale_factor: int = 1, point_grids: Optional[List[np.ndarray]] = None, min_mask_region_area: int = 0, output_mode: str = "binary_mask", ) -> None: """ Using a SAM model, generates masks for the entire image. Generates a grid of point prompts over the image, then filters low quality and duplicate masks. The default settings are chosen for SAM with a ViT-H backbone. Arguments: model (Sam): The SAM model to use for mask prediction. points_per_side (int or None): The number of points to be sampled along one side of the image. The total number of points is points_per_side**2. If None, 'point_grids' must provide explicit point sampling. points_per_batch (int): Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU memory. pred_iou_thresh (float): A filtering threshold in [0,1], using the model's predicted mask quality. stability_score_thresh (float): A filtering threshold in [0,1], using the stability of the mask under changes to the cutoff used to binarize the model's mask predictions. stability_score_offset (float): The amount to shift the cutoff when calculated the stability score. box_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks. crop_n_layers (int): If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2**i_layer number of image crops. crop_nms_thresh (float): The box IoU cutoff used by non-maximal suppression to filter duplicate masks between different crops. crop_overlap_ratio (float): Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap. crop_n_points_downscale_factor (int): The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n. point_grids (list(np.ndarray) or None): A list over explicit grids of points used for sampling, normalized to [0,1]. The nth grid in the list is used in the nth crop layer. Exclusive with points_per_side. min_mask_region_area (int): If >0, postprocessing will be applied to remove disconnected regions and holes in masks with area smaller than min_mask_region_area. Requires opencv. output_mode (str): The form masks are returned in. Can be 'binary_mask', 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. For large resolutions, 'binary_mask' may consume large amounts of memory. """ assert (points_per_side is None) != ( point_grids is None ), "Exactly one of points_per_side or point_grid must be provided." if points_per_side is not None: self.point_grids = build_all_layer_point_grids( points_per_side, crop_n_layers, crop_n_points_downscale_factor, ) elif point_grids is not None: self.point_grids = point_grids else: raise ValueError("Can't have both points_per_side and point_grid be None.") assert output_mode in [ "binary_mask", "uncompressed_rle", "coco_rle", ], f"Unknown output_mode {output_mode}." if output_mode == "coco_rle": if min_mask_region_area > 0: self.points_per_batch = points_per_batch self.pred_iou_thresh = pred_iou_thresh self.stability_score_thresh = stability_score_thresh self.stability_score_offset = stability_score_offset self.box_nms_thresh = box_nms_thresh self.crop_n_layers = crop_n_layers self.crop_nms_thresh = crop_nms_thresh self.crop_overlap_ratio = crop_overlap_ratio self.crop_n_points_downscale_factor = crop_n_points_downscale_factor self.min_mask_region_area = min_mask_region_area self.output_mode = output_mode @torch.no_grad() def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: """ Generates masks for the given image. Arguments: image (np.ndarray): The image to generate masks for, in HWC uint8 format. Returns: list(dict(str, any)): A list over records for masks. Each record is a dict containing the following keys: segmentation (dict(str, any) or np.ndarray): The mask. If output_mode='binary_mask', is an array of shape HW. Otherwise, is a dictionary containing the RLE. bbox (list(float)): The box around the mask, in XYWH format. area (int): The area in pixels of the mask. predicted_iou (float): The model's own prediction of the mask's quality. This is filtered by the pred_iou_thresh parameter. point_coords (list(list(float))): The point coordinates input to the model to generate this mask. stability_score (float): A measure of the mask's quality. This is filtered on using the stability_score_thresh parameter. crop_box (list(float)): The crop of the image used to generate the mask, given in XYWH format. """ # Generate masks mask_data = self._generate_masks(image) # Filter small disconnected regions and holes in masks if self.min_mask_region_area > 0: mask_data = self.postprocess_small_regions( mask_data, self.min_mask_region_area, max(self.box_nms_thresh, self.crop_nms_thresh), ) # Encode masks if self.output_mode == "coco_rle": mask_data["segmentations"] = [coco_encode_rle(rle) for rle in mask_data["rles"]] elif self.output_mode == "binary_mask": mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]] else: mask_data["segmentations"] = mask_data["rles"] # Write mask records curr_anns = [] for idx in range(len(mask_data["segmentations"])): ann = { "segmentation": mask_data["segmentations"][idx], "area": area_from_rle(mask_data["rles"][idx]),
"bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(),
5
2023-11-09 07:26:33+00:00
12k
tianhaowuhz/human-assisting-dex-grasp
Runners/TrainGFPPO.py
[ { "identifier": "GFPPO", "path": "Algorithms/ppo/gf_ppo_update.py", "snippet": "class GFPPO:\n def __init__(self,\n vec_env,\n cfg_train,\n device='cpu',\n sampler='sequential',\n log_dir='run',\n is_testi...
import isaacgym import condexenvs import torch import os import sys from Algorithms.ppo import GFPPO from utils.config import load_cfg, get_args, set_np_formatting
10,617
sys.path.append(os.path.dirname(os.path.dirname(__file__))) if __name__ == '__main__': set_np_formatting() args = get_args()
sys.path.append(os.path.dirname(os.path.dirname(__file__))) if __name__ == '__main__': set_np_formatting() args = get_args()
cfg_train, logdir = load_cfg(args)
1
2023-11-09 06:08:40+00:00
12k
ApolloAuto/apollo-model-centerpoint
paddle3d/models/detection/smoke/smoke.py
[ { "identifier": "manager", "path": "paddle3d/apis/manager.py", "snippet": "class ComponentManager:\n def __init__(self, *, name: str, description: str = ''):\n def __len__(self):\n def __repr__(self):\n def __getitem__(self, item: str):\n def components_dict(self) -> dict:\n def name(s...
import os import paddle import paddle.nn as nn import paddle.nn.functional as F from typing import List, Tuple from paddle3d.apis import manager from paddle3d.geometries import BBoxes2D, BBoxes3D, CoordMode from paddle3d.models.base import BaseMonoModel from paddle3d.models.detection.smoke.processor import PostProcessor from paddle3d.models.detection.smoke.smoke_loss import SMOKELossComputation from paddle3d.sample import Sample from paddle3d.utils.logger import logger
7,597
# Copyright (c) 2022 PaddlePaddle 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. @manager.MODELS.add_component class SMOKE(BaseMonoModel): """ """ def __init__(self, backbone, head, depth_ref: Tuple, dim_ref: Tuple, max_detection: int = 50, pred_2d: bool = True, box_with_velocity: bool = False): super().__init__( box_with_velocity=box_with_velocity, need_camera_to_image=True, need_lidar_to_camera=False, need_down_ratios=True) self.backbone = backbone self.heads = head self.max_detection = max_detection self.init_weight()
# Copyright (c) 2022 PaddlePaddle 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. @manager.MODELS.add_component class SMOKE(BaseMonoModel): """ """ def __init__(self, backbone, head, depth_ref: Tuple, dim_ref: Tuple, max_detection: int = 50, pred_2d: bool = True, box_with_velocity: bool = False): super().__init__( box_with_velocity=box_with_velocity, need_camera_to_image=True, need_lidar_to_camera=False, need_down_ratios=True) self.backbone = backbone self.heads = head self.max_detection = max_detection self.init_weight()
self.loss_computation = SMOKELossComputation(
6
2023-11-08 07:08:03+00:00
12k
camlsys/fl-project-template
project/main.py
[ { "identifier": "get_client_generator", "path": "project/client/client.py", "snippet": "def get_client_generator(\n working_dir: Path,\n net_generator: NetGen,\n dataloader_gen: ClientDataloaderGen,\n train: TrainFunc,\n test: TestFunc,\n) -> ClientGen:\n \"\"\"Return a function which ...
import json import logging import os import subprocess import sys import flwr as fl import hydra import wandb from pathlib import Path from typing import cast from flwr.common.logger import log from hydra.core.hydra_config import HydraConfig from hydra.utils import instantiate from omegaconf import DictConfig, OmegaConf from project.client.client import get_client_generator from project.dispatch.dispatch import dispatch_config, dispatch_data, dispatch_train from project.fed.server.deterministic_client_manager import DeterministicClientManager from project.fed.server.wandb_history import WandbHistory from project.fed.server.wandb_server import WandbServer from project.fed.utils.utils import ( get_initial_parameters, get_save_parameters_to_file, get_weighted_avg_metrics_agg_fn, test_client, ) from project.types.common import ClientGen, FedEvalFN from project.utils.utils import ( FileSystemManager, RayContextManager, seed_everything, wandb_init, )
7,950
"""Create and connect the building blocks for your experiments; start the simulation. It includes processing the dataset, instantiate strategy, specifying how the global model will be evaluated, etc. In the end, this script saves the results. """ # Only import from the project root # Never do a relative import nor one that assumes a given folder structure # Make debugging easier when using Hydra + Ray os.environ["HYDRA_FULL_ERROR"] = "1" os.environ["OC_CAUSE"] = "1" @hydra.main( config_path="conf", config_name="base", version_base=None, ) def main(cfg: DictConfig) -> None: """Run the baseline. Parameters ---------- cfg : DictConfig An omegaconf object that stores the hydra config. """ # Print parsed config log(logging.INFO, OmegaConf.to_yaml(cfg)) wandb_config = OmegaConf.to_container( cfg, resolve=True, throw_on_missing=True, ) # Obtain the output dir from hydra original_hydra_dir = Path( hydra.utils.to_absolute_path( HydraConfig.get().runtime.output_dir, ), ) output_directory = original_hydra_dir # Reuse an output directory for checkpointing if cfg.reuse_output_dir is not None: output_directory = Path(cfg.reuse_output_dir) # The directory to save data to results_dir = output_directory / "results" results_dir.mkdir(parents=True, exist_ok=True) # Where to save files to and from if cfg.working_dir is not None: # Pre-defined directory working_dir = Path(cfg.working_dir) else: # Default directory working_dir = output_directory / "working" working_dir.mkdir(parents=True, exist_ok=True) # Wandb context manager # controlls if wandb is initialised or not # if not it returns a dummy run with wandb_init( cfg.use_wandb, **cfg.wandb.setup, settings=wandb.Settings(start_method="thread"), config=wandb_config, ) as run: log( logging.INFO, "Wandb run initialized with %s", cfg.use_wandb, ) # Context managers for saving and cleaning up files # from the working directory # at the start/end of the simulation # The RayContextManager deletes the ray session folder with ( FileSystemManager( working_dir=working_dir, output_dir=results_dir, to_clean_once=cfg.to_clean_once, to_save_once=cfg.to_save_once, original_hydra_dir=original_hydra_dir, reuse_output_dir=cfg.reuse_output_dir, file_limit=cfg.file_limit, ) as fs_manager, RayContextManager() as _ray_manager, ): # Which files to save every <to_save_per_round> rounds # e.g. model checkpoints save_files_per_round = fs_manager.get_save_files_every_round( cfg.to_save_per_round, cfg.save_frequency, ) # For checkpointed runs, adjust the seed # so different clients are sampled adjusted_seed = cfg.fed.seed ^ fs_manager.checkpoint_index save_parameters_to_file = get_save_parameters_to_file(working_dir) # Client manager that samples the same clients # For a given seed+checkpoint combination
"""Create and connect the building blocks for your experiments; start the simulation. It includes processing the dataset, instantiate strategy, specifying how the global model will be evaluated, etc. In the end, this script saves the results. """ # Only import from the project root # Never do a relative import nor one that assumes a given folder structure # Make debugging easier when using Hydra + Ray os.environ["HYDRA_FULL_ERROR"] = "1" os.environ["OC_CAUSE"] = "1" @hydra.main( config_path="conf", config_name="base", version_base=None, ) def main(cfg: DictConfig) -> None: """Run the baseline. Parameters ---------- cfg : DictConfig An omegaconf object that stores the hydra config. """ # Print parsed config log(logging.INFO, OmegaConf.to_yaml(cfg)) wandb_config = OmegaConf.to_container( cfg, resolve=True, throw_on_missing=True, ) # Obtain the output dir from hydra original_hydra_dir = Path( hydra.utils.to_absolute_path( HydraConfig.get().runtime.output_dir, ), ) output_directory = original_hydra_dir # Reuse an output directory for checkpointing if cfg.reuse_output_dir is not None: output_directory = Path(cfg.reuse_output_dir) # The directory to save data to results_dir = output_directory / "results" results_dir.mkdir(parents=True, exist_ok=True) # Where to save files to and from if cfg.working_dir is not None: # Pre-defined directory working_dir = Path(cfg.working_dir) else: # Default directory working_dir = output_directory / "working" working_dir.mkdir(parents=True, exist_ok=True) # Wandb context manager # controlls if wandb is initialised or not # if not it returns a dummy run with wandb_init( cfg.use_wandb, **cfg.wandb.setup, settings=wandb.Settings(start_method="thread"), config=wandb_config, ) as run: log( logging.INFO, "Wandb run initialized with %s", cfg.use_wandb, ) # Context managers for saving and cleaning up files # from the working directory # at the start/end of the simulation # The RayContextManager deletes the ray session folder with ( FileSystemManager( working_dir=working_dir, output_dir=results_dir, to_clean_once=cfg.to_clean_once, to_save_once=cfg.to_save_once, original_hydra_dir=original_hydra_dir, reuse_output_dir=cfg.reuse_output_dir, file_limit=cfg.file_limit, ) as fs_manager, RayContextManager() as _ray_manager, ): # Which files to save every <to_save_per_round> rounds # e.g. model checkpoints save_files_per_round = fs_manager.get_save_files_every_round( cfg.to_save_per_round, cfg.save_frequency, ) # For checkpointed runs, adjust the seed # so different clients are sampled adjusted_seed = cfg.fed.seed ^ fs_manager.checkpoint_index save_parameters_to_file = get_save_parameters_to_file(working_dir) # Client manager that samples the same clients # For a given seed+checkpoint combination
client_manager = DeterministicClientManager(
4
2023-11-08 15:31:44+00:00
12k
silicx/GoldFromOres
DatasetCondensation/main.py
[ { "identifier": "get_loops", "path": "DatasetCondensation/utils.py", "snippet": "def get_loops(ipc):\r\n # Get the two hyper-parameters of outer-loop and inner-loop.\r\n # The following values are empirically good.\r\n if ipc == 1:\r\n outer_loop, inner_loop = 1, 1\r\n elif ipc == 10:...
import os import time import copy import argparse import numpy as np import torch import torch.nn as nn import pdb from torchvision.utils import save_image from .utils import get_loops, get_dataset, get_network, get_eval_pool, evaluate_synset, get_daparam, match_loss, get_time, TensorDataset, epoch, DiffAugment, ParamDiffAug from drop_utils import drop_samples
7,657
def main(): parser = argparse.ArgumentParser(description='Parameter Processing') parser.add_argument('--method', type=str, default='DC', help='DC/DSA') parser.add_argument('--dataset', type=str, default='CIFAR10', help='dataset') parser.add_argument('--model', type=str, default='ConvNet', help='model') parser.add_argument('--ipc', type=int, default=1, help='image(s) per class') parser.add_argument('--eval_mode', type=str, default='S', help='eval_mode') # S: the same to training model, M: multi architectures, W: net width, D: net depth, A: activation function, P: pooling layer, N: normalization layer, parser.add_argument('--num_exp', type=int, default=5, help='the number of experiments') parser.add_argument('--num_eval', type=int, default=20, help='the number of evaluating randomly initialized models') parser.add_argument('--epoch_eval_train', type=int, default=300, help='epochs to train a model with synthetic data') parser.add_argument('--Iteration', type=int, default=1000, help='training iterations') parser.add_argument('--lr_img', type=float, default=0.1, help='learning rate for updating synthetic images') parser.add_argument('--lr_net', type=float, default=0.01, help='learning rate for updating network parameters') parser.add_argument('--batch_real', type=int, default=256, help='batch size for real data') parser.add_argument('--batch_train', type=int, default=256, help='batch size for training networks') parser.add_argument('--init', type=str, default='noise', help='noise/real: initialize synthetic images from random noise or randomly sampled real images.') parser.add_argument('--dsa_strategy', type=str, default='None', help='differentiable Siamese augmentation strategy') parser.add_argument('--data_path', type=str, default='data', help='dataset path') parser.add_argument('--save_path', type=str, default='result', help='path to save results') parser.add_argument('--dis_metric', type=str, default='ours', help='distance metric') parser.add_argument('--drop_criterion', type=str, default='LossConverge_large', help='Criterion for data dropping') parser.add_argument('--drop_ratio', type=float, default=0.0, help='The ratio to drop (for each class)') args = parser.parse_args() args.outer_loop, args.inner_loop = get_loops(args.ipc) args.device = 'cuda' if torch.cuda.is_available() else 'cpu' args.dsa_param = ParamDiffAug() args.dsa = True if args.method == 'DSA' else False if not os.path.exists(args.data_path): os.mkdir(args.data_path) if not os.path.exists(args.save_path): os.mkdir(args.save_path) eval_it_pool = np.arange(0, args.Iteration+1, 500).tolist() if args.eval_mode == 'S' or args.eval_mode == 'SS' else [args.Iteration] # The list of iterations when we evaluate models and record results. print('eval_it_pool: ', eval_it_pool) channel, im_size, num_classes, class_names, mean, std, dst_train, dst_test, testloader = get_dataset(args.dataset, args.data_path) model_eval_pool = get_eval_pool(args.eval_mode, args.model, args.model) accs_all_exps = dict() # record performances of all experiments for key in model_eval_pool: accs_all_exps[key] = [] data_save = [] for exp in range(args.num_exp): print('\n================== Exp %d ==================\n '%exp) print('Hyper-parameters: \n', args.__dict__) print('Evaluation model pool: ', model_eval_pool) ''' organize the real dataset ''' images_all = [] labels_all = [] indices_class = [[] for c in range(num_classes)] images_all = [torch.unsqueeze(dst_train[i][0], dim=0) for i in range(len(dst_train))] labels_all = [dst_train[i][1] for i in range(len(dst_train))] for i, lab in enumerate(labels_all): indices_class[lab].append(i) images_all = torch.cat(images_all, dim=0).to(args.device) labels_all = torch.tensor(labels_all, dtype=torch.long, device=args.device) images_all, labels_all, indices_class = drop_samples( images_all, labels_all, indices_class, args.dataset, args.drop_criterion, drop_ratio=args.drop_ratio) for c in range(num_classes): print('class c = %d: %d real images'%(c, len(indices_class[c]))) def get_images(c, n): # get random n images from class c idx_shuffle = np.random.permutation(indices_class[c])[:n] return images_all[idx_shuffle] for ch in range(channel): print('real images channel %d, mean = %.4f, std = %.4f'%(ch, torch.mean(images_all[:, ch]), torch.std(images_all[:, ch]))) ''' initialize the synthetic data ''' image_syn = torch.randn(size=(num_classes*args.ipc, channel, im_size[0], im_size[1]), dtype=torch.float, requires_grad=True, device=args.device) label_syn = torch.tensor([np.ones(args.ipc)*i for i in range(num_classes)], dtype=torch.long, requires_grad=False, device=args.device).view(-1) # [0,0,0, 1,1,1, ..., 9,9,9] if args.init == 'real': print('initialize synthetic data from random real images') for c in range(num_classes): image_syn.data[c*args.ipc:(c+1)*args.ipc] = get_images(c, args.ipc).detach().data else: print('initialize synthetic data from random noise') ''' training ''' optimizer_img = torch.optim.SGD([image_syn, ], lr=args.lr_img, momentum=0.5) # optimizer_img for synthetic data optimizer_img.zero_grad() criterion = nn.CrossEntropyLoss().to(args.device) print('%s training begins'%get_time()) for it in range(args.Iteration+1): ''' Evaluate synthetic data ''' if it in eval_it_pool: for model_eval in model_eval_pool: print('-------------------------\nEvaluation\nmodel_train = %s, model_eval = %s, iteration = %d'%(args.model, model_eval, it)) if args.dsa: args.epoch_eval_train = 1000 args.dc_aug_param = None print('DSA augmentation strategy: \n', args.dsa_strategy) print('DSA augmentation parameters: \n', args.dsa_param.__dict__) else:
def main(): parser = argparse.ArgumentParser(description='Parameter Processing') parser.add_argument('--method', type=str, default='DC', help='DC/DSA') parser.add_argument('--dataset', type=str, default='CIFAR10', help='dataset') parser.add_argument('--model', type=str, default='ConvNet', help='model') parser.add_argument('--ipc', type=int, default=1, help='image(s) per class') parser.add_argument('--eval_mode', type=str, default='S', help='eval_mode') # S: the same to training model, M: multi architectures, W: net width, D: net depth, A: activation function, P: pooling layer, N: normalization layer, parser.add_argument('--num_exp', type=int, default=5, help='the number of experiments') parser.add_argument('--num_eval', type=int, default=20, help='the number of evaluating randomly initialized models') parser.add_argument('--epoch_eval_train', type=int, default=300, help='epochs to train a model with synthetic data') parser.add_argument('--Iteration', type=int, default=1000, help='training iterations') parser.add_argument('--lr_img', type=float, default=0.1, help='learning rate for updating synthetic images') parser.add_argument('--lr_net', type=float, default=0.01, help='learning rate for updating network parameters') parser.add_argument('--batch_real', type=int, default=256, help='batch size for real data') parser.add_argument('--batch_train', type=int, default=256, help='batch size for training networks') parser.add_argument('--init', type=str, default='noise', help='noise/real: initialize synthetic images from random noise or randomly sampled real images.') parser.add_argument('--dsa_strategy', type=str, default='None', help='differentiable Siamese augmentation strategy') parser.add_argument('--data_path', type=str, default='data', help='dataset path') parser.add_argument('--save_path', type=str, default='result', help='path to save results') parser.add_argument('--dis_metric', type=str, default='ours', help='distance metric') parser.add_argument('--drop_criterion', type=str, default='LossConverge_large', help='Criterion for data dropping') parser.add_argument('--drop_ratio', type=float, default=0.0, help='The ratio to drop (for each class)') args = parser.parse_args() args.outer_loop, args.inner_loop = get_loops(args.ipc) args.device = 'cuda' if torch.cuda.is_available() else 'cpu' args.dsa_param = ParamDiffAug() args.dsa = True if args.method == 'DSA' else False if not os.path.exists(args.data_path): os.mkdir(args.data_path) if not os.path.exists(args.save_path): os.mkdir(args.save_path) eval_it_pool = np.arange(0, args.Iteration+1, 500).tolist() if args.eval_mode == 'S' or args.eval_mode == 'SS' else [args.Iteration] # The list of iterations when we evaluate models and record results. print('eval_it_pool: ', eval_it_pool) channel, im_size, num_classes, class_names, mean, std, dst_train, dst_test, testloader = get_dataset(args.dataset, args.data_path) model_eval_pool = get_eval_pool(args.eval_mode, args.model, args.model) accs_all_exps = dict() # record performances of all experiments for key in model_eval_pool: accs_all_exps[key] = [] data_save = [] for exp in range(args.num_exp): print('\n================== Exp %d ==================\n '%exp) print('Hyper-parameters: \n', args.__dict__) print('Evaluation model pool: ', model_eval_pool) ''' organize the real dataset ''' images_all = [] labels_all = [] indices_class = [[] for c in range(num_classes)] images_all = [torch.unsqueeze(dst_train[i][0], dim=0) for i in range(len(dst_train))] labels_all = [dst_train[i][1] for i in range(len(dst_train))] for i, lab in enumerate(labels_all): indices_class[lab].append(i) images_all = torch.cat(images_all, dim=0).to(args.device) labels_all = torch.tensor(labels_all, dtype=torch.long, device=args.device) images_all, labels_all, indices_class = drop_samples( images_all, labels_all, indices_class, args.dataset, args.drop_criterion, drop_ratio=args.drop_ratio) for c in range(num_classes): print('class c = %d: %d real images'%(c, len(indices_class[c]))) def get_images(c, n): # get random n images from class c idx_shuffle = np.random.permutation(indices_class[c])[:n] return images_all[idx_shuffle] for ch in range(channel): print('real images channel %d, mean = %.4f, std = %.4f'%(ch, torch.mean(images_all[:, ch]), torch.std(images_all[:, ch]))) ''' initialize the synthetic data ''' image_syn = torch.randn(size=(num_classes*args.ipc, channel, im_size[0], im_size[1]), dtype=torch.float, requires_grad=True, device=args.device) label_syn = torch.tensor([np.ones(args.ipc)*i for i in range(num_classes)], dtype=torch.long, requires_grad=False, device=args.device).view(-1) # [0,0,0, 1,1,1, ..., 9,9,9] if args.init == 'real': print('initialize synthetic data from random real images') for c in range(num_classes): image_syn.data[c*args.ipc:(c+1)*args.ipc] = get_images(c, args.ipc).detach().data else: print('initialize synthetic data from random noise') ''' training ''' optimizer_img = torch.optim.SGD([image_syn, ], lr=args.lr_img, momentum=0.5) # optimizer_img for synthetic data optimizer_img.zero_grad() criterion = nn.CrossEntropyLoss().to(args.device) print('%s training begins'%get_time()) for it in range(args.Iteration+1): ''' Evaluate synthetic data ''' if it in eval_it_pool: for model_eval in model_eval_pool: print('-------------------------\nEvaluation\nmodel_train = %s, model_eval = %s, iteration = %d'%(args.model, model_eval, it)) if args.dsa: args.epoch_eval_train = 1000 args.dc_aug_param = None print('DSA augmentation strategy: \n', args.dsa_strategy) print('DSA augmentation parameters: \n', args.dsa_param.__dict__) else:
args.dc_aug_param = get_daparam(args.dataset, args.model, model_eval, args.ipc) # This augmentation parameter set is only for DC method. It will be muted when args.dsa is True.
5
2023-11-03 09:34:15+00:00
12k
gchada/ROAM
sim/rail_walker_interface/environment/joystick_real.py
[ { "identifier": "WalkerEnvironment", "path": "sim/rail_walker_interface/environment/env.py", "snippet": "class WalkerEnvironment:\n @property\n def robot(self) -> BaseWalker:\n pass" }, { "identifier": "JoystickEnvironment", "path": "sim/rail_walker_interface/environment/env.py"...
import gym import gym.spaces import numpy as np import copy from .env import WalkerEnvironment, JoystickEnvironment from ..robot import BaseWalker, BaseWalkerWithFootContact from ..joystick_policy import JoystickPolicy from functools import cached_property from typing import Optional, Any from collections import OrderedDict
7,316
if isinstance(self.env.robot.unwrapped(), BaseWalkerWithFootContact): ret_dict["robot/foot_forces"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32 ) ret_dict["robot/foot_forces_normalized"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32 ) ret_dict["robot/foot_forces_normalized_masked"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32 ) ret_dict["robot/foot_contacts"] = gym.spaces.Box( # should use MultiBinary but flatten() does not support having multibinary / box spaces in a Dict low=0, high=1, shape=(4,), dtype=np.float32 ) return gym.spaces.Dict(ret_dict) def extract_observation(self) -> dict[str,Any]: roll, pitch, yaw = self.env.robot.get_roll_pitch_yaw() dr, dp, dy = self.env.robot.get_3d_angular_velocity() imu = np.array([roll, pitch, dr, dp], dtype=np.float32) ret_dict = { "robot/joints_pos": self.env.robot.get_joint_qpos(), "robot/joints_vel": self.env.robot.get_joint_qvel(), "robot/imu": imu, "robot/sensors_gyro": self.env.robot.get_3d_angular_velocity(), "robot/sensors_framequat": self.env.robot.get_framequat_wijk(), "robot/torques": self.env.robot.get_joint_torques(), "robot/sensors_local_velocimeter": self.env.robot.get_3d_local_velocity(), "robot/sensors_accelerometer": self.env.robot.get_3d_acceleration_local(), } if isinstance(self.env.robot.unwrapped(), BaseWalkerWithFootContact): ret_dict["robot/foot_forces"] = self.env.robot.get_foot_force() ret_dict["robot/foot_contacts"] = self.env.robot.get_foot_contact() if hasattr(self.env.robot, "foot_contact_no_contact_threshold") and hasattr(self.env.robot, "foot_contact_has_contact_threshold"): ret_dict["robot/foot_forces_normalized"] = (ret_dict["robot/foot_forces"] - self.env.robot.foot_contact_no_contact_threshold) / (self.env.robot.foot_contact_has_contact_threshold - self.env.robot.foot_contact_no_contact_threshold) else: ret_dict["robot/foot_forces_normalized"] = ret_dict["robot/foot_forces"] masked_foot_forces = ret_dict["robot/foot_forces_normalized"].copy() masked_foot_forces[-1] = 0.0 ret_dict["robot/foot_forces_normalized_masked"] = masked_foot_forces return ret_dict class JoystickEnvImpl(gym.Env[dict[str,Any],np.ndarray], WalkerEnvironment, JoystickEnvironment): metadata = { "render_modes": [] } def __init__( self, joystick_policy : JoystickPolicy ): gym.Env.__init__(self) WalkerEnvironment.__init__(self) JoystickEnvironment.__init__(self) # ====================== Store Parameters ====================== self._joystick_policy = joystick_policy self.obs_extractor = JoystickEnvObservationExtractor(self) self.random_state = np.random.RandomState() @property def action_space(self) -> gym.spaces.Box: return gym.spaces.Box( low=self.robot.action_qpos_mins, high=self.robot.action_qpos_maxs, dtype=np.float32 ) @property def observation_space(self) -> gym.spaces.Dict: robot_space = self.obs_extractor.observation_spec real_obs_space = {} for key, space in robot_space.items(): if key.startswith("robot/") and key[len("robot/"):] in self.joystick_policy.enabled_observables: real_obs_space[key] = space if self.joystick_policy.target_observable is not None: real_obs_space["target_obs"] = self.joystick_policy.target_observable.get_observation_spec() if not self.joystick_policy.target_yaw_provider.is_target_velocity_fixed(): real_obs_space["target_vel"] = gym.spaces.Box( low = 0.0, high = np.inf, shape=(1,) ) target_custom_data_spec = self.joystick_policy.target_yaw_provider.get_target_custom_data_observable_spec() if self.joystick_policy.enable_target_custom_obs and target_custom_data_spec is not None: real_obs_space["target_custom"] = target_custom_data_spec # Enforce order real_obs_space = OrderedDict(sorted(real_obs_space.items(), key=lambda t: t[0])) obs_space = gym.spaces.Dict(real_obs_space) return obs_space @property def joystick_policy(self) -> JoystickPolicy: return self._joystick_policy def set_joystick_policy(self, joystick_policy: JoystickPolicy): self._joystick_policy = joystick_policy @property def is_resetter_policy(self) -> bool: return False @property
class JoystickEnvObservationExtractor: def __init__(self, env : "JoystickEnvImpl"): self.env = env @cached_property def observation_spec(self) -> gym.spaces.Dict: ret_dict = { "robot/joints_pos": gym.spaces.Box( low=self.env.robot.joint_qpos_mins, high=self.env.robot.joint_qpos_maxs, shape=(self.env.robot.joint_nums,), dtype=np.float32 ), "robot/joints_vel": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(self.env.robot.joint_nums,), dtype=np.float32 ), "robot/imu": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), ), "robot/sensors_gyro": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(3,), dtype=np.float32 ), "robot/sensors_framequat": gym.spaces.Box( low=-1.0, high=1.0, shape=(4,), dtype=np.float32 ), "robot/torques": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(self.env.robot.joint_nums,), dtype=np.float32 ), "robot/sensors_local_velocimeter": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(3,), dtype=np.float32 ), "robot/sensors_accelerometer": gym.spaces.Box( low=-np.inf, high=np.inf, shape=(3,), dtype=np.float32 ), } if isinstance(self.env.robot.unwrapped(), BaseWalkerWithFootContact): ret_dict["robot/foot_forces"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32 ) ret_dict["robot/foot_forces_normalized"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32 ) ret_dict["robot/foot_forces_normalized_masked"] = gym.spaces.Box( low=-np.inf, high=np.inf, shape=(4,), dtype=np.float32 ) ret_dict["robot/foot_contacts"] = gym.spaces.Box( # should use MultiBinary but flatten() does not support having multibinary / box spaces in a Dict low=0, high=1, shape=(4,), dtype=np.float32 ) return gym.spaces.Dict(ret_dict) def extract_observation(self) -> dict[str,Any]: roll, pitch, yaw = self.env.robot.get_roll_pitch_yaw() dr, dp, dy = self.env.robot.get_3d_angular_velocity() imu = np.array([roll, pitch, dr, dp], dtype=np.float32) ret_dict = { "robot/joints_pos": self.env.robot.get_joint_qpos(), "robot/joints_vel": self.env.robot.get_joint_qvel(), "robot/imu": imu, "robot/sensors_gyro": self.env.robot.get_3d_angular_velocity(), "robot/sensors_framequat": self.env.robot.get_framequat_wijk(), "robot/torques": self.env.robot.get_joint_torques(), "robot/sensors_local_velocimeter": self.env.robot.get_3d_local_velocity(), "robot/sensors_accelerometer": self.env.robot.get_3d_acceleration_local(), } if isinstance(self.env.robot.unwrapped(), BaseWalkerWithFootContact): ret_dict["robot/foot_forces"] = self.env.robot.get_foot_force() ret_dict["robot/foot_contacts"] = self.env.robot.get_foot_contact() if hasattr(self.env.robot, "foot_contact_no_contact_threshold") and hasattr(self.env.robot, "foot_contact_has_contact_threshold"): ret_dict["robot/foot_forces_normalized"] = (ret_dict["robot/foot_forces"] - self.env.robot.foot_contact_no_contact_threshold) / (self.env.robot.foot_contact_has_contact_threshold - self.env.robot.foot_contact_no_contact_threshold) else: ret_dict["robot/foot_forces_normalized"] = ret_dict["robot/foot_forces"] masked_foot_forces = ret_dict["robot/foot_forces_normalized"].copy() masked_foot_forces[-1] = 0.0 ret_dict["robot/foot_forces_normalized_masked"] = masked_foot_forces return ret_dict class JoystickEnvImpl(gym.Env[dict[str,Any],np.ndarray], WalkerEnvironment, JoystickEnvironment): metadata = { "render_modes": [] } def __init__( self, joystick_policy : JoystickPolicy ): gym.Env.__init__(self) WalkerEnvironment.__init__(self) JoystickEnvironment.__init__(self) # ====================== Store Parameters ====================== self._joystick_policy = joystick_policy self.obs_extractor = JoystickEnvObservationExtractor(self) self.random_state = np.random.RandomState() @property def action_space(self) -> gym.spaces.Box: return gym.spaces.Box( low=self.robot.action_qpos_mins, high=self.robot.action_qpos_maxs, dtype=np.float32 ) @property def observation_space(self) -> gym.spaces.Dict: robot_space = self.obs_extractor.observation_spec real_obs_space = {} for key, space in robot_space.items(): if key.startswith("robot/") and key[len("robot/"):] in self.joystick_policy.enabled_observables: real_obs_space[key] = space if self.joystick_policy.target_observable is not None: real_obs_space["target_obs"] = self.joystick_policy.target_observable.get_observation_spec() if not self.joystick_policy.target_yaw_provider.is_target_velocity_fixed(): real_obs_space["target_vel"] = gym.spaces.Box( low = 0.0, high = np.inf, shape=(1,) ) target_custom_data_spec = self.joystick_policy.target_yaw_provider.get_target_custom_data_observable_spec() if self.joystick_policy.enable_target_custom_obs and target_custom_data_spec is not None: real_obs_space["target_custom"] = target_custom_data_spec # Enforce order real_obs_space = OrderedDict(sorted(real_obs_space.items(), key=lambda t: t[0])) obs_space = gym.spaces.Dict(real_obs_space) return obs_space @property def joystick_policy(self) -> JoystickPolicy: return self._joystick_policy def set_joystick_policy(self, joystick_policy: JoystickPolicy): self._joystick_policy = joystick_policy @property def is_resetter_policy(self) -> bool: return False @property
def robot(self) -> BaseWalker:
2
2023-11-02 23:21:38+00:00
12k
UMass-Foundation-Model/genome
engine/viper/base_models/xvlm/xvlm.py
[ { "identifier": "VisionTransformer", "path": "engine/viper/base_models/xvlm/vit.py", "snippet": "class VisionTransformer(nn.Module):\n \"\"\" Vision Transformer\n A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` -\n https://arxiv.org/abs/2010...
import os import torch import torch.nn as nn import torch.nn.functional as F import torch.distributed as dist import json from functools import partial from engine.viper.base_models.xvlm.vit import VisionTransformer, interpolate_pos_embed from engine.viper.base_models.xvlm.swin_transformer import SwinTransformer, interpolate_relative_pos_embed from engine.viper.base_models.xvlm.xbert import BertConfig, BertForMaskedLM, BertModel
8,466
# Multi-Grained Vision Language Pre-Training: Aligning Texts with Visual Concepts (https://arxiv.org/abs/2111.08276) # Github: https://github.com/zengyan-97/X-VLM # Copyright (c) 2022, ByteDance Inc. # All rights reserved. def read_json(rpath): with open(rpath, 'r') as f: return json.load(f) class AllGather(torch.autograd.Function): """An autograd function that performs allgather on a tensor.""" @staticmethod def forward(ctx, tensor, rank, world_size): output = [torch.empty_like(tensor) for _ in range(world_size)] dist.all_gather(output, tensor) ctx.rank = rank ctx.batch_size = tensor.shape[0] return torch.cat(output, 0) @staticmethod def backward(ctx, grad_output): return ( grad_output[ctx.batch_size * ctx.rank: ctx.batch_size * (ctx.rank + 1)], None, None ) allgather = AllGather.apply def build_vision_encoder(vision_config, load_params=False): """ Args: load_params: False when building fine-tuning models """ vision_width = vision_config['vision_width'] vision_encoder = SwinTransformer(img_size=vision_config['image_res'], patch_size=4, in_chans=3, embed_dim=vision_config['embed_dim'], depths=vision_config['depths'], num_heads=vision_config['num_heads'], window_size=vision_config['window_size'], mlp_ratio=4., qkv_bias=True, drop_rate=0.0, drop_path_rate=0.1, ape=False, patch_norm=True, use_checkpoint=False) if load_params: # download from https://github.com/microsoft/Swin-Transformer state_dict = torch.load(vision_config['ckpt'], map_location="cpu")['model'] for k in list(state_dict.keys()): if 'relative_position_bias_table' in k: dst_num_pos = (2 * vision_config['window_size'] - 1) ** 2 state_dict[k] = interpolate_relative_pos_embed(state_dict[k], dst_num_pos, param_name=k) elif ('relative_position_index' in k) or ('attn_mask' in k): del state_dict[k] if load_params: print("### Load ViT: ", flush=True) msg = vision_encoder.load_state_dict(state_dict, strict=False) print("missing_keys: ", msg.missing_keys) print("unexpected_keys: ", msg.unexpected_keys) return vision_encoder, vision_width def build_text_encoder(config, vision_width, load_text_params=False, use_mlm_loss=False, config_text=None): init_params = [] # train from scratch with larger lr config_text = BertConfig.from_json_file('engine/viper/base_models/xvlm/config_bert.json') config_text.encoder_width = vision_width if use_mlm_loss: # for pre-training, load_text_params by default (otherwise notimplemented) assert load_text_params is True if ('accelerator' in config.keys()) and (config['accelerator']['FP16_OPT_LEVEL'] != 'O0'): config_text.fp16 = True # will use some operations to avoid gradient overflow
# Multi-Grained Vision Language Pre-Training: Aligning Texts with Visual Concepts (https://arxiv.org/abs/2111.08276) # Github: https://github.com/zengyan-97/X-VLM # Copyright (c) 2022, ByteDance Inc. # All rights reserved. def read_json(rpath): with open(rpath, 'r') as f: return json.load(f) class AllGather(torch.autograd.Function): """An autograd function that performs allgather on a tensor.""" @staticmethod def forward(ctx, tensor, rank, world_size): output = [torch.empty_like(tensor) for _ in range(world_size)] dist.all_gather(output, tensor) ctx.rank = rank ctx.batch_size = tensor.shape[0] return torch.cat(output, 0) @staticmethod def backward(ctx, grad_output): return ( grad_output[ctx.batch_size * ctx.rank: ctx.batch_size * (ctx.rank + 1)], None, None ) allgather = AllGather.apply def build_vision_encoder(vision_config, load_params=False): """ Args: load_params: False when building fine-tuning models """ vision_width = vision_config['vision_width'] vision_encoder = SwinTransformer(img_size=vision_config['image_res'], patch_size=4, in_chans=3, embed_dim=vision_config['embed_dim'], depths=vision_config['depths'], num_heads=vision_config['num_heads'], window_size=vision_config['window_size'], mlp_ratio=4., qkv_bias=True, drop_rate=0.0, drop_path_rate=0.1, ape=False, patch_norm=True, use_checkpoint=False) if load_params: # download from https://github.com/microsoft/Swin-Transformer state_dict = torch.load(vision_config['ckpt'], map_location="cpu")['model'] for k in list(state_dict.keys()): if 'relative_position_bias_table' in k: dst_num_pos = (2 * vision_config['window_size'] - 1) ** 2 state_dict[k] = interpolate_relative_pos_embed(state_dict[k], dst_num_pos, param_name=k) elif ('relative_position_index' in k) or ('attn_mask' in k): del state_dict[k] if load_params: print("### Load ViT: ", flush=True) msg = vision_encoder.load_state_dict(state_dict, strict=False) print("missing_keys: ", msg.missing_keys) print("unexpected_keys: ", msg.unexpected_keys) return vision_encoder, vision_width def build_text_encoder(config, vision_width, load_text_params=False, use_mlm_loss=False, config_text=None): init_params = [] # train from scratch with larger lr config_text = BertConfig.from_json_file('engine/viper/base_models/xvlm/config_bert.json') config_text.encoder_width = vision_width if use_mlm_loss: # for pre-training, load_text_params by default (otherwise notimplemented) assert load_text_params is True if ('accelerator' in config.keys()) and (config['accelerator']['FP16_OPT_LEVEL'] != 'O0'): config_text.fp16 = True # will use some operations to avoid gradient overflow
text_encoder, msg = BertForMaskedLM.from_pretrained(config['text_encoder'], config=config_text,
4
2023-11-01 16:39:33+00:00
12k
ml4bio/RhoFold
rhofold/model/structure_module.py
[ { "identifier": "Linear", "path": "rhofold/model/primitives.py", "snippet": "class Linear(nn.Linear):\n \"\"\"\n A Linear layer with built-in nonstandard initializations. Called just\n like torch.nn.Linear.\n\n Implements the initializers in 1.11.4, plus some additional ones found\n in th...
import math import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Sequence from rhofold.model.primitives import Linear, LayerNorm from rhofold.utils.rigid_utils import Rigid from rhofold.utils.tensor_utils import ( dict_multimap, permute_final_dims, flatten_final_dims, ) from einops import rearrange from rhofold.utils.alphabet import RNAAlphabet from rhofold.utils.converter import RNAConverter
9,008
# 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 RefineNet(nn.Module): """""" def __init__(self, dim = 64, is_pos_emb = True, n_layer = 4, enable = True, **kwargs): """Constructor function.""" super().__init__() self.is_pos_emb = is_pos_emb
# 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 RefineNet(nn.Module): """""" def __init__(self, dim = 64, is_pos_emb = True, n_layer = 4, enable = True, **kwargs): """Constructor function.""" super().__init__() self.is_pos_emb = is_pos_emb
self.alphabet = RNAAlphabet.from_architecture('RNA')
6
2023-11-01 10:29:08+00:00
12k
ziqi-zhang/TAOISM
python/sgx_net.py
[ { "identifier": "SecretInputLayer", "path": "python/layers/input.py", "snippet": "class SecretInputLayer(SecretNonlinearLayer):\n shape = None\n\n def __init__(\n self, sid, LayerName, input_shape, EnclaveMode, link_prev=True, link_next=True, \n manually_register_prev=False, manually...
import os import torch import torch.nn.functional as F import torch.distributed as dist from itertools import product from collections import defaultdict, namedtuple from pdb import set_trace as st from time import time from python.layers.input import SecretInputLayer from python.layers.output import SecretOutputLayer from python.utils.basic_utils import str_hash from python.enclave_interfaces import GlobalTensor from python.utils.timer_utils import NamedTimerInstance, NetworkNamedTimerInstance from python.common_torch import SecretConfig, mod_move_down, union_dicts, \ get_random_uniform, calc_shape_conv2d_weight, GlobalCppExtension from python.utils.torch_utils import compare_expected_actual, torch_sync from python.tensor_loader import TensorLoader from python.stateless_logger import StatelessLogger
7,631
def classifier_output(self): with NamedTimerInstance(f"S{self.sid}: {self.nn_name} classifier_output"): self.forward() if self.sid == 2: return # layers: input_layer, ..., fc_layer, output_layer last_fc = self.layers[-2] last_fc.transfer_enclave_to_cpu("output") outputs = last_fc.get_cpu("output") _, predicted = torch.max(outputs.data, 1) return predicted def get_loss(self): return self.layers[-1].get_loss() def forward_with_time(self): def run_forward(layer): layer.forward() t0 = time() with NetworkNamedTimerInstance(f"S{self.sid}: {self.nn_name} Forward"): self.execute_for_each_layer(run_forward) t1 = time() # time in ms elapse_time = (t1 - t0) * (10 ** 3) return elapse_time def forward(self): def run_forward(layer): layer.forward() with NetworkNamedTimerInstance(f"S{self.sid}: {self.nn_name} Forward"): self.execute_for_each_layer(run_forward) def backward(self): def run_backward(layer): layer.backward() with NamedTimerInstance(f"S{self.sid}: {self.nn_name} Backward"): self.execute_for_each_layer(run_backward, reverse=True) def plain_forward(self): with NetworkNamedTimerInstance(f"S{self.sid}: {self.nn_name} PlainForward"): self.execute_for_each_layer(lambda x: x.plain_forward()) def plain_backward(self): with NetworkNamedTimerInstance(f"S{self.sid}: {self.nn_name} PlainBackward"): self.execute_for_each_layer(lambda x: x.plain_backward(), reverse=True) def show_plain_error(self): self.execute_for_each_layer(lambda x: x.show_plain_error()) # Take the registered learnable parameters list in layers and update them # It may need take extra storage # And execution depends on where the tensors are stored # https://pytorch.org/docs/stable/optim.html#torch.optim.SGD class SgdOptimizer(TensorLoader): def __init__(self, sid): super().__init__() self.sid = sid self.learning_rate = 0.05 self.momentum = 0.9 self.weight_decay = 5e-4 self.momentum_init_flags = defaultdict(lambda: False) self.ideal_momentum_buf = {} self.lr_gamma = 0.5 self.lr_step = 30 self.step_counter = 0 self.layers = None def set_layers(self, layers): self.layers = layers def generate_tensor_name_list(self, force=False): # Run if forced or self.tensor_name_list is not generated if not force and self.tensor_name_list: return if self.sid == 2: return self.tensor_name_list = [] for layer in self.layers: for (DerName, ParamName, shape) in layer.LearnableParamsList: self.tensor_name_list.append((ParamName + "Momentum", shape, None)) def update_params(self, test_with_ideal=False): if self.sid == 2: return for layer in self.layers: self.update_params_in_layer(layer, test_with_ideal=test_with_ideal) def update_params_in_layer(self, layer, test_with_ideal=False): # ref: https://github.com/pytorch/pytorch/blob/master/torch/optim/sgd.py if layer.LearnableParamsList is None: return task_ids = [] for (der_name, param_name, shape) in layer.LearnableParamsList: momentum_name = param_name + "Momentum" global_momentum_name = layer.name_modifier(momentum_name) if layer.StoreInEnclave: if test_with_ideal: ideal_p, ideal_momentum = self.ideal_update_params_with_name(layer, der_name, param_name, shape) first_momentum = not self.momentum_init_flags[global_momentum_name] if first_momentum: # print("FIRST MOMENTUM") self.momentum_init_flags[global_momentum_name] = True layer.init_enclave_tensor(momentum_name, shape) task_id = layer.sgd_update(param_name=param_name, grad_name=der_name, momentum_name=momentum_name, lr=self.learning_rate, momentum=self.momentum, weight_decay=self.weight_decay, first_momentum=first_momentum, is_async=True) if test_with_ideal: while not self.get_task_status(task_id): pass layer.generate_cpu_tensor(momentum_name, shape) layer.transfer_enclave_to_cpu(momentum_name) layer.transfer_enclave_to_cpu(param_name)
#!/usr/bin/env python from __future__ import print_function torch.backends.cudnn.deterministic = True LearnableParamTuple = namedtuple('LearnableParam', ('dw_name', 'w_name', 'shape')) def conv2d_op(w, x, is_div=True): padding = 1 batch_size, in_chan, img_hw, _ = x.size() out_chan, _, fil_hw, __ = w.size() y_shape = [batch_size, out_chan, img_hw, img_hw] dtype = x.dtype device = x.device is_cpu = True if device == torch.device("cpu") else False def base_conv2d(sub_x, sub_w): return F.conv2d(sub_x, sub_w, padding=padding) if is_cpu or (is_div is False): return base_conv2d(x, w) def sum_of_div(best_shape): best_batch_size, best_in_chan, best_out_chan = best_shape y = torch.zeros(y_shape, device=device, dtype=dtype) for idx_batch_size, idx_in_chan, idx_out_chan in product(range(batch_size // best_batch_size), range(in_chan // best_in_chan), range(out_chan // best_out_chan)): start_batch_size, end_batch_size = idx_batch_size * best_batch_size, (idx_batch_size + 1) * best_batch_size start_in_chan, end_in_chan = idx_in_chan * best_in_chan, (idx_in_chan + 1) * best_in_chan start_out_chan, end_out_chan = idx_out_chan * best_out_chan, (idx_out_chan + 1) * best_out_chan y[start_batch_size:end_batch_size, start_out_chan:end_out_chan, :, :] += \ base_conv2d(x[start_batch_size:end_batch_size, start_in_chan:end_in_chan, :, :], w[start_out_chan:end_out_chan, start_in_chan:end_in_chan, :, :]) return y shapes_v100 = { (1024, 512, 512, 2): (1024, 512, 128), (1024, 512, 512, 4): (1024, 512, 128), (1024, 256, 512, 4): (1024, 128, 128), (1024, 256, 256, 8): (1024, 64, 128), (1024, 128, 256, 8): (1024, 64, 128), (512, 512, 512, 2): (512, 512, 128), (512, 512, 512, 4): (256, 256, 128), (512, 256, 512, 4): (256, 256, 128), (512, 256, 256, 8): (512, 128, 128), (512, 128, 256, 8): (512, 128, 128), } tunnable_shape = (batch_size, in_chan, out_chan, img_hw) if is_div and tunnable_shape in shapes_v100: return sum_of_div(shapes_v100[tunnable_shape]) else: return base_conv2d(x, w) def conv2d_input_grad_op(w, dy): return F.conv_transpose2d(dy, w, padding=1) def conv2d_weight_grad_op(dy, x, is_div=True): batch_size, in_chan, img_hw, _ = x.size() _, out_chan, __, ___ = dy.size() w_shape = calc_shape_conv2d_weight(dy, x) dtype = x.dtype device = x.device is_cpu = True if device == torch.device("cpu") else False if is_cpu: return torch.transpose(F.conv2d(torch.transpose(x, 0, 1), torch.transpose(dy, 0, 1), padding=1), 0, 1).contiguous() def base_conv2d_weight_grad_op(sub_dy, sub_x): sub_w_shape = calc_shape_conv2d_weight(sub_dy, sub_x) return GlobalCppExtension.get_conv2d_cudnn().backward(sub_w_shape, sub_dy, sub_x, (1, 1), (1, 1), (1, 1), 1, 0, 0) if is_div is False: return base_conv2d_weight_grad_op(dy, x) def sum_of_div(best_shape): # print("running conv2d weight div") best_batch_size, best_in_chan, best_out_chan = best_shape dw = torch.zeros(w_shape, device=device, dtype=dtype) for idx_batch_size, idx_in_chan, idx_out_chan in product(range(batch_size // best_batch_size), range(in_chan // best_in_chan), range(out_chan // best_out_chan)): start_batch_size, end_batch_size = idx_batch_size * best_batch_size, (idx_batch_size + 1) * best_batch_size start_in_chan, end_in_chan = idx_in_chan * best_in_chan, (idx_in_chan + 1) * best_in_chan start_out_chan, end_out_chan = idx_out_chan * best_out_chan, (idx_out_chan + 1) * best_out_chan dw[start_out_chan:end_out_chan, start_in_chan:end_in_chan, :, :] += \ base_conv2d_weight_grad_op(dy[start_batch_size:end_batch_size, start_out_chan:end_out_chan, :, :], x[start_batch_size:end_batch_size, start_in_chan:end_in_chan, :, :]) return dw shapes_v100 = { (1024, 512, 512, 2): (1024, 512, 128), (1024, 512, 512, 4): (1024, 512, 128), (1024, 256, 512, 4): (1024, 128, 128), (1024, 128, 256, 8): (1024, 128, 128), (512, 512, 512, 2): (512, 512, 128), (512, 512, 512, 4): (512, 512, 128), (512, 256, 512, 4): (512, 128, 128), (512, 128, 256, 8): (128, 128, 256), } tunnable_shape = (batch_size, in_chan, out_chan, img_hw) if is_div and tunnable_shape in shapes_v100: return sum_of_div(shapes_v100[tunnable_shape]) else: return base_conv2d_weight_grad_op(dy, x) def matmul_op(w, x): return torch.mm(x, w.t()) def matmul_input_grad_op(w, dy): return torch.mm(dy, w) def matmul_weight_grad_op(dy, x): return torch.mm(dy.t(), x) def set_tensor_name_maybe_quantized(name, quantized): return name + ("Q" if quantized else "") # target_op = conv2d_op # idealC = ModOnCpu(target_op(AQ.type(torch.double), BQ.type(torch.double))).type(SecretConfig.dtypeForCpuOp) # Forward # A: Weight # B: Input # A: Weight # B: dy InputGradRemap = { "Af": "Af", "AQ": "AQ", "A0": "A0", "A1": "A1", "Bf": "DerCf", "BQ": "DerCQ", "B0": "DerC0", "B1": "DerC1", "E": "EForDerB", "F": "FForDerB", "C0": "C0ForDerB", "C1": "C1ForDerB", "CQ": "CQForDerB", "Cf": "CfForDerB", "Z": "ZForDerB", } # A: dy # B: InputQ WeightGradRemap = { "Af": "DerCf", "AQ": "DerCQ", "A0": "DerC0", "A1": "DerC1", "Bf": "Bf", "BQ": "BQ", "B0": "B0", "B1": "B1", "E": "EForDerA", "F": "FForDerA", "C0": "C0ForDerA", "C1": "C1ForDerA", "CQ": "CQForDerA", "Cf": "CfForDerA", "Z": "ZForDerA", } def secret_op_class_factory(sid, target_op_name): all_target_op = {"Matmul": matmul_op, "MatmulInputGrad": matmul_input_grad_op, "MatmulWeightGrad": matmul_weight_grad_op, "Conv2d": conv2d_op, "Conv2dInputGrad": conv2d_input_grad_op, "Conv2dWeightGrad": conv2d_weight_grad_op} all_sid_class = {0: SecretBaseS0, 1: SecretBaseS1, 2: SecretBaseS2} target_op_func = all_target_op[target_op_name] sid_class = all_sid_class[sid] class_name = "Secret%sS%d" % (target_op_name, sid) def __init__(self, name): sid_class.__init__(self, name) # noinspection PyUnusedLocal def target_op(self, a, b): return target_op_func(a, b) new_class = type(class_name, (sid_class,), {"__init__": __init__, "target_op": target_op}) return new_class class SecretNeuralNetwork(TensorLoader): nn_name = None layers = None def __init__(self, sid, nn_name): super().__init__() self.sid = sid self.init(start_enclave=False) self.nn_name = nn_name def set_layers(self, layers): self.layers = layers if not isinstance(self.layers[0], SecretInputLayer): raise ValueError("The first layer has to be input layer") if not isinstance(self.layers[-1], SecretOutputLayer): raise ValueError("The last layer has to be output layer") for i in range(len(self.layers) - 1): PrevLayer = self.layers[i] NextLayer = self.layers[i + 1] if not PrevLayer.manually_register_next: PrevLayer.register_next_layer(NextLayer) if not NextLayer.manually_register_prev: NextLayer.register_prev_layer(PrevLayer) for layer in self.layers: # print(f"Init_shape/link layer {layer.LayerName}") layer.set_eid(self.get_eid()) layer.init_shape() # if layer.LayerName in ["Layer1.0.weighted_add", "Layer1.0.proxies.0.bn"]: # st() layer.link_tensors() # print(layer.LayerName) # layer.print_tensor_link_relation() # if layer.LayerName in ["Layer1.0.weighted_add", "Layer1.0.proxies.0.bn"]: # st() for idx, layer in enumerate(self.layers): # print(f"Init layer {layer.LayerName}") # if layer.LayerName == "Layer1.0.main.relu2": # st() layer.init(start_enclave=False) # if idx > 3: # print(layer.LayerName, self.layers[4].get_cpu("input").shape, self.layers[4].PrevLayer.LayerName) def execute_for_each_layer(self, func, reverse=False): layers = self.layers[::-1] if reverse else self.layers for layer in layers: # print(f"SID: {self.sid} {layer.LayerName}, {func}") if self.sid == 2 and layer.IsDummyForS2: continue # print("Processing ", layer.LayerName) func(layer) # st() def classifier_output(self): with NamedTimerInstance(f"S{self.sid}: {self.nn_name} classifier_output"): self.forward() if self.sid == 2: return # layers: input_layer, ..., fc_layer, output_layer last_fc = self.layers[-2] last_fc.transfer_enclave_to_cpu("output") outputs = last_fc.get_cpu("output") _, predicted = torch.max(outputs.data, 1) return predicted def get_loss(self): return self.layers[-1].get_loss() def forward_with_time(self): def run_forward(layer): layer.forward() t0 = time() with NetworkNamedTimerInstance(f"S{self.sid}: {self.nn_name} Forward"): self.execute_for_each_layer(run_forward) t1 = time() # time in ms elapse_time = (t1 - t0) * (10 ** 3) return elapse_time def forward(self): def run_forward(layer): layer.forward() with NetworkNamedTimerInstance(f"S{self.sid}: {self.nn_name} Forward"): self.execute_for_each_layer(run_forward) def backward(self): def run_backward(layer): layer.backward() with NamedTimerInstance(f"S{self.sid}: {self.nn_name} Backward"): self.execute_for_each_layer(run_backward, reverse=True) def plain_forward(self): with NetworkNamedTimerInstance(f"S{self.sid}: {self.nn_name} PlainForward"): self.execute_for_each_layer(lambda x: x.plain_forward()) def plain_backward(self): with NetworkNamedTimerInstance(f"S{self.sid}: {self.nn_name} PlainBackward"): self.execute_for_each_layer(lambda x: x.plain_backward(), reverse=True) def show_plain_error(self): self.execute_for_each_layer(lambda x: x.show_plain_error()) # Take the registered learnable parameters list in layers and update them # It may need take extra storage # And execution depends on where the tensors are stored # https://pytorch.org/docs/stable/optim.html#torch.optim.SGD class SgdOptimizer(TensorLoader): def __init__(self, sid): super().__init__() self.sid = sid self.learning_rate = 0.05 self.momentum = 0.9 self.weight_decay = 5e-4 self.momentum_init_flags = defaultdict(lambda: False) self.ideal_momentum_buf = {} self.lr_gamma = 0.5 self.lr_step = 30 self.step_counter = 0 self.layers = None def set_layers(self, layers): self.layers = layers def generate_tensor_name_list(self, force=False): # Run if forced or self.tensor_name_list is not generated if not force and self.tensor_name_list: return if self.sid == 2: return self.tensor_name_list = [] for layer in self.layers: for (DerName, ParamName, shape) in layer.LearnableParamsList: self.tensor_name_list.append((ParamName + "Momentum", shape, None)) def update_params(self, test_with_ideal=False): if self.sid == 2: return for layer in self.layers: self.update_params_in_layer(layer, test_with_ideal=test_with_ideal) def update_params_in_layer(self, layer, test_with_ideal=False): # ref: https://github.com/pytorch/pytorch/blob/master/torch/optim/sgd.py if layer.LearnableParamsList is None: return task_ids = [] for (der_name, param_name, shape) in layer.LearnableParamsList: momentum_name = param_name + "Momentum" global_momentum_name = layer.name_modifier(momentum_name) if layer.StoreInEnclave: if test_with_ideal: ideal_p, ideal_momentum = self.ideal_update_params_with_name(layer, der_name, param_name, shape) first_momentum = not self.momentum_init_flags[global_momentum_name] if first_momentum: # print("FIRST MOMENTUM") self.momentum_init_flags[global_momentum_name] = True layer.init_enclave_tensor(momentum_name, shape) task_id = layer.sgd_update(param_name=param_name, grad_name=der_name, momentum_name=momentum_name, lr=self.learning_rate, momentum=self.momentum, weight_decay=self.weight_decay, first_momentum=first_momentum, is_async=True) if test_with_ideal: while not self.get_task_status(task_id): pass layer.generate_cpu_tensor(momentum_name, shape) layer.transfer_enclave_to_cpu(momentum_name) layer.transfer_enclave_to_cpu(param_name)
param_err = compare_expected_actual(ideal_p, layer.get_cpu(param_name), get_relative=True)
7
2023-11-01 10:37:37+00:00
12k
NVlabs/M2T2
m2t2/m2t2.py
[ { "identifier": "ActionDecoder", "path": "m2t2/action_decoder.py", "snippet": "class ActionDecoder(torch.nn.Module):\n def __init__(\n self, mask_dim, use_embed, embed_dim, max_num_pred, num_params,\n hidden_dim, num_layers, activation, offset_bins\n ):\n super(ActionDecoder, ...
import torch import torch.nn as nn from m2t2.action_decoder import ActionDecoder, infer_placements from m2t2.contact_decoder import ContactDecoder from m2t2.criterion import SetCriterion, GraspCriterion, PlaceCriterion from m2t2.matcher import HungarianMatcher from m2t2.pointnet2 import PointNet2MSG, PointNet2MSGCls
9,412
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # # Author: Wentao Yuan ''' Top-level M2T2 network. ''' class M2T2(nn.Module): def __init__( self, backbone: nn.Module, transformer: nn.Module, object_encoder: nn.Module = None, grasp_mlp: nn.Module = None, set_criterion: nn.Module = None, grasp_criterion: nn.Module = None, place_criterion: nn.Module = None ): super(M2T2, self).__init__() self.backbone = backbone self.object_encoder = object_encoder self.transformer = transformer self.grasp_mlp = grasp_mlp self.set_criterion = set_criterion self.grasp_criterion = grasp_criterion self.place_criterion = place_criterion @classmethod def from_config(cls, cfg): args = {} args['backbone'] = PointNet2MSG.from_config(cfg.scene_encoder) channels = args['backbone'].out_channels obj_channels = None if cfg.contact_decoder.num_place_queries > 0: args['object_encoder'] = PointNet2MSGCls.from_config( cfg.object_encoder ) obj_channels = args['object_encoder'].out_channels
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # # Author: Wentao Yuan ''' Top-level M2T2 network. ''' class M2T2(nn.Module): def __init__( self, backbone: nn.Module, transformer: nn.Module, object_encoder: nn.Module = None, grasp_mlp: nn.Module = None, set_criterion: nn.Module = None, grasp_criterion: nn.Module = None, place_criterion: nn.Module = None ): super(M2T2, self).__init__() self.backbone = backbone self.object_encoder = object_encoder self.transformer = transformer self.grasp_mlp = grasp_mlp self.set_criterion = set_criterion self.grasp_criterion = grasp_criterion self.place_criterion = place_criterion @classmethod def from_config(cls, cfg): args = {} args['backbone'] = PointNet2MSG.from_config(cfg.scene_encoder) channels = args['backbone'].out_channels obj_channels = None if cfg.contact_decoder.num_place_queries > 0: args['object_encoder'] = PointNet2MSGCls.from_config( cfg.object_encoder ) obj_channels = args['object_encoder'].out_channels
args['place_criterion'] = PlaceCriterion.from_config(
5
2023-11-03 22:32:05+00:00
12k
Codra-Ingenierie-Informatique/DataLab
cdl/core/gui/processor/base.py
[ { "identifier": "env", "path": "cdl/env.py", "snippet": "DEBUG = os.environ.get(\"DEBUG\", \"\").lower() in (\"1\", \"true\")\n QUIET = \"quiet\"\n NORMAL = \"normal\"\n DEBUG = \"debug\"\n UNATTENDED_ARG = \"unattended\"\n VERBOSE_ARG = \"verbose\"\n SCREENSHOT_ARG = \"screenshot\"\n ...
import abc import multiprocessing import time import warnings import guidata.dataset as gds import numpy as np from collections.abc import Callable from multiprocessing import Pool from typing import TYPE_CHECKING, Any, Union from guidata.configtools import get_icon from guidata.dataset import update_dataset from guidata.qthelpers import exec_dialog from guidata.widgets.arrayeditor import ArrayEditor from qtpy import QtCore as QC from qtpy import QtWidgets as QW from cdl import env from cdl.algorithms.datatypes import is_complex_dtype, is_integer_dtype from cdl.config import Conf, _ from cdl.core.computation.base import ROIDataParam from cdl.core.gui.processor.catcher import CompOut, wng_err_func from cdl.core.model.base import ResultShape, ShapeTypes from cdl.utils.qthelpers import create_progress_bar, qt_try_except from cdl.widgets.warningerror import show_warning_error from multiprocessing.pool import AsyncResult from plotpy.plot import PlotWidget from cdl.core.computation.base import ( ClipParam, GaussianParam, MovingAverageParam, MovingMedianParam, ThresholdParam, ) from cdl.core.gui.panel.image import ImagePanel from cdl.core.gui.panel.signal import SignalPanel from cdl.core.model.image import ImageObj from cdl.core.model.signal import SignalObj
8,137
if TYPE_CHECKING: # pragma: no cover Obj = Union[SignalObj, ImageObj] # Enable multiprocessing support for Windows, with frozen executable (e.g. PyInstaller) multiprocessing.freeze_support() COMPUTATION_TIP = _( "DataLab relies on various libraries to perform the computation. During the " "computation, errors may occur because of the data (e.g. division by zero, " "unexpected data type, etc.) or because of the libraries (e.g. memory error, " "etc.). If you encounter an error, before reporting it, please ensure that " "the computation is correct, by checking the data and the parameters." ) POOL: Pool = None class Worker: """Multiprocessing worker, to run long-running tasks in a separate process""" def __init__(self) -> None: self.asyncresult: AsyncResult = None self.result: Any = None @staticmethod def create_pool() -> None: """Create multiprocessing pool""" global POOL # pylint: disable=global-statement # Create a pool with one process POOL = Pool(processes=1) # pylint: disable=not-callable,consider-using-with @staticmethod def terminate_pool(wait: bool = False) -> None: """Terminate multiprocessing pool. Args: wait (bool | None): wait for all tasks to finish. Defaults to False. """ global POOL # pylint: disable=global-statement if POOL is not None: if wait: # Close the pool properly (wait for all tasks to finish) POOL.close() else: # Terminate the pool and stop the timer POOL.terminate() POOL.join() POOL = None def restart_pool(self) -> None: """Terminate and recreate the pool""" # Terminate the process and stop the timer self.terminate_pool(wait=False) # Recreate the pool for the next computation self.create_pool() def run(self, func: Callable, args: tuple[Any]) -> None: """Run computation. Args: func (Callable): function to run args (tuple[Any]): arguments """ global POOL # pylint: disable=global-statement,global-variable-not-assigned assert POOL is not None self.asyncresult = POOL.apply_async(wng_err_func, (func, args)) def close(self) -> None: """Close worker: close pool properly and wait for all tasks to finish""" # Close multiprocessing Pool properly, but only if no computation is running, # to avoid blocking the GUI at exit (so, when wait=True, we wait for the # task to finish before closing the pool but there is actually no task running, # so the pool is closed immediately but *properly*) self.terminate_pool(wait=self.asyncresult is None) def is_computation_finished(self) -> bool: """Return True if computation is finished. Returns: bool: True if computation is finished """ return self.asyncresult.ready() def get_result(self) -> CompOut: """Return computation result. Returns: CompOut: computation result """ self.result = self.asyncresult.get() self.asyncresult = None return self.result class BaseProcessor(QC.QObject): """Object handling data processing: operations, processing, computing. Args: panel (SignalPanel | ImagePanel): panel plotwidget (CurveWidget | ImageWidget): plot widget """ SIG_ADD_SHAPE = QC.Signal(str) EDIT_ROI_PARAMS = False PARAM_DEFAULTS: dict[str, gds.DataSet] = {} def __init__(self, panel: SignalPanel | ImagePanel, plotwidget: PlotWidget): super().__init__() self.panel = panel self.plotwidget = plotwidget self.worker: Worker | None = None
# -*- coding: utf-8 -*- # # Licensed under the terms of the BSD 3-Clause # (see cdl/LICENSE for details) """ DataLab Base Processor GUI module --------------------------------- This module defines the base class for data processing GUIs. """ # pylint: disable=invalid-name # Allows short reference names like x, y, ... from __future__ import annotations if TYPE_CHECKING: # pragma: no cover Obj = Union[SignalObj, ImageObj] # Enable multiprocessing support for Windows, with frozen executable (e.g. PyInstaller) multiprocessing.freeze_support() COMPUTATION_TIP = _( "DataLab relies on various libraries to perform the computation. During the " "computation, errors may occur because of the data (e.g. division by zero, " "unexpected data type, etc.) or because of the libraries (e.g. memory error, " "etc.). If you encounter an error, before reporting it, please ensure that " "the computation is correct, by checking the data and the parameters." ) POOL: Pool = None class Worker: """Multiprocessing worker, to run long-running tasks in a separate process""" def __init__(self) -> None: self.asyncresult: AsyncResult = None self.result: Any = None @staticmethod def create_pool() -> None: """Create multiprocessing pool""" global POOL # pylint: disable=global-statement # Create a pool with one process POOL = Pool(processes=1) # pylint: disable=not-callable,consider-using-with @staticmethod def terminate_pool(wait: bool = False) -> None: """Terminate multiprocessing pool. Args: wait (bool | None): wait for all tasks to finish. Defaults to False. """ global POOL # pylint: disable=global-statement if POOL is not None: if wait: # Close the pool properly (wait for all tasks to finish) POOL.close() else: # Terminate the pool and stop the timer POOL.terminate() POOL.join() POOL = None def restart_pool(self) -> None: """Terminate and recreate the pool""" # Terminate the process and stop the timer self.terminate_pool(wait=False) # Recreate the pool for the next computation self.create_pool() def run(self, func: Callable, args: tuple[Any]) -> None: """Run computation. Args: func (Callable): function to run args (tuple[Any]): arguments """ global POOL # pylint: disable=global-statement,global-variable-not-assigned assert POOL is not None self.asyncresult = POOL.apply_async(wng_err_func, (func, args)) def close(self) -> None: """Close worker: close pool properly and wait for all tasks to finish""" # Close multiprocessing Pool properly, but only if no computation is running, # to avoid blocking the GUI at exit (so, when wait=True, we wait for the # task to finish before closing the pool but there is actually no task running, # so the pool is closed immediately but *properly*) self.terminate_pool(wait=self.asyncresult is None) def is_computation_finished(self) -> bool: """Return True if computation is finished. Returns: bool: True if computation is finished """ return self.asyncresult.ready() def get_result(self) -> CompOut: """Return computation result. Returns: CompOut: computation result """ self.result = self.asyncresult.get() self.asyncresult = None return self.result class BaseProcessor(QC.QObject): """Object handling data processing: operations, processing, computing. Args: panel (SignalPanel | ImagePanel): panel plotwidget (CurveWidget | ImageWidget): plot widget """ SIG_ADD_SHAPE = QC.Signal(str) EDIT_ROI_PARAMS = False PARAM_DEFAULTS: dict[str, gds.DataSet] = {} def __init__(self, panel: SignalPanel | ImagePanel, plotwidget: PlotWidget): super().__init__() self.panel = panel self.plotwidget = plotwidget self.worker: Worker | None = None
self.set_process_isolation_enabled(Conf.main.process_isolation_enabled.get())
3
2023-11-09 16:56:03+00:00
12k
choderalab/chiron
chiron/tests/test_pairs.py
[ { "identifier": "NeighborListNsqrd", "path": "chiron/neighbors.py", "snippet": "class NeighborListNsqrd(PairsBase):\n \"\"\"\n N^2 neighborlist implementation that returns the particle pair ids, displacement vectors, and distances.\n\n Parameters\n ----------\n space: Space\n Class...
import jax.numpy as jnp import pytest from chiron.neighbors import ( NeighborListNsqrd, PairList, OrthogonalPeriodicSpace, OrthogonalNonperiodicSpace, ) from chiron.states import SamplerState from openmm import unit
9,303
def test_orthogonal_periodic_displacement(): # test that the incorrect box shapes throw an exception with pytest.raises(ValueError): space = OrthogonalPeriodicSpace(jnp.array([10.0, 10.0, 10.0])) # test that incorrect units throw an exception with pytest.raises(ValueError): space = OrthogonalPeriodicSpace( unit.Quantity( jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]), unit.radians, ) ) space = OrthogonalPeriodicSpace( jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) ) # test that the box vectors are set correctly assert jnp.all( space.box_vectors == jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) ) # test that the box lengths for an orthogonal box are set correctly assert jnp.all(space._box_lengths == jnp.array([10.0, 10.0, 10.0])) # test calculation of the displacement_vector and distance between two points p1 = jnp.array([[0, 0, 0], [0, 0, 0]]) p2 = jnp.array([[1, 0, 0], [6, 0, 0]]) r_ij, distance = space.displacement(p1, p2) assert jnp.all(r_ij == jnp.array([[-1.0, 0.0, 0.0], [4.0, 0.0, 0.0]])) assert jnp.all(distance == jnp.array([1, 4])) # test that the periodic wrapping works as expected wrapped_x = space.wrap(jnp.array([11, 0, 0])) assert jnp.all(wrapped_x == jnp.array([1, 0, 0])) wrapped_x = space.wrap(jnp.array([-1, 0, 0])) assert jnp.all(wrapped_x == jnp.array([9, 0, 0])) wrapped_x = space.wrap(jnp.array([5, 0, 0])) assert jnp.all(wrapped_x == jnp.array([5, 0, 0])) wrapped_x = space.wrap(jnp.array([5, 12, -1])) assert jnp.all(wrapped_x == jnp.array([5, 2, 9])) # test the setter for the box vectors space.box_vectors = jnp.array( [[10.0, 0.0, 0.0], [0.0, 20.0, 0.0], [0.0, 0.0, 30.0]] ) assert jnp.all( space._box_vectors == jnp.array([[10.0, 0.0, 0.0], [0.0, 20.0, 0.0], [0.0, 0.0, 30.0]]) ) assert jnp.all(space._box_lengths == jnp.array([10.0, 20.0, 30.0])) def test_orthogonal_nonperiodic_displacement(): space = OrthogonalNonperiodicSpace( jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) ) p1 = jnp.array([[0, 0, 0], [0, 0, 0]]) p2 = jnp.array([[1, 0, 0], [6, 0, 0]]) r_ij, distance = space.displacement(p1, p2) assert jnp.all(r_ij == jnp.array([[-1.0, 0.0, 0.0], [-6.0, 0.0, 0.0]])) assert jnp.all(distance == jnp.array([1, 6])) wrapped_x = space.wrap(jnp.array([11, -1, 2])) assert jnp.all(wrapped_x == jnp.array([11, -1, 2])) def test_neighborlist_pair(): """ This simple test of the neighborlist for 2 particles """ coordinates = jnp.array([[0, 0, 0], [1, 0, 0]]) box_vectors = jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) state = SamplerState( x0=unit.Quantity(coordinates, unit.nanometer), box_vectors=unit.Quantity(box_vectors, unit.nanometer), ) space = OrthogonalPeriodicSpace() cutoff = 1.1 skin = 0.1
def test_orthogonal_periodic_displacement(): # test that the incorrect box shapes throw an exception with pytest.raises(ValueError): space = OrthogonalPeriodicSpace(jnp.array([10.0, 10.0, 10.0])) # test that incorrect units throw an exception with pytest.raises(ValueError): space = OrthogonalPeriodicSpace( unit.Quantity( jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]), unit.radians, ) ) space = OrthogonalPeriodicSpace( jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) ) # test that the box vectors are set correctly assert jnp.all( space.box_vectors == jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) ) # test that the box lengths for an orthogonal box are set correctly assert jnp.all(space._box_lengths == jnp.array([10.0, 10.0, 10.0])) # test calculation of the displacement_vector and distance between two points p1 = jnp.array([[0, 0, 0], [0, 0, 0]]) p2 = jnp.array([[1, 0, 0], [6, 0, 0]]) r_ij, distance = space.displacement(p1, p2) assert jnp.all(r_ij == jnp.array([[-1.0, 0.0, 0.0], [4.0, 0.0, 0.0]])) assert jnp.all(distance == jnp.array([1, 4])) # test that the periodic wrapping works as expected wrapped_x = space.wrap(jnp.array([11, 0, 0])) assert jnp.all(wrapped_x == jnp.array([1, 0, 0])) wrapped_x = space.wrap(jnp.array([-1, 0, 0])) assert jnp.all(wrapped_x == jnp.array([9, 0, 0])) wrapped_x = space.wrap(jnp.array([5, 0, 0])) assert jnp.all(wrapped_x == jnp.array([5, 0, 0])) wrapped_x = space.wrap(jnp.array([5, 12, -1])) assert jnp.all(wrapped_x == jnp.array([5, 2, 9])) # test the setter for the box vectors space.box_vectors = jnp.array( [[10.0, 0.0, 0.0], [0.0, 20.0, 0.0], [0.0, 0.0, 30.0]] ) assert jnp.all( space._box_vectors == jnp.array([[10.0, 0.0, 0.0], [0.0, 20.0, 0.0], [0.0, 0.0, 30.0]]) ) assert jnp.all(space._box_lengths == jnp.array([10.0, 20.0, 30.0])) def test_orthogonal_nonperiodic_displacement(): space = OrthogonalNonperiodicSpace( jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) ) p1 = jnp.array([[0, 0, 0], [0, 0, 0]]) p2 = jnp.array([[1, 0, 0], [6, 0, 0]]) r_ij, distance = space.displacement(p1, p2) assert jnp.all(r_ij == jnp.array([[-1.0, 0.0, 0.0], [-6.0, 0.0, 0.0]])) assert jnp.all(distance == jnp.array([1, 6])) wrapped_x = space.wrap(jnp.array([11, -1, 2])) assert jnp.all(wrapped_x == jnp.array([11, -1, 2])) def test_neighborlist_pair(): """ This simple test of the neighborlist for 2 particles """ coordinates = jnp.array([[0, 0, 0], [1, 0, 0]]) box_vectors = jnp.array([[10.0, 0.0, 0.0], [0.0, 10.0, 0.0], [0.0, 0.0, 10.0]]) state = SamplerState( x0=unit.Quantity(coordinates, unit.nanometer), box_vectors=unit.Quantity(box_vectors, unit.nanometer), ) space = OrthogonalPeriodicSpace() cutoff = 1.1 skin = 0.1
nbr_list = NeighborListNsqrd(
0
2023-11-07 18:17:43+00:00
12k
Rishit-dagli/Astroformer
pytorch-image-models/timm/models/mobilenetv3.py
[ { "identifier": "build_model_with_cfg", "path": "pytorch-image-models/timm/models/_builder.py", "snippet": "def build_model_with_cfg(\n model_cls: Callable,\n variant: str,\n pretrained: bool,\n pretrained_cfg: Optional[Dict] = None,\n pretrained_cfg_overlay: Optional[...
from functools import partial from typing import Callable, List, Optional, Tuple from torch.utils.checkpoint import checkpoint from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.layers import SelectAdaptivePool2d, Linear, LayerType, PadType, create_conv2d, get_norm_act_layer from ._builder import build_model_with_cfg, pretrained_cfg_for_features from ._efficientnet_blocks import SqueezeExcite from ._efficientnet_builder import BlockArgs, EfficientNetBuilder, decode_arch_def, efficientnet_init_weights, \ round_channels, resolve_bn_args, resolve_act_layer, BN_EPS_TF_DEFAULT from ._features import FeatureInfo, FeatureHooks from ._manipulate import checkpoint_seq from ._registry import generate_default_cfgs, register_model, register_model_deprecations import torch import torch.nn as nn import torch.nn.functional as F
7,991
se_layer: Type of Squeeze-and-Excite layer. drop_rate: Dropout rate. drop_path_rate: Stochastic depth rate. """ super(MobileNetV3Features, self).__init__() act_layer = act_layer or nn.ReLU norm_layer = norm_layer or nn.BatchNorm2d se_layer = se_layer or SqueezeExcite self.drop_rate = drop_rate self.grad_checkpointing = False # Stem if not fix_stem: stem_size = round_chs_fn(stem_size) self.conv_stem = create_conv2d(in_chans, stem_size, 3, stride=2, padding=pad_type) self.bn1 = norm_layer(stem_size) self.act1 = act_layer(inplace=True) # Middle stages (IR/ER/DS Blocks) builder = EfficientNetBuilder( output_stride=output_stride, pad_type=pad_type, round_chs_fn=round_chs_fn, se_from_exp=se_from_exp, act_layer=act_layer, norm_layer=norm_layer, se_layer=se_layer, drop_path_rate=drop_path_rate, feature_location=feature_location, ) self.blocks = nn.Sequential(*builder(stem_size, block_args)) self.feature_info = FeatureInfo(builder.features, out_indices) self._stage_out_idx = {f['stage']: f['index'] for f in self.feature_info.get_dicts()} efficientnet_init_weights(self) # Register feature extraction hooks with FeatureHooks helper self.feature_hooks = None if feature_location != 'bottleneck': hooks = self.feature_info.get_dicts(keys=('module', 'hook_type')) self.feature_hooks = FeatureHooks(hooks, self.named_modules()) @torch.jit.ignore def set_grad_checkpointing(self, enable: bool = True): self.grad_checkpointing = enable def forward(self, x: torch.Tensor) -> List[torch.Tensor]: x = self.conv_stem(x) x = self.bn1(x) x = self.act1(x) if self.feature_hooks is None: features = [] if 0 in self._stage_out_idx: features.append(x) # add stem out for i, b in enumerate(self.blocks): if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint(b, x) else: x = b(x) if i + 1 in self._stage_out_idx: features.append(x) return features else: self.blocks(x) out = self.feature_hooks.get_output(x.device) return list(out.values()) def _create_mnv3(variant: str, pretrained: bool = False, **kwargs) -> MobileNetV3: features_mode = '' model_cls = MobileNetV3 kwargs_filter = None if kwargs.pop('features_only', False): if 'feature_cfg' in kwargs: features_mode = 'cfg' else: kwargs_filter = ('num_classes', 'num_features', 'head_conv', 'head_bias', 'global_pool') model_cls = MobileNetV3Features features_mode = 'cls' model = build_model_with_cfg( model_cls, variant, pretrained, features_only=features_mode == 'cfg', pretrained_strict=features_mode != 'cls', kwargs_filter=kwargs_filter, **kwargs, ) if features_mode == 'cls': model.default_cfg = pretrained_cfg_for_features(model.default_cfg) return model def _gen_mobilenet_v3_rw(variant: str, channel_multiplier: float = 1.0, pretrained: bool = False, **kwargs) -> MobileNetV3: """Creates a MobileNet-V3 model. Ref impl: ? Paper: https://arxiv.org/abs/1905.02244 Args: channel_multiplier: multiplier to number of channels per layer. """ arch_def = [ # stage 0, 112x112 in ['ds_r1_k3_s1_e1_c16_nre_noskip'], # relu # stage 1, 112x112 in ['ir_r1_k3_s2_e4_c24_nre', 'ir_r1_k3_s1_e3_c24_nre'], # relu # stage 2, 56x56 in ['ir_r3_k5_s2_e3_c40_se0.25_nre'], # relu # stage 3, 28x28 in ['ir_r1_k3_s2_e6_c80', 'ir_r1_k3_s1_e2.5_c80', 'ir_r2_k3_s1_e2.3_c80'], # hard-swish # stage 4, 14x14in ['ir_r2_k3_s1_e6_c112_se0.25'], # hard-swish # stage 5, 14x14in ['ir_r3_k5_s2_e6_c160_se0.25'], # hard-swish # stage 6, 7x7 in ['cn_r1_k1_s1_c960'], # hard-swish ] model_kwargs = dict(
""" MobileNet V3 A PyTorch impl of MobileNet-V3, compatible with TF weights from official impl. Paper: Searching for MobileNetV3 - https://arxiv.org/abs/1905.02244 Hacked together by / Copyright 2019, Ross Wightman """ __all__ = ['MobileNetV3', 'MobileNetV3Features'] class MobileNetV3(nn.Module): """ MobiletNet-V3 Based on my EfficientNet implementation and building blocks, this model utilizes the MobileNet-v3 specific 'efficient head', where global pooling is done before the head convolution without a final batch-norm layer before the classifier. Paper: `Searching for MobileNetV3` - https://arxiv.org/abs/1905.02244 Other architectures utilizing MobileNet-V3 efficient head that are supported by this impl include: * HardCoRe-NAS - https://arxiv.org/abs/2102.11646 (defn in hardcorenas.py uses this class) * FBNet-V3 - https://arxiv.org/abs/2006.02049 * LCNet - https://arxiv.org/abs/2109.15099 """ def __init__( self, block_args: BlockArgs, num_classes: int = 1000, in_chans: int = 3, stem_size: int = 16, fix_stem: bool = False, num_features: int = 1280, head_bias: bool = True, pad_type: PadType = '', act_layer: Optional[LayerType] = None, norm_layer: Optional[LayerType] = None, se_layer: Optional[LayerType] = None, se_from_exp: bool = True, round_chs_fn: Callable = round_channels, drop_rate: float = 0., drop_path_rate: float = 0., global_pool: str = 'avg', ): """ Args: block_args: Arguments for blocks of the network. num_classes: Number of classes for classification head. in_chans: Number of input image channels. stem_size: Number of output channels of the initial stem convolution. fix_stem: If True, don't scale stem by round_chs_fn. num_features: Number of output channels of the conv head layer. head_bias: If True, add a learnable bias to the conv head layer. pad_type: Type of padding to use for convolution layers. act_layer: Type of activation layer. norm_layer: Type of normalization layer. se_layer: Type of Squeeze-and-Excite layer. se_from_exp: If True, calculate SE channel reduction from expanded mid channels. round_chs_fn: Callable to round number of filters based on depth multiplier. drop_rate: Dropout rate. drop_path_rate: Stochastic depth rate. global_pool: Type of pooling to use for global pooling features of the FC head. """ super(MobileNetV3, self).__init__() act_layer = act_layer or nn.ReLU norm_layer = norm_layer or nn.BatchNorm2d norm_act_layer = get_norm_act_layer(norm_layer, act_layer) se_layer = se_layer or SqueezeExcite self.num_classes = num_classes self.num_features = num_features self.drop_rate = drop_rate self.grad_checkpointing = False # Stem if not fix_stem: stem_size = round_chs_fn(stem_size) self.conv_stem = create_conv2d(in_chans, stem_size, 3, stride=2, padding=pad_type) self.bn1 = norm_act_layer(stem_size, inplace=True) # Middle stages (IR/ER/DS Blocks) builder = EfficientNetBuilder( output_stride=32, pad_type=pad_type, round_chs_fn=round_chs_fn, se_from_exp=se_from_exp, act_layer=act_layer, norm_layer=norm_layer, se_layer=se_layer, drop_path_rate=drop_path_rate, ) self.blocks = nn.Sequential(*builder(stem_size, block_args)) self.feature_info = builder.features head_chs = builder.in_chs # Head + Pooling self.global_pool = SelectAdaptivePool2d(pool_type=global_pool) num_pooled_chs = head_chs * self.global_pool.feat_mult() self.conv_head = create_conv2d(num_pooled_chs, self.num_features, 1, padding=pad_type, bias=head_bias) self.act2 = act_layer(inplace=True) self.flatten = nn.Flatten(1) if global_pool else nn.Identity() # don't flatten if pooling disabled self.classifier = Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() efficientnet_init_weights(self) def as_sequential(self): layers = [self.conv_stem, self.bn1] layers.extend(self.blocks) layers.extend([self.global_pool, self.conv_head, self.act2]) layers.extend([nn.Flatten(), nn.Dropout(self.drop_rate), self.classifier]) return nn.Sequential(*layers) @torch.jit.ignore def group_matcher(self, coarse: bool = False): return dict( stem=r'^conv_stem|bn1', blocks=r'^blocks\.(\d+)' if coarse else r'^blocks\.(\d+)\.(\d+)' ) @torch.jit.ignore def set_grad_checkpointing(self, enable: bool = True): self.grad_checkpointing = enable @torch.jit.ignore def get_classifier(self): return self.classifier def reset_classifier(self, num_classes: int, global_pool: str = 'avg'): self.num_classes = num_classes # cannot meaningfully change pooling of efficient head after creation self.global_pool = SelectAdaptivePool2d(pool_type=global_pool) self.flatten = nn.Flatten(1) if global_pool else nn.Identity() # don't flatten if pooling disabled self.classifier = Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity() def forward_features(self, x: torch.Tensor) -> torch.Tensor: x = self.conv_stem(x) x = self.bn1(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x, flatten=True) else: x = self.blocks(x) return x def forward_head(self, x: torch.Tensor, pre_logits: bool = False) -> torch.Tensor: x = self.global_pool(x) x = self.conv_head(x) x = self.act2(x) x = self.flatten(x) if pre_logits: return x if self.drop_rate > 0.: x = F.dropout(x, p=self.drop_rate, training=self.training) return self.classifier(x) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.forward_features(x) x = self.forward_head(x) return x class MobileNetV3Features(nn.Module): """ MobileNetV3 Feature Extractor A work-in-progress feature extraction module for MobileNet-V3 to use as a backbone for segmentation and object detection models. """ def __init__( self, block_args: BlockArgs, out_indices: Tuple[int, ...] = (0, 1, 2, 3, 4), feature_location: str = 'bottleneck', in_chans: int = 3, stem_size: int = 16, fix_stem: bool = False, output_stride: int = 32, pad_type: PadType = '', round_chs_fn: Callable = round_channels, se_from_exp: bool = True, act_layer: Optional[LayerType] = None, norm_layer: Optional[LayerType] = None, se_layer: Optional[LayerType] = None, drop_rate: float = 0., drop_path_rate: float = 0., ): """ Args: block_args: Arguments for blocks of the network. out_indices: Output from stages at indices. feature_location: Location of feature before/after each block, must be in ['bottleneck', 'expansion'] in_chans: Number of input image channels. stem_size: Number of output channels of the initial stem convolution. fix_stem: If True, don't scale stem by round_chs_fn. output_stride: Output stride of the network. pad_type: Type of padding to use for convolution layers. round_chs_fn: Callable to round number of filters based on depth multiplier. se_from_exp: If True, calculate SE channel reduction from expanded mid channels. act_layer: Type of activation layer. norm_layer: Type of normalization layer. se_layer: Type of Squeeze-and-Excite layer. drop_rate: Dropout rate. drop_path_rate: Stochastic depth rate. """ super(MobileNetV3Features, self).__init__() act_layer = act_layer or nn.ReLU norm_layer = norm_layer or nn.BatchNorm2d se_layer = se_layer or SqueezeExcite self.drop_rate = drop_rate self.grad_checkpointing = False # Stem if not fix_stem: stem_size = round_chs_fn(stem_size) self.conv_stem = create_conv2d(in_chans, stem_size, 3, stride=2, padding=pad_type) self.bn1 = norm_layer(stem_size) self.act1 = act_layer(inplace=True) # Middle stages (IR/ER/DS Blocks) builder = EfficientNetBuilder( output_stride=output_stride, pad_type=pad_type, round_chs_fn=round_chs_fn, se_from_exp=se_from_exp, act_layer=act_layer, norm_layer=norm_layer, se_layer=se_layer, drop_path_rate=drop_path_rate, feature_location=feature_location, ) self.blocks = nn.Sequential(*builder(stem_size, block_args)) self.feature_info = FeatureInfo(builder.features, out_indices) self._stage_out_idx = {f['stage']: f['index'] for f in self.feature_info.get_dicts()} efficientnet_init_weights(self) # Register feature extraction hooks with FeatureHooks helper self.feature_hooks = None if feature_location != 'bottleneck': hooks = self.feature_info.get_dicts(keys=('module', 'hook_type')) self.feature_hooks = FeatureHooks(hooks, self.named_modules()) @torch.jit.ignore def set_grad_checkpointing(self, enable: bool = True): self.grad_checkpointing = enable def forward(self, x: torch.Tensor) -> List[torch.Tensor]: x = self.conv_stem(x) x = self.bn1(x) x = self.act1(x) if self.feature_hooks is None: features = [] if 0 in self._stage_out_idx: features.append(x) # add stem out for i, b in enumerate(self.blocks): if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint(b, x) else: x = b(x) if i + 1 in self._stage_out_idx: features.append(x) return features else: self.blocks(x) out = self.feature_hooks.get_output(x.device) return list(out.values()) def _create_mnv3(variant: str, pretrained: bool = False, **kwargs) -> MobileNetV3: features_mode = '' model_cls = MobileNetV3 kwargs_filter = None if kwargs.pop('features_only', False): if 'feature_cfg' in kwargs: features_mode = 'cfg' else: kwargs_filter = ('num_classes', 'num_features', 'head_conv', 'head_bias', 'global_pool') model_cls = MobileNetV3Features features_mode = 'cls' model = build_model_with_cfg( model_cls, variant, pretrained, features_only=features_mode == 'cfg', pretrained_strict=features_mode != 'cls', kwargs_filter=kwargs_filter, **kwargs, ) if features_mode == 'cls': model.default_cfg = pretrained_cfg_for_features(model.default_cfg) return model def _gen_mobilenet_v3_rw(variant: str, channel_multiplier: float = 1.0, pretrained: bool = False, **kwargs) -> MobileNetV3: """Creates a MobileNet-V3 model. Ref impl: ? Paper: https://arxiv.org/abs/1905.02244 Args: channel_multiplier: multiplier to number of channels per layer. """ arch_def = [ # stage 0, 112x112 in ['ds_r1_k3_s1_e1_c16_nre_noskip'], # relu # stage 1, 112x112 in ['ir_r1_k3_s2_e4_c24_nre', 'ir_r1_k3_s1_e3_c24_nre'], # relu # stage 2, 56x56 in ['ir_r3_k5_s2_e3_c40_se0.25_nre'], # relu # stage 3, 28x28 in ['ir_r1_k3_s2_e6_c80', 'ir_r1_k3_s1_e2.5_c80', 'ir_r2_k3_s1_e2.3_c80'], # hard-swish # stage 4, 14x14in ['ir_r2_k3_s1_e6_c112_se0.25'], # hard-swish # stage 5, 14x14in ['ir_r3_k5_s2_e6_c160_se0.25'], # hard-swish # stage 6, 7x7 in ['cn_r1_k1_s1_c960'], # hard-swish ] model_kwargs = dict(
block_args=decode_arch_def(arch_def),
3
2023-11-05 01:25:14+00:00
12k
ilur98/DGQ
dgq/quant/quant_sequence.py
[ { "identifier": "prepare_hook", "path": "dgq/quant/smooth_hooker.py", "snippet": "def prepare_hook(layer, inps, qconfig, inps_kwargs): \n handles = []\n for mod in layer.modules():\n if isinstance(mod, nn.LayerNorm) or isinstance(mod, LlamaRMSNorm):\n if qconfig[\"meanact\"]:\n ...
import torch import torch.nn as nn from dgq.quant.smooth_hooker import prepare_hook from dgq.quant.smooth import mean_bias, smooth_module from dgq.quant.quant_linear import QuantLinear from dgq.quant.quantizer_helper import QuantizerHelper from dgq.quant.kvquanter import kvquant from dgq.utils.modelutils import find_layers, move_embed, get_blocks
8,274
__all__ = ["quant_sequential"] def set_quant_state(module, actq, wtq): for mod in module.modules(): if isinstance(mod, QuantLinear): mod.setquant(actq, wtq) @torch.no_grad() def PTQ(model, enc, qconfig, nsamples=128, seqlen=2048): dev = "cuda:0" layers = get_blocks(model) layer_kwargs = {} cache={'i': 0} layers[0] = layers[0].cuda() move_embed(model, dev) dtype = next(iter(model.parameters())).dtype inps = torch.zeros((nsamples, seqlen, model.config.hidden_size), dtype=dtype, device=dev) outs = torch.zeros_like(inps) class Catcher(nn.Module): def __init__(self, module): super().__init__() self.module = module def forward(self, inp, **kwargs): inps[cache['i']] = inp cache['i'] += 1 layer_kwargs.update(kwargs) raise ValueError layers[0] = Catcher(layers[0]) for batch in enc: try: model(batch[0].to(dev)) except ValueError: pass del enc layers[0] = layers[0].module # restore # inps = inps[0] layers[0] = layers[0].cpu() move_embed(model, "cpu") for i in range(len(layers)): print(i) layer = layers[i].to(dev) full = find_layers(layer, [QuantLinear]) sequential = [list(full.keys())] set_quant_state(layer, False, False)
__all__ = ["quant_sequential"] def set_quant_state(module, actq, wtq): for mod in module.modules(): if isinstance(mod, QuantLinear): mod.setquant(actq, wtq) @torch.no_grad() def PTQ(model, enc, qconfig, nsamples=128, seqlen=2048): dev = "cuda:0" layers = get_blocks(model) layer_kwargs = {} cache={'i': 0} layers[0] = layers[0].cuda() move_embed(model, dev) dtype = next(iter(model.parameters())).dtype inps = torch.zeros((nsamples, seqlen, model.config.hidden_size), dtype=dtype, device=dev) outs = torch.zeros_like(inps) class Catcher(nn.Module): def __init__(self, module): super().__init__() self.module = module def forward(self, inp, **kwargs): inps[cache['i']] = inp cache['i'] += 1 layer_kwargs.update(kwargs) raise ValueError layers[0] = Catcher(layers[0]) for batch in enc: try: model(batch[0].to(dev)) except ValueError: pass del enc layers[0] = layers[0].module # restore # inps = inps[0] layers[0] = layers[0].cpu() move_embed(model, "cpu") for i in range(len(layers)): print(i) layer = layers[i].to(dev) full = find_layers(layer, [QuantLinear]) sequential = [list(full.keys())] set_quant_state(layer, False, False)
prepare_hook(layer, inps, qconfig, layer_kwargs)
0
2023-11-01 13:45:16+00:00
12k
m4rkw/monzo-utils
monzo_utils/lib/monzo_sync.py
[ { "identifier": "Config", "path": "monzo_utils/lib/config.py", "snippet": "class Config(metaclass=Singleton):\n\n def __init__(self, config=None, config_path=None):\n if config_path is None:\n homedir = pwd.getpwuid(os.getuid()).pw_dir\n config_path = f\"{homedir}/.monzo\...
import os import sys import time import json import yaml import re import datetime import pwd from pathlib import Path from monzo_utils.lib.config import Config from monzo_utils.lib.db import DB from monzo_utils.lib.log import Log from monzo_utils.lib.monzo_api import MonzoAPI from monzo_utils.model.provider import Provider from monzo_utils.model.account import Account from monzo_utils.model.merchant import Merchant from monzo_utils.model.merchant_address import MerchantAddress from monzo_utils.model.pot import Pot from monzo_utils.model.transaction import Transaction from monzo_utils.model.counterparty import Counterparty from monzo_utils.model.transaction_metadata import TransactionMetadata from monzo.exceptions import MonzoAuthenticationError, MonzoServerError, MonzoHTTPError, MonzoPermissionsError
8,563
def get_or_create_counterparty(self, mo_counterparty): counterparty = Counterparty().find_by_user_id(mo_counterparty['user_id']) if not counterparty: Log().info(f"creating counterparty: {mo_counterparty['name']} ({mo_counterparty['user_id']})") counterparty = Counterparty() counterparty.update(mo_counterparty) counterparty.save() return counterparty def get_provider(self): provider = Provider().find_by_name(PROVIDER) if not provider: Log().info(f"creating provider: {PROVIDER}") provider = Provider() provider.name = PROVIDER provider.save() return provider def sync(self, days=3): mo_accounts = self.api.accounts() accounts = [] for mo_account in mo_accounts: if 'monzoflexbackingloan' in mo_account.description: continue if mo_account.account_id not in Config().accounts: continue account = self.get_or_create_account(mo_account, Config().accounts[mo_account.account_id]) Log().info(f"syncing account: {account.name}") Log().info(f"getting pots for account: {account.name}") mo_pots = self.api.pots(account_id=account.account_id) pot_lookup = {} for mo_pot in mo_pots: pot = Pot().find_by_account_id_and_pot_id(account.id, mo_pot.pot_id) if not pot: Log().info(f"creating pot: {mo_pot.name}") pot = Pot() pot.account_id = account.id pot.pot_id = mo_pot.pot_id pot.name = mo_pot.name pot.balance = mo_pot.balance / 100 pot.deleted = mo_pot.deleted pot.save() pot_lookup[pot.pot_id] = pot try: Log().info(f'syncing transactions for account: {account.name}') mo_transactions = self.api.transactions(account.account_id, days=days) except MonzoPermissionsError as e: Log().error(f"permissions error: {str(e)}") if sys.stdin.isatty(): Log().info("Need to refresh permissions in the app, Settings -> Privacy & Security -> Manage Apps") else: os.system("echo 'Need to refresh permissions in the app, Settings -> Privacy & Security -> Manage Apps'| mail -s 'Monzo permission refresh required' '%s'" % (Config().email)) sys.exit(1) except MonzoServerError as e: Log().error(f"server error: {str(e)}") continue seen = {} total = 0 pot_account_ids = {} for mo_transaction in mo_transactions: transaction = self.add_transaction(account, mo_transaction, pot_account_ids) seen[transaction.id] = 1 total += 1 seen = {} for pot_account_id in pot_account_ids: if pot_lookup[pot_account_ids[pot_account_id]].deleted: continue Log().info(f"syncing transactions for pot: {pot_lookup[pot_account_ids[pot_account_id]].name}") mo_pot_transactions = self.api.transactions(pot_account_id, days=days) for mo_pot_transaction in mo_pot_transactions: transaction = self.add_transaction(account, mo_pot_transaction, pot_account_ids, pot_lookup[pot_account_ids[pot_account_id]].id) seen[transaction.id] = 1 total += 1 Log().info(f"account {account.name} synced {total} transactions") if 'touch_file' in Config().keys: Path(Config().touch_file).touch() def get_or_create_account(self, mo_account, account_config):
#!/usr/bin/env python3 PROVIDER = 'Monzo' class MonzoSync: def __init__(self, no_init=False): homedir = pwd.getpwuid(os.getuid()).pw_dir self.monzo_dir = f"{homedir}/.monzo" if not os.path.exists(self.monzo_dir): os.mkdir(self.monzo_dir, 0o755) self.config_file = f"{self.monzo_dir}/config.yaml" self.token_file = f"{self.monzo_dir}/tokens" if no_init: return Config() self.api = MonzoAPI() self.db = DB() self.provider = self.get_provider() def setup(self): print("\n========================") print("Monzo Utils Setup Wizard") print("========================\n") print("Requirements:\n") print("1) You must have created an OAuth client here: https://developers.monzo.com/apps/new") print(" Note: confidentiality must be set to Confidential\n") print("2) The database (MySQL/MariaDB or SQLite3) must be created and ready (see README.md)\n") print("3) The machine we are running on must be reachable on a known port from the internet.") print(" The webserver must be configured with the CGI script to capture the oauth tokens.") print(" This is only required during setup for the initial oauth authentication flow.") print(" Once this is complete and the tokens are stored this can be removed.\n") self.prompt_continue() if os.path.exists(self.config_file): sys.stdout.write(f"\nWARNING! Config file already exists at: {self.config_file}\n\n") sys.stdout.write("If we continue this will be erased.\n\n") self.prompt_continue() sys.stdout.write("\n") sys.stdout.write("Which database do you want to use?\n\n") sys.stdout.write("1. MySQL/MariaDB (recommended)\n") sys.stdout.write("2. SQLite3\n\n") while 1: db_backend = self.prompt_input('DB choice') if db_backend in ['1','2']: break if db_backend == '1': mysql_host = self.prompt_input('MySQL host', '127.0.0.1') mysql_port = self.prompt_input('MySQL port', '3306', False, 'int') mysql_db = self.prompt_input('MySQL database', 'monzo') mysql_user = self.prompt_input('MySQL username', 'monzo') mysql_password = self.prompt_input('MySQL password', 'monzo') db = { 'driver': 'mysql', 'host': mysql_host, 'port': mysql_port, 'user': mysql_user, 'password': mysql_password, 'database': mysql_db } else: db = { 'driver': 'sqlite', 'path': f"{self.monzo_dir}/data.db" } self.test_db_access(db) sys.stdout.write("\n") client_id = self.prompt_input('Monzo Client ID') client_secret = self.prompt_input('Monzo Client Secret') redirect_url = self.prompt_input('Monzo Client redirect URL') sys.stdout.write("Enter the path where the CGI script will store the token file:\n") token_path = self.prompt_input('Token path', '/var/www/monzo/token') sys.stdout.write("\nIf the auth token expires or stops working the sync script can send\n") sys.stdout.write("an email to notify you. Enter this email below or leave blank if not required.\n") email = self.prompt_input('Email', None, True) Config({ 'oauth_token_file': token_path, 'db': db, 'client_id': client_id, 'client_secret': client_secret, 'redirect_url': redirect_url, 'email': email }) Config().save() self.__init__() self.scan_accounts() sys.stdout.write("Performing initial transaction sync ...\n\n") sys.stdout.flush() self.sync(days=89) sys.stdout.write("\nSetup complete!\n\n") def scan_accounts(self): sys.stdout.write("\nFinding accounts...\n\n") accounts = self.api.accounts() found_accounts = [] for account in accounts: if account.balance is None: continue if 'accounts' in Config().keys and account.account_id in Config().accounts: continue if 'Joint account between' in account.description: account_type = 'Joint Current Account' else: account_type = account.account_type() print(f" id: {account.account_id}") print(f" balance: £{account.balance.balance/100:.2f}") print(f"description: {account.description}") print(f" type: {account_type}") sys.stdout.write("\n") resp = self.prompt_continue('Sync this account? [y/N] ', True) if resp == 'n': continue account_name = self.prompt_input('name for this account') if 'accounts' not in Config().keys: Config().set('accounts', {}) Config().accounts[account.account_id] = { 'name': account_name } if account_type == 'Flex': Config().accounts[account.account_id]['credit_limit'] = self.prompt_input('credit limit', None, False, 'int') else: Config().accounts[account.account_id]['sortcode'] = self.prompt_input('sort code') Config().accounts[account.account_id]['account_no'] = self.prompt_input('account no') sys.stdout.write("\n") Config().save() def prompt_continue(self, prompt='Continue? [y/N] ', boolean=False): while 1: sys.stdout.write(prompt) sys.stdout.flush() resp = sys.stdin.readline().rstrip().lower() if resp == 'n': if boolean: return False print("\nStopping at user request.\n") sys.exit(0) if resp == 'y': break return True def prompt_input(self, prompt, default=None, none_allowed=False, validation=None): while 1: if default is None: sys.stdout.write(f"Enter {prompt}: ") else: sys.stdout.write(f"Enter {prompt} [{default}]: ") sys.stdout.flush() resp = sys.stdin.readline().rstrip() if len(resp) == 0: if default is None and none_allowed is False: continue resp = default if validation == 'int' and resp is not None: try: resp = int(resp) except: sys.stderr.write("\nerror: value must be an integer\n\n") sys.stderr.flush() continue return resp def test_db_access(self, db_config): try: db = DB(db_config) except Exception as e: Log().error(f"failed to initialise the database: {str(e)}") sys.exit(1) try: if db_config['driver'] == 'mysql': resp = db.query("show tables") else: resp = db.query("pragma table_info(`provider`)") except Exception as e: Log().error(f"Failed to connect to the database: {str(e)}") sys.exit(1) def get_or_create_merchant(self, mo_merchant): if 'metadata' in mo_merchant and 'website' in mo_merchant['metadata']: website = mo_merchant['metadata']['website'] else: website = None merchant_id = mo_merchant['id'] mo_merchant['merchant_id'] = mo_merchant['id'] mo_merchant.pop('id') mo_address = mo_merchant.pop('address') merchant = Merchant().find_by_merchant_id(merchant_id) if not merchant: Log().info(f"creating merchant: {mo_merchant['name']} ({mo_merchant['merchant_id']})") merchant = Merchant() merchant.update(mo_merchant) merchant.save() mo_address['merchant_id'] = merchant.id address = MerchantAddress().find_by_merchant_id(merchant.id) if not address: address = MerchantAddress() address.update(mo_address) address.save() return merchant def sanitise(self, string): return re.sub('[\s\t]+', ' ', string) def add_transaction(self, account, mo_transaction, pot_account_ids, pot_id=None): counterparty = None if mo_transaction.counterparty: counterparty = self.get_or_create_counterparty(mo_transaction.counterparty) if counterparty.name != mo_transaction.description: description = self.sanitise('%s %s' % (counterparty.name, mo_transaction.description)) else: description = mo_transaction.description else: description = self.sanitise(mo_transaction.description) amount = mo_transaction.amount if amount >0: money_in = amount / 100 money_out = None verb = 'from' _type = 'credit' else: money_in = None money_out = 0 - (amount / 100) verb = 'to' _type = 'debit' if pot_id: where = [{ 'clause': 'pot_id = %s', 'params': [pot_id] }] else: where = [{ 'clause': 'pot_id is null' }] transaction = Transaction().find_by_account_id_and_transaction_id( account.id, mo_transaction.transaction_id, where=where ) date = mo_transaction.created.strftime('%Y-%m-%d') if not transaction: Log().info(f"creating transaction: {account.name} {date} -{money_in} +{money_out} {description}") transaction = Transaction() if pot_id is None and mo_transaction.metadata and 'pot_account_id' in mo_transaction.metadata and mo_transaction.metadata['pot_account_id'] not in pot_account_ids: pot_account_ids[mo_transaction.metadata['pot_account_id']] = mo_transaction.metadata['pot_id'] if mo_transaction.merchant: merchant = self.get_or_create_merchant(mo_transaction.merchant) else: merchant = None transaction.update({ 'account_id': account.id, 'transaction_id': mo_transaction.transaction_id, 'date': date, 'type': _type, 'description': description, 'ref': mo_transaction.description, 'money_in': money_in, 'money_out': money_out, 'pending': mo_transaction.amount_is_pending, 'created_at': mo_transaction.created, 'updated_at': mo_transaction.updated, 'currency': mo_transaction.currency, 'local_currency': mo_transaction.local_currency, 'local_amount': mo_transaction.local_amount, 'merchant_id': merchant.id if merchant else None, 'notes': mo_transaction.notes, 'originator': mo_transaction.originator, 'scheme': mo_transaction.scheme, 'settled': mo_transaction.settled, 'declined': 1 if len(mo_transaction.decline_reason) >0 else 0, 'decline_reason': mo_transaction.decline_reason, 'counterparty_id': counterparty.id if counterparty else None, 'pot_id': pot_id }) transaction.save() metadata = {} if type(mo_transaction.atm_fees_detailed) == dict: for key in mo_transaction.atm_fees_detailed: metadata['atm_fees_detailed_%s' % (key)] = mo_transaction.atm_fees_detailed[key] if type(mo_transaction.categories) == dict: for key in mo_transaction.categories: metadata['categories_%s' % (key)] = mo_transaction.categories[key] if type(mo_transaction.fees) == dict: for key in mo_transaction.fees: metadata['fees_%s' % (key)] = mo_transaction.fees[key] if type(mo_transaction.metadata) == dict: for key in mo_transaction.metadata: metadata['metadata_%s' % (key)] = mo_transaction.metadata[key] for key in metadata: transaction_metadata = TransactionMetadata().find_by_transaction_id_and_key(transaction.id, key) if not transaction_metadata: transaction_metadata = TransactionMetadata() transaction_metadata.transaction_id = transaction.id transaction_metadata.key = key transaction_metadata.value = metadata[key] transaction_metadata.save() for transaction_metadata in TransactionMetadata().find_all_by_transaction_id(transaction.id): if transaction_metadata.key not in metadata: transaction_metadata.delete() return transaction def get_or_create_counterparty(self, mo_counterparty): counterparty = Counterparty().find_by_user_id(mo_counterparty['user_id']) if not counterparty: Log().info(f"creating counterparty: {mo_counterparty['name']} ({mo_counterparty['user_id']})") counterparty = Counterparty() counterparty.update(mo_counterparty) counterparty.save() return counterparty def get_provider(self): provider = Provider().find_by_name(PROVIDER) if not provider: Log().info(f"creating provider: {PROVIDER}") provider = Provider() provider.name = PROVIDER provider.save() return provider def sync(self, days=3): mo_accounts = self.api.accounts() accounts = [] for mo_account in mo_accounts: if 'monzoflexbackingloan' in mo_account.description: continue if mo_account.account_id not in Config().accounts: continue account = self.get_or_create_account(mo_account, Config().accounts[mo_account.account_id]) Log().info(f"syncing account: {account.name}") Log().info(f"getting pots for account: {account.name}") mo_pots = self.api.pots(account_id=account.account_id) pot_lookup = {} for mo_pot in mo_pots: pot = Pot().find_by_account_id_and_pot_id(account.id, mo_pot.pot_id) if not pot: Log().info(f"creating pot: {mo_pot.name}") pot = Pot() pot.account_id = account.id pot.pot_id = mo_pot.pot_id pot.name = mo_pot.name pot.balance = mo_pot.balance / 100 pot.deleted = mo_pot.deleted pot.save() pot_lookup[pot.pot_id] = pot try: Log().info(f'syncing transactions for account: {account.name}') mo_transactions = self.api.transactions(account.account_id, days=days) except MonzoPermissionsError as e: Log().error(f"permissions error: {str(e)}") if sys.stdin.isatty(): Log().info("Need to refresh permissions in the app, Settings -> Privacy & Security -> Manage Apps") else: os.system("echo 'Need to refresh permissions in the app, Settings -> Privacy & Security -> Manage Apps'| mail -s 'Monzo permission refresh required' '%s'" % (Config().email)) sys.exit(1) except MonzoServerError as e: Log().error(f"server error: {str(e)}") continue seen = {} total = 0 pot_account_ids = {} for mo_transaction in mo_transactions: transaction = self.add_transaction(account, mo_transaction, pot_account_ids) seen[transaction.id] = 1 total += 1 seen = {} for pot_account_id in pot_account_ids: if pot_lookup[pot_account_ids[pot_account_id]].deleted: continue Log().info(f"syncing transactions for pot: {pot_lookup[pot_account_ids[pot_account_id]].name}") mo_pot_transactions = self.api.transactions(pot_account_id, days=days) for mo_pot_transaction in mo_pot_transactions: transaction = self.add_transaction(account, mo_pot_transaction, pot_account_ids, pot_lookup[pot_account_ids[pot_account_id]].id) seen[transaction.id] = 1 total += 1 Log().info(f"account {account.name} synced {total} transactions") if 'touch_file' in Config().keys: Path(Config().touch_file).touch() def get_or_create_account(self, mo_account, account_config):
account = Account().find_by_provider_id_and_account_id(self.provider.id, mo_account.account_id)
5
2023-11-05 12:48:18+00:00
12k
WolfgangFahl/dcm
tests/test_api.py
[ { "identifier": "CompetenceCmd", "path": "dcm/dcm_cmd.py", "snippet": "class CompetenceCmd(WebserverCmd):\n \"\"\"\n Command line for diagrams server\n \"\"\"\n\n def getArgParser(self, description: str, version_msg) -> ArgumentParser:\n \"\"\"\n override the default argparser ...
from ngwidgets.webserver_test import WebserverTest from dcm.dcm_cmd import CompetenceCmd from dcm.dcm_core import CompetenceTree, DynamicCompetenceMap from dcm.dcm_webserver import DynamicCompentenceMapWebServer from dcm.svg import SVGConfig from tests.markup_check import MarkupCheck
7,860
""" Created on 2023-11-08 @author: wf """ class TestAPI(WebserverTest): """ test the dcm RESTFul API """ def setUp(self, debug=False, profile=True): server_class = DynamicCompentenceMapWebServer cmd_class = CompetenceCmd WebserverTest.setUp( self, debug=debug, profile=profile, server_class=server_class, cmd_class=cmd_class, ) self.example_definitions = {} for markup in ["json", "yaml"]: self.example_definitions[ markup ] = DynamicCompetenceMap.get_example_dcm_definitions( markup=markup, required_keys=CompetenceTree.required_keys() ) def test_svg_render(self): """ test the rendering """ path = "/svg"
""" Created on 2023-11-08 @author: wf """ class TestAPI(WebserverTest): """ test the dcm RESTFul API """ def setUp(self, debug=False, profile=True): server_class = DynamicCompentenceMapWebServer cmd_class = CompetenceCmd WebserverTest.setUp( self, debug=debug, profile=profile, server_class=server_class, cmd_class=cmd_class, ) self.example_definitions = {} for markup in ["json", "yaml"]: self.example_definitions[ markup ] = DynamicCompetenceMap.get_example_dcm_definitions( markup=markup, required_keys=CompetenceTree.required_keys() ) def test_svg_render(self): """ test the rendering """ path = "/svg"
svg_config = SVGConfig(width=666, height=666)
4
2023-11-06 09:24:24+00:00
12k
fortelex/hiveline
hiveline/routing/vc_router.py
[ { "identifier": "JobHandler", "path": "hiveline/jobs/jobs.py", "snippet": "class JobHandler:\n def __init__(self, service_name: str, sim_id: str, data_source: JobsDataSource):\n self.service_name = service_name\n self.sim_id = sim_id\n self.data_source = data_source\n\n def cr...
import sys import os import argparse import datetime import time import uuid import pymongo.errors from dotenv import load_dotenv from hiveline.jobs.jobs import JobHandler, JobStatus from hiveline.jobs.mongo import MongoJobsDataSource from hiveline.models import fptf from hiveline.models.options import Option from hiveline.mongo.db import get_database from hiveline.routing import resource_builder from hiveline.routing.clients.delayed import DelayedRoutingClient from hiveline.routing.clients.routing_client import RoutingClient from hiveline.routing.servers.routing_server import RoutingServer from hiveline.vc import vc_extract from hiveline.routing.servers.otp import OpenTripPlannerRoutingServer from hiveline.routing.clients.otp import OpenTripPlannerRoutingClient from hiveline.routing.servers.bifrost import BifrostRoutingServer from hiveline.routing.clients.bifrost import BifrostRoutingClient
7,378
:param client: The routing client :param vc: The virtual commuter :param sim: The simulation :param modes: The modes to use :return: """ origin = vc_extract.extract_origin_loc(vc) destination = vc_extract.extract_destination_loc(vc) departure = vc_extract.extract_departure(vc, sim) journeys = client.get_journeys(origin[1], origin[0], destination[1], destination[0], departure, modes) if journeys is None: return None origin_fptf = fptf.Location(longitude=origin[0], latitude=origin[1]) destination_fptf = fptf.Location(longitude=destination[0], latitude=destination[1]) return [Option(str(uuid.uuid4()), origin_fptf, destination_fptf, departure, modes, journey) for journey in journeys] def __route_virtual_commuter(client: RoutingClient, vc: dict, sim: dict) -> list[Option]: """ Route a virtual commuter. It will calculate available mode combinations and then calculate routes for each of them. :param client: The routing client :param vc: The virtual commuter :param sim: The simulation :return: """ mode_combinations = [[fptf.Mode.WALKING, fptf.Mode.BUS, fptf.Mode.TRAIN, fptf.Mode.GONDOLA]] # if vc_extract.has_motor_vehicle(vc): mode_combinations += [[fptf.Mode.WALKING, fptf.Mode.CAR]] option_lists = [__get_route_results(client, vc, sim, modes) for modes in mode_combinations] options = [] for option_list in option_lists: if option_list is None: continue options += option_list options = [option for option in options if option is not None] return options def __process_virtual_commuter(client, route_results_coll, vc_coll, vc_id, sim, meta): vc = vc_coll.find_one({"vc-id": vc_id, "sim-id": sim["sim-id"]}) should_route = vc_extract.should_route(vc) if not should_route: return options = __route_virtual_commuter(client, vc, sim) if options is None or len(options) == 0: print("No route found for virtual commuter " + vc["vc-id"]) raise Exception("No route found") # dump options to route-results collection route_results = { "vc-id": vc["vc-id"], "sim-id": vc["sim-id"], "created": datetime.datetime.now(), "options": [option.to_dict() for option in options], "traveller": vc_extract.extract_traveller(vc), "meta": meta } try: route_results_coll.insert_one(route_results) except pymongo.errors.DuplicateKeyError: if "_id" in route_results: del route_results["_id"] route_results_coll.update_one({"vc-id": vc["vc-id"], "sim-id": vc["sim-id"]}, {"$set": route_results}) def __route_virtual_commuters(server: RoutingServer, client: RoutingClient, sim_id, data_dir="./cache", use_delays=True, force_graph_rebuild=False, num_threads=4, reset_jobs=False, reset_failed=False, db=None): """ Run the routing algorithm for a virtual commuter set. It will spawn a new OTP process and run the routing algorithm for all open jobs in the database. It will also update the database with the results of the routing algorithm. :param server: The routing server :param client: The routing client :param sim_id: The virtual commuter set id :param data_dir: The directory where the data should be stored :param use_delays: Whether to use delays or not :param force_graph_rebuild: Whether to force a rebuild of the graph or not :param num_threads: The number of threads to use for sending route requests to the server :param reset_jobs: Whether to reset all jobs to pending or not :param reset_failed: Whether to reset all failed jobs to pending or not :param db: The database :return: """ if db is None: db = get_database() job_handler = JobHandler("routing", sim_id, MongoJobsDataSource(db=db)) if reset_jobs: job_handler.reset_jobs() if reset_failed and not reset_jobs: job_handler.reset_failed_jobs() __create_route_calculation_jobs(db, sim_id, job_handler) job_handler.reset_timed_out_jobs() if job_handler.count_jobs(status=JobStatus.PENDING) == 0: print("No active jobs, stopping") return sim = db["simulations"].find_one({"sim-id": sim_id}) place_resources = db["place-resources"].find_one({"place-id": sim["place-id"]}) sim_date = datetime.datetime.strptime(sim["sim-date"], "%Y-%m-%d").date() print("Building resources")
if __name__ == "__main__": load_dotenv() sys.path.append(os.getenv("PROJECT_PATH")) def __create_route_calculation_jobs(db, sim_id, job_handler): """ Create route calculation jobs for all virtual commuters of a given simulation that do not have a job yet. :param db: the database :param sim_id: the simulation id :return: """ pipeline = [ { "$match": { "sim-id": sim_id } }, { "$project": { "vc-id": "$vc-id", } } ] coll = db["virtual-commuters"] result = coll.aggregate(pipeline) job_ids = [vc["vc-id"] for vc in result] job_handler.create_jobs(job_ids) def __get_route_results(client: RoutingClient, vc: dict, sim: dict, modes: list[fptf.Mode]) -> list[Option] | None: """ Get a route for a virtual commuter. :param client: The routing client :param vc: The virtual commuter :param sim: The simulation :param modes: The modes to use :return: """ origin = vc_extract.extract_origin_loc(vc) destination = vc_extract.extract_destination_loc(vc) departure = vc_extract.extract_departure(vc, sim) journeys = client.get_journeys(origin[1], origin[0], destination[1], destination[0], departure, modes) if journeys is None: return None origin_fptf = fptf.Location(longitude=origin[0], latitude=origin[1]) destination_fptf = fptf.Location(longitude=destination[0], latitude=destination[1]) return [Option(str(uuid.uuid4()), origin_fptf, destination_fptf, departure, modes, journey) for journey in journeys] def __route_virtual_commuter(client: RoutingClient, vc: dict, sim: dict) -> list[Option]: """ Route a virtual commuter. It will calculate available mode combinations and then calculate routes for each of them. :param client: The routing client :param vc: The virtual commuter :param sim: The simulation :return: """ mode_combinations = [[fptf.Mode.WALKING, fptf.Mode.BUS, fptf.Mode.TRAIN, fptf.Mode.GONDOLA]] # if vc_extract.has_motor_vehicle(vc): mode_combinations += [[fptf.Mode.WALKING, fptf.Mode.CAR]] option_lists = [__get_route_results(client, vc, sim, modes) for modes in mode_combinations] options = [] for option_list in option_lists: if option_list is None: continue options += option_list options = [option for option in options if option is not None] return options def __process_virtual_commuter(client, route_results_coll, vc_coll, vc_id, sim, meta): vc = vc_coll.find_one({"vc-id": vc_id, "sim-id": sim["sim-id"]}) should_route = vc_extract.should_route(vc) if not should_route: return options = __route_virtual_commuter(client, vc, sim) if options is None or len(options) == 0: print("No route found for virtual commuter " + vc["vc-id"]) raise Exception("No route found") # dump options to route-results collection route_results = { "vc-id": vc["vc-id"], "sim-id": vc["sim-id"], "created": datetime.datetime.now(), "options": [option.to_dict() for option in options], "traveller": vc_extract.extract_traveller(vc), "meta": meta } try: route_results_coll.insert_one(route_results) except pymongo.errors.DuplicateKeyError: if "_id" in route_results: del route_results["_id"] route_results_coll.update_one({"vc-id": vc["vc-id"], "sim-id": vc["sim-id"]}, {"$set": route_results}) def __route_virtual_commuters(server: RoutingServer, client: RoutingClient, sim_id, data_dir="./cache", use_delays=True, force_graph_rebuild=False, num_threads=4, reset_jobs=False, reset_failed=False, db=None): """ Run the routing algorithm for a virtual commuter set. It will spawn a new OTP process and run the routing algorithm for all open jobs in the database. It will also update the database with the results of the routing algorithm. :param server: The routing server :param client: The routing client :param sim_id: The virtual commuter set id :param data_dir: The directory where the data should be stored :param use_delays: Whether to use delays or not :param force_graph_rebuild: Whether to force a rebuild of the graph or not :param num_threads: The number of threads to use for sending route requests to the server :param reset_jobs: Whether to reset all jobs to pending or not :param reset_failed: Whether to reset all failed jobs to pending or not :param db: The database :return: """ if db is None: db = get_database() job_handler = JobHandler("routing", sim_id, MongoJobsDataSource(db=db)) if reset_jobs: job_handler.reset_jobs() if reset_failed and not reset_jobs: job_handler.reset_failed_jobs() __create_route_calculation_jobs(db, sim_id, job_handler) job_handler.reset_timed_out_jobs() if job_handler.count_jobs(status=JobStatus.PENDING) == 0: print("No active jobs, stopping") return sim = db["simulations"].find_one({"sim-id": sim_id}) place_resources = db["place-resources"].find_one({"place-id": sim["place-id"]}) sim_date = datetime.datetime.strptime(sim["sim-date"], "%Y-%m-%d").date() print("Building resources")
config = resource_builder.build_resources(data_dir, place_resources, sim_date)
6
2023-11-07 15:34:04+00:00
12k
uhppoted/uhppoted-app-home-assistant
custom_components/uhppoted/config_flow.py
[ { "identifier": "DOMAIN", "path": "custom_components/uhppoted/const.py", "snippet": "DOMAIN = 'uhppoted'" }, { "identifier": "CONF_BIND_ADDR", "path": "custom_components/uhppoted/const.py", "snippet": "CONF_BIND_ADDR = 'bind_address'" }, { "identifier": "CONF_BROADCAST_ADDR", ...
import logging import re import uuid import voluptuous as vol from typing import Any from typing import Dict from typing import Optional from homeassistant.core import HomeAssistant from homeassistant.core import callback from homeassistant.config_entries import ConfigFlow from homeassistant.config_entries import OptionsFlow from homeassistant.config_entries import ConfigEntry from homeassistant.helpers import selector from homeassistant.helpers.selector import SelectSelector from homeassistant.helpers.selector import SelectSelectorConfig from homeassistant.helpers.selector import SelectSelectorMode from homeassistant.helpers import config_validation as cv from uhppoted import uhppote from .const import DOMAIN from .const import CONF_BIND_ADDR from .const import CONF_BROADCAST_ADDR from .const import CONF_LISTEN_ADDR from .const import CONF_DEBUG from .const import CONF_CONTROLLERS from .const import CONF_CONTROLLER_ID from .const import CONF_CONTROLLER_SERIAL_NUMBER from .const import CONF_CONTROLLER_ADDR from .const import CONF_CONTROLLER_TIMEZONE from .const import CONF_DOORS from .const import CONF_DOOR_ID from .const import CONF_DOOR_CONTROLLER from .const import CONF_DOOR_NUMBER from .const import CONF_CARDS from .const import CONF_CARD_UNIQUE_ID from .const import CONF_CARD_NUMBER from .const import CONF_CARD_NAME from .const import CONF_CARD_STARTDATE from .const import CONF_CARD_ENDDATE from .const import CONF_CARD_DOORS from .const import DEFAULT_CONTROLLER_ID from .const import DEFAULT_CONTROLLER_ADDR from .const import DEFAULT_CONTROLLER_TIMEZONE from .const import DEFAULT_DOOR1 from .const import DEFAULT_DOOR2 from .const import DEFAULT_DOOR3 from .const import DEFAULT_DOOR4 from .options_flow import UhppotedOptionsFlow from .config import validate_controller_id from .config import validate_door_id from .config import validate_door_duplicates from .config import validate_card_id from .config import validate_all_cards from .config import get_IPv4 from .config import get_all_controllers from .config import get_all_cards from .config import default_card_start_date from .config import default_card_end_date
8,521
return await self.async_step_doors() doors = [] if re.match('^[1234].*', f"{controller['serial_no']}"): doors.append(1) if re.match('^[234].*', f"{controller['serial_no']}"): doors.append(2) if re.match('^[34].*', f"{controller['serial_no']}"): doors.append(3) if re.match('^[4].*', f"{controller['serial_no']}"): doors.append(4) select = selector.SelectSelectorConfig(options=[{ 'label': f'Door {v}', 'value': f'{v}' } for v in doors], multiple=True, custom_value=False, mode=selector.SelectSelectorMode.LIST) # yapf: disable schema = vol.Schema({ vol.Required('doors', default=[f'{v}' for v in doors]): selector.SelectSelector(select), }) placeholders = { 'controller': f'{controller["name"]}', 'serial_no': f'{controller["serial_no"]}', } return self.async_show_form(step_id="doors", data_schema=schema, errors=errors, description_placeholders=placeholders) async def async_step_door(self, user_input: Optional[Dict[str, Any]] = None): def f(v): return len(v['doors']) > 0 and not v['configured'] it = next((v for v in self.controllers if f(v['doors'])), None) if it == None: return await self.async_step_cards() else: controller = it['controller']['name'] serial_no = it['controller']['serial_no'] doors = it['doors']['doors'] errors: Dict[str, str] = {} if user_input is not None: l = [user_input[f'door{v}_id'] for v in doors] for d in doors: try: k = f'door{d}_id' v = user_input[k] validate_door_id(v, self.options) validate_door_duplicates(v, l) except ValueError as err: errors[k] = f'{err}' if not errors: v = self.options[CONF_DOORS] for d in doors: v.append({ CONF_DOOR_ID: user_input[f'door{d}_id'], CONF_DOOR_CONTROLLER: controller, CONF_DOOR_NUMBER: int(f'{d}'), }) self.options.update({CONF_DOORS: v}) it['doors']['configured'] = True return await self.async_step_door() defaults = { 'door1_id': DEFAULT_DOOR1, 'door2_id': DEFAULT_DOOR2, 'door3_id': DEFAULT_DOOR3, 'door4_id': DEFAULT_DOOR4, } if user_input is not None: for k in ['door1_id', 'door2_id', 'door3_id', 'door4_id']: if k in user_input: defaults[k] = user_input[k] schema = vol.Schema({}) if 1 in doors: schema = schema.extend({vol.Required('door1_id', default=defaults['door1_id']): str}) if 2 in doors: schema = schema.extend({vol.Required('door2_id', default=defaults['door2_id']): str}) if 3 in doors: schema = schema.extend({vol.Required('door3_id', default=defaults['door3_id']): str}) if 4 in doors: schema = schema.extend({vol.Required('door4_id', default=defaults['door4_id']): str}) placeholders = { 'controller': f'{it["controller"]["name"]}', 'serial_no': f'{it["controller"]["serial_no"]}', } return self.async_show_form(step_id="door", data_schema=schema, errors=errors, description_placeholders=placeholders) async def async_step_cards(self, user_input: Optional[Dict[str, Any]] = None): errors: Dict[str, str] = {} if user_input is not None: if not errors: self.configuration['cards'] = [{ 'card': int(f'{v}'), 'unique_id': uuid.uuid4(), 'configured': False,
_LOGGER = logging.getLogger(__name__) class UhppotedConfigFlow(ConfigFlow, domain=DOMAIN): @staticmethod @callback def async_get_options_flow(config_entry: ConfigEntry) -> UhppotedOptionsFlow: return UhppotedOptionsFlow(config_entry) async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None): defaults = self.hass.data[DOMAIN] if DOMAIN in self.hass.data else {} self.data = {} self.options = {} self.controllers = [] self.doors = [] self.configuration = {'cards': []} self.options.update(get_IPv4(defaults)) self.options.update({ CONF_CONTROLLERS: [], CONF_DOORS: [], }) return await self.async_step_IPv4() async def async_step_IPv4(self, user_input: Optional[Dict[str, Any]] = None): errors: Dict[str, str] = {} if user_input is not None: if not errors: self.options.update(user_input) return await self.async_step_controllers() bind = self.options[CONF_BIND_ADDR] broadcast = self.options[CONF_BROADCAST_ADDR] listen = self.options[CONF_LISTEN_ADDR] debug = self.options[CONF_DEBUG] schema = vol.Schema({ vol.Optional(CONF_BIND_ADDR, default=bind): str, vol.Optional(CONF_BROADCAST_ADDR, default=broadcast): str, vol.Optional(CONF_LISTEN_ADDR, default=listen): str, vol.Optional(CONF_DEBUG, default=debug): bool, }) return self.async_show_form(step_id="IPv4", data_schema=schema, errors=errors) async def async_step_controllers(self, user_input: Optional[Dict[str, Any]] = None): errors: Dict[str, str] = {} if user_input is not None: if not errors: for v in user_input[CONF_CONTROLLERS]: self.controllers.append({ 'controller': { 'name': '', 'serial_no': v, 'configured': False, }, 'doors': None, }) return await self.async_step_controller() controllers = get_all_controllers(self.options) if len(controllers) < 2: for v in controllers: self.controllers.append({ 'controller': { 'name': '', 'serial_no': v, 'configured': False, }, 'doors': None, }) return await self.async_step_controller() schema = vol.Schema({ vol.Required(CONF_CONTROLLERS, default=[f'{v}' for v in controllers]): SelectSelector( SelectSelectorConfig(options=[f'{v}' for v in controllers], multiple=True, custom_value=False, mode=SelectSelectorMode.LIST)), }) return self.async_show_form(step_id="controllers", data_schema=schema, errors=errors) async def async_step_controller(self, user_input: Optional[Dict[str, Any]] = None): it = next((v for v in self.controllers if not v['controller']['configured']), None) if it == None: return await self.async_step_doors() else: controller = it['controller'] errors: Dict[str, str] = {} if user_input is not None: name = user_input[CONF_CONTROLLER_ID] serial_no = controller['serial_no'] address = user_input[CONF_CONTROLLER_ADDR] timezone = user_input[CONF_CONTROLLER_TIMEZONE] try: validate_controller_id(serial_no, name, self.options) except ValueError as err: errors[CONF_CONTROLLER_ID] = f'{err}' if not errors: v = self.options[CONF_CONTROLLERS] v.append({ CONF_CONTROLLER_ID: name, CONF_CONTROLLER_SERIAL_NUMBER: serial_no, CONF_CONTROLLER_ADDR: address, CONF_CONTROLLER_TIMEZONE: timezone, }) self.options.update({CONF_CONTROLLERS: v}) controller['name'] = user_input[CONF_CONTROLLER_ID] controller['configured'] = True return await self.async_step_controller() defaults = { CONF_CONTROLLER_ID: DEFAULT_CONTROLLER_ID, CONF_CONTROLLER_ADDR: DEFAULT_CONTROLLER_ADDR, CONF_CONTROLLER_TIMEZONE: DEFAULT_CONTROLLER_TIMEZONE, } if user_input is not None: for k in [CONF_CONTROLLER_ID, CONF_CONTROLLER_ADDR, CONF_CONTROLLER_TIMEZONE]: if k in user_input: defaults[k] = user_input[k] schema = vol.Schema({ vol.Required(CONF_CONTROLLER_ID, default=defaults[CONF_CONTROLLER_ID]): str, vol.Optional(CONF_CONTROLLER_ADDR, default=defaults[CONF_CONTROLLER_ADDR]): str, vol.Optional(CONF_CONTROLLER_TIMEZONE, default=defaults[CONF_CONTROLLER_TIMEZONE]): str, }) return self.async_show_form(step_id="controller", data_schema=schema, errors=errors, description_placeholders={ "serial_no": controller['serial_no'], }) async def async_step_doors(self, user_input: Optional[Dict[str, Any]] = None): it = next((v for v in self.controllers if not v['doors']), None) if it == None: return await self.async_step_door() else: controller = it['controller'] errors: Dict[str, str] = {} if user_input is not None: if not errors: it['doors'] = { 'doors': [int(f'{v}') for v in user_input['doors']], 'configured': False, } return await self.async_step_doors() doors = [] if re.match('^[1234].*', f"{controller['serial_no']}"): doors.append(1) if re.match('^[234].*', f"{controller['serial_no']}"): doors.append(2) if re.match('^[34].*', f"{controller['serial_no']}"): doors.append(3) if re.match('^[4].*', f"{controller['serial_no']}"): doors.append(4) select = selector.SelectSelectorConfig(options=[{ 'label': f'Door {v}', 'value': f'{v}' } for v in doors], multiple=True, custom_value=False, mode=selector.SelectSelectorMode.LIST) # yapf: disable schema = vol.Schema({ vol.Required('doors', default=[f'{v}' for v in doors]): selector.SelectSelector(select), }) placeholders = { 'controller': f'{controller["name"]}', 'serial_no': f'{controller["serial_no"]}', } return self.async_show_form(step_id="doors", data_schema=schema, errors=errors, description_placeholders=placeholders) async def async_step_door(self, user_input: Optional[Dict[str, Any]] = None): def f(v): return len(v['doors']) > 0 and not v['configured'] it = next((v for v in self.controllers if f(v['doors'])), None) if it == None: return await self.async_step_cards() else: controller = it['controller']['name'] serial_no = it['controller']['serial_no'] doors = it['doors']['doors'] errors: Dict[str, str] = {} if user_input is not None: l = [user_input[f'door{v}_id'] for v in doors] for d in doors: try: k = f'door{d}_id' v = user_input[k] validate_door_id(v, self.options) validate_door_duplicates(v, l) except ValueError as err: errors[k] = f'{err}' if not errors: v = self.options[CONF_DOORS] for d in doors: v.append({ CONF_DOOR_ID: user_input[f'door{d}_id'], CONF_DOOR_CONTROLLER: controller, CONF_DOOR_NUMBER: int(f'{d}'), }) self.options.update({CONF_DOORS: v}) it['doors']['configured'] = True return await self.async_step_door() defaults = { 'door1_id': DEFAULT_DOOR1, 'door2_id': DEFAULT_DOOR2, 'door3_id': DEFAULT_DOOR3, 'door4_id': DEFAULT_DOOR4, } if user_input is not None: for k in ['door1_id', 'door2_id', 'door3_id', 'door4_id']: if k in user_input: defaults[k] = user_input[k] schema = vol.Schema({}) if 1 in doors: schema = schema.extend({vol.Required('door1_id', default=defaults['door1_id']): str}) if 2 in doors: schema = schema.extend({vol.Required('door2_id', default=defaults['door2_id']): str}) if 3 in doors: schema = schema.extend({vol.Required('door3_id', default=defaults['door3_id']): str}) if 4 in doors: schema = schema.extend({vol.Required('door4_id', default=defaults['door4_id']): str}) placeholders = { 'controller': f'{it["controller"]["name"]}', 'serial_no': f'{it["controller"]["serial_no"]}', } return self.async_show_form(step_id="door", data_schema=schema, errors=errors, description_placeholders=placeholders) async def async_step_cards(self, user_input: Optional[Dict[str, Any]] = None): errors: Dict[str, str] = {} if user_input is not None: if not errors: self.configuration['cards'] = [{ 'card': int(f'{v}'), 'unique_id': uuid.uuid4(), 'configured': False,
} for v in user_input[CONF_CARDS]]
14
2023-11-06 18:46:49+00:00
12k
shadowpa0327/FLORA
main.py
[ { "identifier": "AverageMeter", "path": "my_meter.py", "snippet": "class AverageMeter:\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\n self._world_size = dist.get_world_size()\n self.reset()\n\n def reset(self):\n # local\n s...
import os import time import random import argparse import datetime import numpy as np import torch import torch.backends.cudnn as cudnn import torch.distributed as dist import wandb from collections import defaultdict from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy from timm.utils import accuracy from my_meter import AverageMeter from config import get_config from models import build_model from data import build_loader from lr_scheduler import build_scheduler from optimizer import build_optimizer from logger import create_logger from utils import load_checkpoint, load_pretrained, save_checkpoint,\ NativeScalerWithGradNormCount,\ auto_resume_helper, is_main_process,\ get_git_info, run_cmd from nas_utils import build_low_rank_search_space
9,696
if idx % config.PRINT_FREQ == 0: memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) logger.info( f'Test: [{idx}/{len(data_loader)}]\t' f'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' f'Loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' f'Acc@1 {acc1_meter.val:.3f} ({acc1_meter.avg:.3f})\t' f'Acc@5 {acc5_meter.val:.3f} ({acc5_meter.avg:.3f})\t' f'Mem {memory_used:.0f}MB') acc1_meter.sync() acc5_meter.sync() logger.info( f' The number of validation samples is {int(acc1_meter.count)}') logger.info(f' * Acc@1 {acc1_meter.avg:.3f} Acc@5 {acc5_meter.avg:.3f}') return acc1_meter.avg, acc5_meter.avg, loss_meter.avg @torch.no_grad() def throughput(data_loader, model, logger): # we follow the throughput measurement of LeViT repo (https://github.com/facebookresearch/LeViT/blob/main/speed_test.py) model.eval() T0, T1 = 10, 60 images, _ = next(iter(data_loader)) batch_size, _, H, W = images.shape inputs = torch.randn(batch_size, 3, H, W).cuda(non_blocking=True) # trace model to avoid python overhead model = torch.jit.trace(model, inputs) torch.cuda.empty_cache() torch.cuda.synchronize() start = time.time() with torch.cuda.amp.autocast(): while time.time() - start < T0: model(inputs) timing = [] torch.cuda.synchronize() with torch.cuda.amp.autocast(): while sum(timing) < T1: start = time.time() model(inputs) torch.cuda.synchronize() timing.append(time.time() - start) timing = torch.as_tensor(timing, dtype=torch.float32) throughput = batch_size / timing.mean().item() logger.info(f"batch_size {batch_size} throughput {throughput}") if __name__ == '__main__': args, config = parse_option() config.defrost() if config.DISTILL.TEACHER_LOGITS_PATH: config.DISTILL.ENABLED = True if args.lsss: config.NAS.LSSS.ENABLE = True assert args.lsss_bid >= 0, "Please specify the block id for local search space searching" config.NAS.LSSS.BLOCK_ID = args.lsss_bid config.freeze() if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: rank = int(os.environ["RANK"]) world_size = int(os.environ['WORLD_SIZE']) print(f"RANK and WORLD_SIZE in environ: {rank}/{world_size}") else: rank = -1 world_size = -1 torch.cuda.set_device(config.LOCAL_RANK) torch.distributed.init_process_group( backend='nccl', init_method='env://', world_size=world_size, rank=rank) torch.distributed.barrier() seed = config.SEED + dist.get_rank() torch.manual_seed(seed) torch.cuda.manual_seed(seed) np.random.seed(seed) random.seed(config.SEED) cudnn.benchmark = True # linear scale the learning rate according to total batch size, may not be optimal linear_scaled_lr = config.TRAIN.BASE_LR * \ config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0 linear_scaled_warmup_lr = config.TRAIN.WARMUP_LR * \ config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0 linear_scaled_min_lr = config.TRAIN.MIN_LR * \ config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0 # gradient accumulation also need to scale the learning rate if config.TRAIN.ACCUMULATION_STEPS > 1: linear_scaled_lr = linear_scaled_lr * config.TRAIN.ACCUMULATION_STEPS linear_scaled_warmup_lr = linear_scaled_warmup_lr * config.TRAIN.ACCUMULATION_STEPS linear_scaled_min_lr = linear_scaled_min_lr * config.TRAIN.ACCUMULATION_STEPS config.defrost() config.TRAIN.BASE_LR = linear_scaled_lr config.TRAIN.WARMUP_LR = linear_scaled_warmup_lr config.TRAIN.MIN_LR = linear_scaled_min_lr config.freeze() os.makedirs(config.OUTPUT, exist_ok=True) logger = create_logger(output_dir=config.OUTPUT, dist_rank=dist.get_rank(), name=f"{config.MODEL.NAME}") if is_main_process(): path = os.path.join(config.OUTPUT, "config.json") with open(path, "w") as f: f.write(config.dump()) logger.info(f"Full config saved to {path}") config_dict = dict(config) #config_dict['git'] = get_git_info() if args.use_wandb: wandb_output_path = config.OUTPUT wandb.init(project="TrimsformerV2", entity="brian1009", config=config_dict, dir=wandb_output_path) # print git info logger.info('===== git =====')
# -------------------------------------------------------- # Based on the code: TinyViT # (https://github.com/microsoft/Cream/tree/main/TinyViT) # Add Low Rank Supernet Training # -------------------------------------------------------- try: except ImportError: wandb = None NORM_ITER_LEN = 100 def parse_option(): parser = argparse.ArgumentParser( 'Swin Transformer training and evaluation script', add_help=False) parser.add_argument('--cfg', type=str, required=True, metavar="FILE", help='path to config file', ) parser.add_argument( "--opts", help="Modify config options by adding 'KEY VALUE' pairs. ", default=None, nargs='+', ) # easy config modification parser.add_argument('--batch-size', type=int, help="batch size for single GPU") parser.add_argument('--data-path', type=str, help='path to dataset') parser.add_argument('--pretrained', help='pretrained weight from checkpoint, could be imagenet22k pretrained weight') parser.add_argument('--resume', help='resume from checkpoint') parser.add_argument('--accumulation-steps', type=int, help="gradient accumulation steps") parser.add_argument('--use-checkpoint', action='store_true', help="whether to use gradient checkpointing to save memory") parser.add_argument('--disable_amp', action='store_true', help='Disable pytorch amp') parser.add_argument('--output', default='output', type=str, metavar='PATH', help='root of output folder, the full path is <output>/<model_name>/<tag> (default: output)') parser.add_argument('--tag', help='tag of experiment') parser.add_argument('--eval', action='store_true', help='Perform evaluation only') parser.add_argument('--throughput', action='store_true', help='Test throughput only') parser.add_argument('--use-sync-bn', action='store_true', default=False, help='sync bn') parser.add_argument('--use-wandb', action='store_true', default=False, help='use wandb to record log') # distributed training parser.add_argument("--local_rank", type=int, help='local rank for DistributedDataParallel') # NAS parser.add_argument("--lsss", action='store_true', help = 'train only the local supernet', default=False) parser.add_argument("--lsss-bid", type = int, help = "block id for the target transformer blocks", default = -1) args = parser.parse_args() config = get_config(args) return args, config def main(args, config): dataset_train, dataset_val, data_loader_train, data_loader_val, mixup_fn = build_loader( config) supernet_config = config.NAS.SEARCH_SPACE smallest_config = [] for ratios in supernet_config: smallest_config.append(ratios[0]) logger.info(f"Creating model:{config.MODEL.TYPE}/{config.MODEL.NAME}") model = build_model(config) model.cuda() if args.use_sync_bn: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) logger.info(str(model)) optimizer = build_optimizer(config, model) if 'classic' in config.MODEL.TYPE: model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[config.LOCAL_RANK], broadcast_buffers=False, find_unused_parameters = True) else: model = torch.nn.parallel.DistributedDataParallel( model, device_ids=[config.LOCAL_RANK], broadcast_buffers=False, find_unused_parameters = False) loss_scaler = NativeScalerWithGradNormCount() model_without_ddp = model.module low_rank_search_space = build_low_rank_search_space(args, config) if config.NAS.ENABLE: if config.NAS.INIT_CONFIG is None: cfg = low_rank_search_space.get_smallest_config() else: cfg = config.NAS.INIT_CONFIG model_without_ddp.set_sample_config(cfg) if config.NAS.LSSS.ENABLE: logger.info(f"=> Now training the local supernet of block-{config.NAS.LSSS.BLOCK_ID}") else: logger.info(f"=> Srarting supernet training !") logger.info(f"") logger.info(f"=> Set init subnet config to be {cfg}") logger.info(str(model)) n_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad) logger.info(f"number of params: {n_parameters}") if hasattr(model_without_ddp, 'flops'): flops = model_without_ddp.flops() logger.info(f"number of GFLOPs: {flops / 1e9}") lr_scheduler = build_scheduler(config, optimizer, len( data_loader_train) // config.TRAIN.ACCUMULATION_STEPS) if config.DISTILL.ENABLED: # we disable MIXUP and CUTMIX when knowledge distillation assert len( config.DISTILL.TEACHER_LOGITS_PATH) > 0, "Please fill in DISTILL.TEACHER_LOGITS_PATH" criterion = torch.nn.CrossEntropyLoss(reduction='mean') else: if config.AUG.MIXUP > 0.: # smoothing is handled with mixup label transform criterion = SoftTargetCrossEntropy() elif config.MODEL.LABEL_SMOOTHING > 0.: criterion = LabelSmoothingCrossEntropy( smoothing=config.MODEL.LABEL_SMOOTHING) else: criterion = torch.nn.CrossEntropyLoss() max_accuracy = 0.0 if config.TRAIN.AUTO_RESUME: resume_file = auto_resume_helper(config.OUTPUT) if resume_file: if config.MODEL.RESUME: logger.warning( f"auto-resume changing resume file from {config.MODEL.RESUME} to {resume_file}") config.defrost() config.MODEL.RESUME = resume_file config.freeze() logger.info(f'auto resuming from {resume_file}') else: logger.info( f'no checkpoint found in {config.OUTPUT}, ignoring auto resume') if config.MODEL.RESUME: max_accuracy = load_checkpoint( config, model_without_ddp, optimizer, lr_scheduler, loss_scaler, logger) acc1, acc5, loss = validate(args, config, data_loader_val, model) logger.info( f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") if config.EVAL_MODE: return if config.MODEL.PRETRAINED and (not config.MODEL.RESUME): load_pretrained(config, model_without_ddp, logger) acc1, acc5, loss = validate(args, config, data_loader_val, model) logger.info( f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") if config.EVAL_MODE: return if config.THROUGHPUT_MODE: throughput(data_loader_val, model, logger) return logger.info("Start training") start_time = time.time() for epoch in range(config.TRAIN.START_EPOCH, config.TRAIN.EPOCHS): # set_epoch for dataset_train when distillation if hasattr(dataset_train, 'set_epoch'): dataset_train.set_epoch(epoch) data_loader_train.sampler.set_epoch(epoch) if config.DISTILL.ENABLED: train_one_epoch_distill_using_saved_logits( args, config, model, criterion, data_loader_train, optimizer, epoch, mixup_fn, lr_scheduler, loss_scaler, low_rank_search_space) else: train_one_epoch(args, config, model, criterion, data_loader_train, optimizer, epoch, mixup_fn, lr_scheduler, loss_scaler, low_rank_search_space) if dist.get_rank() == 0 and (epoch % config.SAVE_FREQ == 0 or epoch == (config.TRAIN.EPOCHS - 1)): save_checkpoint(config, epoch, model_without_ddp, max_accuracy, optimizer, lr_scheduler, loss_scaler, logger) if config.NAS.ENABLE: if config.NAS.LSSS.ENABLE: test_cfg = low_rank_search_space.get_smallest_config_ith_block(config.NAS.LSSS.BLOCK_ID) else: test_cfg = low_rank_search_space.get_smallest_config() model.module.set_sample_config(test_cfg) logger.info(f"=> Set smallest subnets:{test_cfg}") logger.info(f"=> # of flops: {model.module.flops() / 1e9}") acc1, acc5, loss = validate(args, config, data_loader_val, model) logger.info( f"Accuracy of the network on the {len(dataset_val)} test images: {acc1:.1f}%") max_accuracy = max(max_accuracy, acc1) logger.info(f'Max accuracy: {max_accuracy:.2f}%') if is_main_process() and args.use_wandb: wandb.log({ f"val/acc@1": acc1, f"val/acc@5": acc5, f"val/loss": loss, "epoch": epoch, }) wandb.run.summary['epoch'] = epoch wandb.run.summary['best_acc@1'] = max_accuracy total_time = time.time() - start_time total_time_str = str(datetime.timedelta(seconds=int(total_time))) logger.info('Training time {}'.format(total_time_str)) def is_valid_grad_norm(num): if num is None: return False return not bool(torch.isinf(num)) and not bool(torch.isnan(num)) def set_bn_state(config, model): if config.TRAIN.EVAL_BN_WHEN_TRAINING: for m in model.modules(): if isinstance(m, torch.nn.modules.batchnorm._BatchNorm): m.eval() def train_one_epoch(args, config, model, criterion, data_loader, optimizer, epoch, mixup_fn, lr_scheduler, loss_scaler, low_rank_search_space): model.train() set_bn_state(config, model) optimizer.zero_grad() num_steps = len(data_loader) batch_time = AverageMeter() loss_meter = AverageMeter() norm_meter = AverageMeter() scaler_meter = AverageMeter() acc1_meter = AverageMeter() acc5_meter = AverageMeter() start = time.time() end = time.time() for idx, (samples, targets) in enumerate(data_loader): normal_global_idx = epoch * NORM_ITER_LEN + \ (idx * NORM_ITER_LEN // num_steps) samples = samples.cuda(non_blocking=True) targets = targets.cuda(non_blocking=True) if config.NAS.LSSS.ENABLE: subnet_cfg = low_rank_search_space.random_ith_block(config.NAS.LSSS.BLOCK_ID) else: subnet_cfg = low_rank_search_space.random() model.module.set_sample_config(subnet_cfg) if mixup_fn is not None: samples, targets = mixup_fn(samples, targets) original_targets = targets.argmax(dim=1) else: original_targets = targets with torch.cuda.amp.autocast(enabled=config.AMP_ENABLE): outputs = model(samples) loss = criterion(outputs, targets) loss = loss / config.TRAIN.ACCUMULATION_STEPS # this attribute is added by timm on one optimizer (adahessian) is_second_order = hasattr( optimizer, 'is_second_order') and optimizer.is_second_order grad_norm = loss_scaler(loss, optimizer, clip_grad=config.TRAIN.CLIP_GRAD, parameters=model.parameters(), create_graph=is_second_order, update_grad=(idx + 1) % config.TRAIN.ACCUMULATION_STEPS == 0) if (idx + 1) % config.TRAIN.ACCUMULATION_STEPS == 0: optimizer.zero_grad() lr_scheduler.step_update( (epoch * num_steps + idx) // config.TRAIN.ACCUMULATION_STEPS) loss_scale_value = loss_scaler.state_dict()["scale"] with torch.no_grad(): acc1, acc5 = accuracy(outputs, original_targets, topk=(1, 5)) acc1_meter.update(acc1.item(), targets.size(0)) acc5_meter.update(acc5.item(), targets.size(0)) torch.cuda.synchronize() loss_meter.update(loss.item(), targets.size(0)) if is_valid_grad_norm(grad_norm): norm_meter.update(grad_norm) scaler_meter.update(loss_scale_value) batch_time.update(time.time() - end) end = time.time() if idx % config.PRINT_FREQ == 0: lr = optimizer.param_groups[0]['lr'] memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) etas = batch_time.avg * (num_steps - idx) logger.info( f'Train: [{epoch}/{config.TRAIN.EPOCHS}][{idx}/{num_steps}]\t' f'eta {datetime.timedelta(seconds=int(etas))} lr {lr:.6f}\t' f'time {batch_time.val:.4f} ({batch_time.avg:.4f})\t' f'loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' f'grad_norm {norm_meter.val:.4f} ({norm_meter.avg:.4f})\t' f'loss_scale {scaler_meter.val:.4f} ({scaler_meter.avg:.4f})\t' f'mem {memory_used:.0f}MB') if is_main_process() and args.use_wandb: wandb.log({ "train/acc@1": acc1_meter.val, "train/acc@5": acc5_meter.val, "train/loss": loss_meter.val, "train/grad_norm": norm_meter.val, "train/loss_scale": scaler_meter.val, "train/lr": lr, }, step=normal_global_idx) epoch_time = time.time() - start logger.info( f"EPOCH {epoch} training takes {datetime.timedelta(seconds=int(epoch_time))}") def train_one_epoch_distill_using_saved_logits(args, config, model, criterion, data_loader, optimizer, epoch, mixup_fn, lr_scheduler, loss_scaler, low_rank_search_space): model.train() set_bn_state(config, model) optimizer.zero_grad() num_steps = len(data_loader) batch_time = AverageMeter() loss_meter = AverageMeter() norm_meter = AverageMeter() scaler_meter = AverageMeter() meters = defaultdict(AverageMeter) start = time.time() end = time.time() data_tic = time.time() num_classes = config.MODEL.NUM_CLASSES topk = config.DISTILL.LOGITS_TOPK for idx, ((samples, targets), (logits_index, logits_value, seeds)) in enumerate(data_loader): normal_global_idx = epoch * NORM_ITER_LEN + \ (idx * NORM_ITER_LEN // num_steps) samples = samples.cuda(non_blocking=True) targets = targets.cuda(non_blocking=True) if config.NAS.LSSS.ENABLE: subnet_cfg = low_rank_search_space.random_ith_block(config.NAS.LSSS.BLOCK_ID) else: subnet_cfg = low_rank_search_space.random() model.module.set_sample_config(subnet_cfg) if mixup_fn is not None: samples, targets = mixup_fn(samples, targets, seeds) original_targets = targets.argmax(dim=1) else: original_targets = targets meters['data_time'].update(time.time() - data_tic) with torch.cuda.amp.autocast(enabled=config.AMP_ENABLE): outputs = model(samples) # recover teacher logits logits_index = logits_index.long() logits_value = logits_value.float() logits_index = logits_index.cuda(non_blocking=True) logits_value = logits_value.cuda(non_blocking=True) minor_value = (1.0 - logits_value.sum(-1, keepdim=True) ) / (num_classes - topk) minor_value = minor_value.repeat_interleave(num_classes, dim=-1) outputs_teacher = minor_value.scatter_(-1, logits_index, logits_value) loss = criterion(outputs, outputs_teacher) loss = loss / config.TRAIN.ACCUMULATION_STEPS # this attribute is added by timm on one optimizer (adahessian) is_second_order = hasattr( optimizer, 'is_second_order') and optimizer.is_second_order grad_norm = loss_scaler(loss, optimizer, clip_grad=config.TRAIN.CLIP_GRAD, parameters=model.parameters(), create_graph=is_second_order, update_grad=(idx + 1) % config.TRAIN.ACCUMULATION_STEPS == 0) if (idx + 1) % config.TRAIN.ACCUMULATION_STEPS == 0: optimizer.zero_grad() lr_scheduler.step_update( (epoch * num_steps + idx) // config.TRAIN.ACCUMULATION_STEPS) loss_scale_value = loss_scaler.state_dict()["scale"] # compute accuracy real_batch_size = len(original_targets) acc1, acc5 = accuracy(outputs, original_targets, topk=(1, 5)) meters['train_acc1'].update(acc1.item(), real_batch_size) meters['train_acc5'].update(acc5.item(), real_batch_size) teacher_acc1, teacher_acc5 = accuracy( outputs_teacher, original_targets, topk=(1, 5)) meters['teacher_acc1'].update(teacher_acc1.item(), real_batch_size) meters['teacher_acc5'].update(teacher_acc5.item(), real_batch_size) torch.cuda.synchronize() loss_meter.update(loss.item(), real_batch_size) if is_valid_grad_norm(grad_norm): norm_meter.update(grad_norm) scaler_meter.update(loss_scale_value) batch_time.update(time.time() - end) end = time.time() data_tic = time.time() if idx % config.PRINT_FREQ == 0: lr = optimizer.param_groups[0]['lr'] memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) etas = batch_time.avg * (num_steps - idx) extra_meters_str = '' for k, v in meters.items(): extra_meters_str += f'{k} {v.val:.4f} ({v.avg:.4f})\t' logger.info( f'Train: [{epoch}/{config.TRAIN.EPOCHS}][{idx}/{num_steps}]\t' f'eta {datetime.timedelta(seconds=int(etas))} lr {lr:.6f}\t' f'time {batch_time.val:.4f} ({batch_time.avg:.4f})\t' f'loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' f'grad_norm {norm_meter.val:.4f} ({norm_meter.avg:.4f})\t' f'loss_scale {scaler_meter.val:.4f} ({scaler_meter.avg:.4f})\t' f'{extra_meters_str}' f'mem {memory_used:.0f}MB') if is_main_process() and args.use_wandb: acc1_meter, acc5_meter = meters['train_acc1'], meters['train_acc5'] wandb.log({ "train/acc@1": acc1_meter.val, "train/acc@5": acc5_meter.val, "train/loss": loss_meter.val, "train/grad_norm": norm_meter.val, "train/loss_scale": scaler_meter.val, "train/lr": lr, }, step=normal_global_idx) epoch_time = time.time() - start extra_meters_str = f'Train-Summary: [{epoch}/{config.TRAIN.EPOCHS}]\t' for k, v in meters.items(): v.sync() extra_meters_str += f'{k} {v.val:.4f} ({v.avg:.4f})\t' logger.info(extra_meters_str) logger.info( f"EPOCH {epoch} training takes {datetime.timedelta(seconds=int(epoch_time))}") @torch.no_grad() def validate(args, config, data_loader, model, num_classes=1000): criterion = torch.nn.CrossEntropyLoss() model.eval() batch_time = AverageMeter() loss_meter = AverageMeter() acc1_meter = AverageMeter() acc5_meter = AverageMeter() end = time.time() for idx, (images, target) in enumerate(data_loader): images = images.cuda(non_blocking=True) target = target.cuda(non_blocking=True) # compute output with torch.cuda.amp.autocast(enabled=config.AMP_ENABLE): output = model(images) # measure accuracy and record loss loss = criterion(output, target) acc1, acc5 = accuracy(output, target, topk=(1, 5)) loss_meter.update(loss.item(), target.size(0)) acc1_meter.update(acc1.item(), target.size(0)) acc5_meter.update(acc5.item(), target.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() if idx % config.PRINT_FREQ == 0: memory_used = torch.cuda.max_memory_allocated() / (1024.0 * 1024.0) logger.info( f'Test: [{idx}/{len(data_loader)}]\t' f'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' f'Loss {loss_meter.val:.4f} ({loss_meter.avg:.4f})\t' f'Acc@1 {acc1_meter.val:.3f} ({acc1_meter.avg:.3f})\t' f'Acc@5 {acc5_meter.val:.3f} ({acc5_meter.avg:.3f})\t' f'Mem {memory_used:.0f}MB') acc1_meter.sync() acc5_meter.sync() logger.info( f' The number of validation samples is {int(acc1_meter.count)}') logger.info(f' * Acc@1 {acc1_meter.avg:.3f} Acc@5 {acc5_meter.avg:.3f}') return acc1_meter.avg, acc5_meter.avg, loss_meter.avg @torch.no_grad() def throughput(data_loader, model, logger): # we follow the throughput measurement of LeViT repo (https://github.com/facebookresearch/LeViT/blob/main/speed_test.py) model.eval() T0, T1 = 10, 60 images, _ = next(iter(data_loader)) batch_size, _, H, W = images.shape inputs = torch.randn(batch_size, 3, H, W).cuda(non_blocking=True) # trace model to avoid python overhead model = torch.jit.trace(model, inputs) torch.cuda.empty_cache() torch.cuda.synchronize() start = time.time() with torch.cuda.amp.autocast(): while time.time() - start < T0: model(inputs) timing = [] torch.cuda.synchronize() with torch.cuda.amp.autocast(): while sum(timing) < T1: start = time.time() model(inputs) torch.cuda.synchronize() timing.append(time.time() - start) timing = torch.as_tensor(timing, dtype=torch.float32) throughput = batch_size / timing.mean().item() logger.info(f"batch_size {batch_size} throughput {throughput}") if __name__ == '__main__': args, config = parse_option() config.defrost() if config.DISTILL.TEACHER_LOGITS_PATH: config.DISTILL.ENABLED = True if args.lsss: config.NAS.LSSS.ENABLE = True assert args.lsss_bid >= 0, "Please specify the block id for local search space searching" config.NAS.LSSS.BLOCK_ID = args.lsss_bid config.freeze() if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: rank = int(os.environ["RANK"]) world_size = int(os.environ['WORLD_SIZE']) print(f"RANK and WORLD_SIZE in environ: {rank}/{world_size}") else: rank = -1 world_size = -1 torch.cuda.set_device(config.LOCAL_RANK) torch.distributed.init_process_group( backend='nccl', init_method='env://', world_size=world_size, rank=rank) torch.distributed.barrier() seed = config.SEED + dist.get_rank() torch.manual_seed(seed) torch.cuda.manual_seed(seed) np.random.seed(seed) random.seed(config.SEED) cudnn.benchmark = True # linear scale the learning rate according to total batch size, may not be optimal linear_scaled_lr = config.TRAIN.BASE_LR * \ config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0 linear_scaled_warmup_lr = config.TRAIN.WARMUP_LR * \ config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0 linear_scaled_min_lr = config.TRAIN.MIN_LR * \ config.DATA.BATCH_SIZE * dist.get_world_size() / 512.0 # gradient accumulation also need to scale the learning rate if config.TRAIN.ACCUMULATION_STEPS > 1: linear_scaled_lr = linear_scaled_lr * config.TRAIN.ACCUMULATION_STEPS linear_scaled_warmup_lr = linear_scaled_warmup_lr * config.TRAIN.ACCUMULATION_STEPS linear_scaled_min_lr = linear_scaled_min_lr * config.TRAIN.ACCUMULATION_STEPS config.defrost() config.TRAIN.BASE_LR = linear_scaled_lr config.TRAIN.WARMUP_LR = linear_scaled_warmup_lr config.TRAIN.MIN_LR = linear_scaled_min_lr config.freeze() os.makedirs(config.OUTPUT, exist_ok=True) logger = create_logger(output_dir=config.OUTPUT, dist_rank=dist.get_rank(), name=f"{config.MODEL.NAME}") if is_main_process(): path = os.path.join(config.OUTPUT, "config.json") with open(path, "w") as f: f.write(config.dump()) logger.info(f"Full config saved to {path}") config_dict = dict(config) #config_dict['git'] = get_git_info() if args.use_wandb: wandb_output_path = config.OUTPUT wandb.init(project="TrimsformerV2", entity="brian1009", config=config_dict, dir=wandb_output_path) # print git info logger.info('===== git =====')
logger.info(run_cmd('git rev-parse --abbrev-ref HEAD'))
14
2023-11-03 09:54:45+00:00
12k
fw-ai/fireworks_poe_bot
fireworks_poe_bot/__main__.py
[ { "identifier": "FireworksPoeTextBot", "path": "fireworks_poe_bot/fw_poe_text_bot.py", "snippet": "class FireworksPoeTextBot(PoeBot):\n def __init__(\n self,\n model: str,\n api_key: str,\n environment: str,\n deployment: str,\n server_version: str,\n ...
from fireworks_poe_bot.fw_poe_text_bot import FireworksPoeTextBot from fireworks_poe_bot.fw_poe_image_bot import FireworksPoeImageBot from fireworks_poe_bot.fw_poe_qr_bot import FireworksPoeQRBot from fireworks_poe_bot.logging import UVICORN_LOGGING_CONFIG from fireworks_poe_bot.plugin import LoggingPlugin, register_logging_plugin, BOT_PLUGINS, log_info from dataclasses import dataclass from typing import Any, Dict from .fastapi_poe import make_app import argparse import uvicorn import logging import os import json
9,919
@dataclass class ServerArgs: host: str = "0.0.0.0" port: int = 80 config_file_path: str = "config.json" environment: str = "" deployment: str = "poe-omnibot"
@dataclass class ServerArgs: host: str = "0.0.0.0" port: int = 80 config_file_path: str = "config.json" environment: str = "" deployment: str = "poe-omnibot"
class PyLoggingPlugin(LoggingPlugin):
4
2023-11-03 23:24:23+00:00
12k
Fsoft-AIC/LSDM
run/train_sdm.py
[ { "identifier": "count_parameters", "path": "posa/posa_utils.py", "snippet": "def count_parameters(model):\n return sum(p.numel() for p in model.parameters() if p.requires_grad)" }, { "identifier": "ProxDataset_txt", "path": "posa/dataset.py", "snippet": "class ProxDataset_txt(Dataset...
import os import functools import os.path as osp import math import argparse import time import numpy as np import torch import torch.nn.functional as F from tqdm import tqdm from torch.utils.tensorboard import SummaryWriter from torch.utils.data import DataLoader from torch.optim import AdamW from pytorch3d.loss import chamfer_distance from posa.posa_utils import count_parameters from posa.dataset import ProxDataset_txt, HUMANISE from posa.general_utils import compute_recon_loss, compute_delta from diffusion.resample import create_named_schedule_sampler from diffusion.fp16_util import MixedPrecisionTrainer from util.model_util import create_model_and_diffusion
7,206
skip_timesteps=0, # 0 is the default value - i.e. don't skip any step init_image=None, progress=False, dump_steps=None, noise=None, const_noise=False, # when experimenting guidance_scale we want to nutrileze the effect of noise on generation ) # pr_cf: (bs, seg_len, 655, 43), mu: (bs, 256), logvar: (bs, 256) # z = torch.tensor(np.random.normal(0, 1, (max_frame, 256)).astype(np.float32)).to(device) # posa_out = model.posa(z, verts_can) pr_pnts = sample gt_pnts = target_obj recon_loss_semantics = ((pr_pnts-gt_pnts)**2).mean() cfd, cfd_normals = chamfer_distance(pr_pnts, gt_pnts.float().to(device)) # Calculate for categorical pred_cat = model.saved_cat pred_cat = pred_cat.squeeze(1) pred_cat = torch.argmax(pred_cat, dim=1) target_cat = torch.argmax(target_cat, dim=1) acc = (pred_cat==target_cat).sum().item() # recon_loss_semantics, semantics_recon_acc = compute_recon_loss(gt_cf, pr_cf, mask=mask, **args_dict) total_recon_loss_semantics += recon_loss_semantics total_cfd += cfd total_acc += acc n_steps += 1 total_recon_loss_semantics /= n_steps total_cfd /= n_steps total_acc /= n_steps print(n_steps) writer.add_scalar('recon_loss_semantics/validate', total_recon_loss_semantics, e) writer.add_scalar('total_cfd/validate', total_cfd, e) writer.add_scalar('total_acc/validate', total_acc, e) print( '====>Recon_loss_semantics = {:.4f} , Chamfer distance = {:.4f}, Category acc = {:.4f}'.format( total_recon_loss_semantics, total_cfd, total_acc)) return total_recon_loss_semantics, total_cfd, total_acc if __name__ == '__main__': # torch.manual_seed(0) print(torch.version.cuda) # torch.multiprocessing.set_start_method('spawn') parser = argparse.ArgumentParser(description="") parser.add_argument("--train_data_dir", type=str, default="data/proxd_train", help="path to POSA_temp dataset dir") parser.add_argument("--valid_data_dir", type=str, default="data/proxd_valid", help="path to POSA_temp dataset dir") parser.add_argument("--load_ckpt", type=str, default=None, help="load a checkpoint as the continue point for training") parser.add_argument("--posa_path", type=str, default="training/posa/model_ckpt/best_model_recon_acc.pt") parser.add_argument("--out_dir", type=str, default="training/", help="Folder that stores checkpoints and training logs") parser.add_argument("--experiment", type=str, default="default_experiment", help="Experiment name. Checkpoints and training logs will be saved in out_dir/experiment folder.") parser.add_argument("--save_interval", type=int, default=50, help="Epoch interval for saving model checkpoints.") parser.add_argument("--lr", type=float, default=1e-3) parser.add_argument("--epochs", type=int, default=1000) parser.add_argument('--fix_ori', dest='fix_ori', action='store_const', const=True, default=False, help="fix orientation of each segment with the rotation calculated from the first frame") parser.add_argument("--encoder_mode", type=int, default=1, help="Encoder mode (different number represents different variants of encoder)") parser.add_argument("--decoder_mode", type=int, default=1, help="Decoder mode (different number represents different variants of decoder)") parser.add_argument("--n_layer", type=int, default=3, help="number of layers in transformer") parser.add_argument("--n_head", type=int, default=4, help="number of heads in transformer") parser.add_argument("--dim_ff", type=int, default=512, help="dimension of hidden layers in positionwise MLP in the transformer") parser.add_argument("--f_vert", type=int, default=64, help="dimension of the embeddings for body vertices") parser.add_argument("--num_workers", type=int, default=0, help="number of workers for dataloader") parser.add_argument("--jump_step", type=int, default=8, help="frame skip size for each input motion sequence") parser.add_argument("--max_frame", type=int, default=256, help="The maximum length of motion sequence (after frame skipping) which model accepts.") parser.add_argument("--eval_epochs", type=int, default=10, help="The number of epochs that we periodically evalute the model.") parser.add_argument("--datatype", type=str, default="proxd", help="Dataset type indicator: PRO-teXt or HUMANISE.") args = parser.parse_args() args_dict = vars(args) # Parse arguments train_data_dir = args_dict['train_data_dir'] valid_data_dir = args_dict['valid_data_dir'] load_ckpt = args_dict['load_ckpt'] save_interval = args_dict['save_interval'] out_dir = args_dict['out_dir'] experiment = args_dict['experiment'] lr = args_dict['lr'] epochs = args_dict['epochs'] fix_ori = args_dict['fix_ori'] encoder_mode = args_dict['encoder_mode'] decoder_mode = args_dict['decoder_mode'] n_layer = args_dict['n_layer'] n_head = args_dict['n_head'] num_workers = args_dict['num_workers'] jump_step = args_dict['jump_step'] max_frame = args_dict['max_frame'] dim_ff = args_dict['dim_ff'] f_vert = args_dict['f_vert'] posa_path = args_dict['posa_path'] eval_epochs = args_dict['eval_epochs'] datatype = args_dict['datatype'] save_ckpt_dir = os.path.join(out_dir, experiment, "model_ckpt") log_dir = os.path.join(out_dir, experiment, "tb_log") os.makedirs(save_ckpt_dir, exist_ok=True) device = torch.device("cuda") dtype = torch.float32 kl_w = 0.5 if datatype == "proxd": train_dataset = ProxDataset_txt(train_data_dir, max_frame=max_frame, fix_orientation=fix_ori, step_multiplier=1, jump_step=jump_step) train_data_loader = DataLoader(train_dataset, batch_size=6, shuffle=True, num_workers=num_workers) valid_dataset = ProxDataset_txt(valid_data_dir, max_frame=max_frame, fix_orientation=fix_ori, step_multiplier=1, jump_step=jump_step) valid_data_loader = DataLoader(valid_dataset, batch_size=6, shuffle=True, num_workers=num_workers) else:
""" Running sample: python train_contactformer.py --train_data_dir ../data/proxd_train --valid_data_dir ../data/proxd_valid --fix_ori --epochs 1000 --jump_step 8 """ def train(): # Create diffusion sampler, optimizer, and trainer schedule_sampler_type = 'uniform' schedule_sampler = create_named_schedule_sampler(schedule_sampler_type, diffusion) use_fp16 = False fp16_scale_growth = 1e-3 mp_trainer = MixedPrecisionTrainer( model=model, use_fp16=use_fp16, fp16_scale_growth=fp16_scale_growth, ) optimizer = AdamW( mp_trainer.master_params, lr=lr ) model.train() torch.autograd.set_detect_anomaly(True) total_recon_loss_semantics = 0 total_semantics_recon_acc = 0 total_train_loss = 0 n_steps = 0 for mask, given_objs, given_cats, target_obj, target_cat, y in tqdm(train_data_loader): # Initialize params of the training batch # verts_can: (bs, seg_len, Nverts, 3), contacts_s: (bs, seg_len, Nverts, 8) mask = mask.to(device) given_objs = given_objs.to(device) given_cats = given_cats.to(device) target_obj = target_obj.to(device) target_cat = target_cat.to(device) t, weights = schedule_sampler.sample(target_obj.shape[0], device) # Initialize the optimizer's step mp_trainer.zero_grad() # Calculate loss compute_losses = functools.partial( diffusion.training_losses, model, target_obj, # [bs, ch, image_size, image_size] mask, t, # [bs](int) sampled timesteps given_objs, given_cats, target_cat, y=y, ) losses = compute_losses() loss = (losses["loss"] * weights).mean() total_train_loss += loss # Backward loss mp_trainer.backward(loss) mp_trainer.optimize(optimizer) # Schedule learning rate n_steps += 1 # Logging the training epoch # pr_cf: (bs, seg_len, 655, 8), mu: (bs, 256), logvar: (bs, 256) # pr_cf = sample # recon_loss_semantics, semantics_recon_acc = compute_recon_loss(gt_cf, pr_cf, mask=mask, **args_dict) # total_recon_loss_semantics += recon_loss_semantics.item() # total_semantics_recon_acc += semantics_recon_acc.item() # total_train_loss += loss.item() # total_recon_loss_semantics /= n_steps total_train_loss /= n_steps # total_semantics_recon_acc /= n_steps # writer.add_scalar('recon_loss_semantics/train', total_recon_loss_semantics, e) # writer.add_scalar('total_semantics_recon_acc/train', total_semantics_recon_acc, e) writer.add_scalar('total/train_total_loss', total_train_loss, e) print('====> Total_train_loss: {:.4f}'.format(total_train_loss)) return total_train_loss def validate(): use_ddim = False # FIXME - hardcoded clip_denoised = False # FIXME - hardcoded model.eval() with torch.no_grad(): sample_fn = ( diffusion.p_sample_loop if not use_ddim else diffusion.ddim_sample_loop ) total_recon_loss_semantics = 0 total_cfd = 0 total_acc = 0 n_steps = 0 for mask, given_objs, given_cats, target_obj, target_cat, y in tqdm(valid_data_loader): # verts_can: (bs, seg_len, Nverts, 3), contacts: (bs, seg_len, Nverts, 1), contacts_s: (bs, seg_len, Nverts, 42) mask = mask.to(device) given_objs = given_objs.to(device) given_cats = given_cats.to(device) target_obj = target_obj.to(device) target_cat = target_cat.to(device) sample = sample_fn( model, target_obj.shape, mask, given_objs, given_cats, y=y, clip_denoised=clip_denoised, model_kwargs=None, skip_timesteps=0, # 0 is the default value - i.e. don't skip any step init_image=None, progress=False, dump_steps=None, noise=None, const_noise=False, # when experimenting guidance_scale we want to nutrileze the effect of noise on generation ) # pr_cf: (bs, seg_len, 655, 43), mu: (bs, 256), logvar: (bs, 256) # z = torch.tensor(np.random.normal(0, 1, (max_frame, 256)).astype(np.float32)).to(device) # posa_out = model.posa(z, verts_can) pr_pnts = sample gt_pnts = target_obj recon_loss_semantics = ((pr_pnts-gt_pnts)**2).mean() cfd, cfd_normals = chamfer_distance(pr_pnts, gt_pnts.float().to(device)) # Calculate for categorical pred_cat = model.saved_cat pred_cat = pred_cat.squeeze(1) pred_cat = torch.argmax(pred_cat, dim=1) target_cat = torch.argmax(target_cat, dim=1) acc = (pred_cat==target_cat).sum().item() # recon_loss_semantics, semantics_recon_acc = compute_recon_loss(gt_cf, pr_cf, mask=mask, **args_dict) total_recon_loss_semantics += recon_loss_semantics total_cfd += cfd total_acc += acc n_steps += 1 total_recon_loss_semantics /= n_steps total_cfd /= n_steps total_acc /= n_steps print(n_steps) writer.add_scalar('recon_loss_semantics/validate', total_recon_loss_semantics, e) writer.add_scalar('total_cfd/validate', total_cfd, e) writer.add_scalar('total_acc/validate', total_acc, e) print( '====>Recon_loss_semantics = {:.4f} , Chamfer distance = {:.4f}, Category acc = {:.4f}'.format( total_recon_loss_semantics, total_cfd, total_acc)) return total_recon_loss_semantics, total_cfd, total_acc if __name__ == '__main__': # torch.manual_seed(0) print(torch.version.cuda) # torch.multiprocessing.set_start_method('spawn') parser = argparse.ArgumentParser(description="") parser.add_argument("--train_data_dir", type=str, default="data/proxd_train", help="path to POSA_temp dataset dir") parser.add_argument("--valid_data_dir", type=str, default="data/proxd_valid", help="path to POSA_temp dataset dir") parser.add_argument("--load_ckpt", type=str, default=None, help="load a checkpoint as the continue point for training") parser.add_argument("--posa_path", type=str, default="training/posa/model_ckpt/best_model_recon_acc.pt") parser.add_argument("--out_dir", type=str, default="training/", help="Folder that stores checkpoints and training logs") parser.add_argument("--experiment", type=str, default="default_experiment", help="Experiment name. Checkpoints and training logs will be saved in out_dir/experiment folder.") parser.add_argument("--save_interval", type=int, default=50, help="Epoch interval for saving model checkpoints.") parser.add_argument("--lr", type=float, default=1e-3) parser.add_argument("--epochs", type=int, default=1000) parser.add_argument('--fix_ori', dest='fix_ori', action='store_const', const=True, default=False, help="fix orientation of each segment with the rotation calculated from the first frame") parser.add_argument("--encoder_mode", type=int, default=1, help="Encoder mode (different number represents different variants of encoder)") parser.add_argument("--decoder_mode", type=int, default=1, help="Decoder mode (different number represents different variants of decoder)") parser.add_argument("--n_layer", type=int, default=3, help="number of layers in transformer") parser.add_argument("--n_head", type=int, default=4, help="number of heads in transformer") parser.add_argument("--dim_ff", type=int, default=512, help="dimension of hidden layers in positionwise MLP in the transformer") parser.add_argument("--f_vert", type=int, default=64, help="dimension of the embeddings for body vertices") parser.add_argument("--num_workers", type=int, default=0, help="number of workers for dataloader") parser.add_argument("--jump_step", type=int, default=8, help="frame skip size for each input motion sequence") parser.add_argument("--max_frame", type=int, default=256, help="The maximum length of motion sequence (after frame skipping) which model accepts.") parser.add_argument("--eval_epochs", type=int, default=10, help="The number of epochs that we periodically evalute the model.") parser.add_argument("--datatype", type=str, default="proxd", help="Dataset type indicator: PRO-teXt or HUMANISE.") args = parser.parse_args() args_dict = vars(args) # Parse arguments train_data_dir = args_dict['train_data_dir'] valid_data_dir = args_dict['valid_data_dir'] load_ckpt = args_dict['load_ckpt'] save_interval = args_dict['save_interval'] out_dir = args_dict['out_dir'] experiment = args_dict['experiment'] lr = args_dict['lr'] epochs = args_dict['epochs'] fix_ori = args_dict['fix_ori'] encoder_mode = args_dict['encoder_mode'] decoder_mode = args_dict['decoder_mode'] n_layer = args_dict['n_layer'] n_head = args_dict['n_head'] num_workers = args_dict['num_workers'] jump_step = args_dict['jump_step'] max_frame = args_dict['max_frame'] dim_ff = args_dict['dim_ff'] f_vert = args_dict['f_vert'] posa_path = args_dict['posa_path'] eval_epochs = args_dict['eval_epochs'] datatype = args_dict['datatype'] save_ckpt_dir = os.path.join(out_dir, experiment, "model_ckpt") log_dir = os.path.join(out_dir, experiment, "tb_log") os.makedirs(save_ckpt_dir, exist_ok=True) device = torch.device("cuda") dtype = torch.float32 kl_w = 0.5 if datatype == "proxd": train_dataset = ProxDataset_txt(train_data_dir, max_frame=max_frame, fix_orientation=fix_ori, step_multiplier=1, jump_step=jump_step) train_data_loader = DataLoader(train_dataset, batch_size=6, shuffle=True, num_workers=num_workers) valid_dataset = ProxDataset_txt(valid_data_dir, max_frame=max_frame, fix_orientation=fix_ori, step_multiplier=1, jump_step=jump_step) valid_data_loader = DataLoader(valid_dataset, batch_size=6, shuffle=True, num_workers=num_workers) else:
train_dataset = HUMANISE(train_data_dir, max_frame=max_frame, fix_orientation=fix_ori,
2
2023-11-06 07:55:51+00:00
12k
Harvard-Ophthalmology-AI-Lab/FairSeg
SAMed/segment_anything/build_sam.py
[ { "identifier": "Sam", "path": "SAMed/segment_anything/modeling/sam.py", "snippet": "class Sam(nn.Module):\n mask_threshold: float = 0.0\n image_format: str = \"RGB\"\n\n def __init__(\n self,\n image_encoder: ImageEncoderViT,\n prompt_encoder: PromptEncoder,\n mask_...
import torch from torch.nn import functional as F from icecream import ic from functools import partial from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWayTransformer
7,562
# 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(image_size, num_classes, pixel_mean=[123.675, 116.28, 103.53], pixel_std=[58.395, 57.12, 57.375], checkpoint=None): return _build_sam( encoder_embed_dim=1280, encoder_depth=32, encoder_num_heads=16, encoder_global_attn_indexes=[7, 15, 23, 31], checkpoint=checkpoint, num_classes=num_classes, image_size=image_size, pixel_mean=pixel_mean, pixel_std=pixel_std ) build_sam = build_sam_vit_h def build_sam_vit_l(image_size, num_classes, pixel_mean=[123.675, 116.28, 103.53], pixel_std=[58.395, 57.12, 57.375], checkpoint=None): return _build_sam( encoder_embed_dim=1024, encoder_depth=24, encoder_num_heads=16, encoder_global_attn_indexes=[5, 11, 17, 23], checkpoint=checkpoint, num_classes=num_classes, image_size=image_size, pixel_mean=pixel_mean, pixel_std=pixel_std ) def build_sam_vit_b(image_size, num_classes, pixel_mean=[123.675, 116.28, 103.53], pixel_std=[58.395, 57.12, 57.375], checkpoint=None): return _build_sam( encoder_embed_dim=768, encoder_depth=12, encoder_num_heads=12, encoder_global_attn_indexes=[2, 5, 8, 11], # adopt global attention at [3, 6, 9, 12] transform layer, else window attention layer checkpoint=checkpoint, num_classes=num_classes, image_size=image_size, pixel_mean=pixel_mean, pixel_std=pixel_std ) sam_model_registry = { "default": build_sam_vit_h, "vit_h": build_sam_vit_h, "vit_l": build_sam_vit_l, "vit_b": build_sam_vit_b, } def _build_sam( encoder_embed_dim, encoder_depth, encoder_num_heads, encoder_global_attn_indexes, num_classes, image_size, pixel_mean, pixel_std, checkpoint=None, ): prompt_embed_dim = 256 image_size = image_size vit_patch_size = 16 image_embedding_size = image_size // vit_patch_size # Divide by 16 here sam = Sam( image_encoder=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, ),
# 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(image_size, num_classes, pixel_mean=[123.675, 116.28, 103.53], pixel_std=[58.395, 57.12, 57.375], checkpoint=None): return _build_sam( encoder_embed_dim=1280, encoder_depth=32, encoder_num_heads=16, encoder_global_attn_indexes=[7, 15, 23, 31], checkpoint=checkpoint, num_classes=num_classes, image_size=image_size, pixel_mean=pixel_mean, pixel_std=pixel_std ) build_sam = build_sam_vit_h def build_sam_vit_l(image_size, num_classes, pixel_mean=[123.675, 116.28, 103.53], pixel_std=[58.395, 57.12, 57.375], checkpoint=None): return _build_sam( encoder_embed_dim=1024, encoder_depth=24, encoder_num_heads=16, encoder_global_attn_indexes=[5, 11, 17, 23], checkpoint=checkpoint, num_classes=num_classes, image_size=image_size, pixel_mean=pixel_mean, pixel_std=pixel_std ) def build_sam_vit_b(image_size, num_classes, pixel_mean=[123.675, 116.28, 103.53], pixel_std=[58.395, 57.12, 57.375], checkpoint=None): return _build_sam( encoder_embed_dim=768, encoder_depth=12, encoder_num_heads=12, encoder_global_attn_indexes=[2, 5, 8, 11], # adopt global attention at [3, 6, 9, 12] transform layer, else window attention layer checkpoint=checkpoint, num_classes=num_classes, image_size=image_size, pixel_mean=pixel_mean, pixel_std=pixel_std ) sam_model_registry = { "default": build_sam_vit_h, "vit_h": build_sam_vit_h, "vit_l": build_sam_vit_l, "vit_b": build_sam_vit_b, } def _build_sam( encoder_embed_dim, encoder_depth, encoder_num_heads, encoder_global_attn_indexes, num_classes, image_size, pixel_mean, pixel_std, checkpoint=None, ): prompt_embed_dim = 256 image_size = image_size vit_patch_size = 16 image_embedding_size = image_size // vit_patch_size # Divide by 16 here sam = Sam( image_encoder=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, ),
prompt_encoder=PromptEncoder(
3
2023-11-03 17:05:40+00:00
12k
microsoft/PLEX
PLEX/util/evaluators.py
[ { "identifier": "DEFAULT_CAM", "path": "PLEX/envs/environments.py", "snippet": "DEFAULT_CAM = {'robosuite': 'agentview',\n 'metaworld': 'corner',\n 'd4rl': None}" }, { "identifier": "RobosuiteEnv", "path": "PLEX/envs/environments.py", "snippet": "class Robosui...
import os import time import math import random import numpy as np import torch import torch.multiprocessing as mp import robomimic.utils.obs_utils as ObsUtils import cv2 import PLEX.util.globals as globals import d4rl import moviepy.editor as mpy from copy import deepcopy from PLEX.envs.environments import DEFAULT_CAM, RobosuiteEnv, MetaWorldEnv, d4rlEnv, init_obs_preprocessing, unprocess_image from PLEX.models.trajectory_models.plex import PLEX from PLEX.util.data import setup_context_sampler, setup_batch_sampler, discount_cumsum from PLEX.util.misc import parse_comma_sep_param_value, construct_rewards, setup_trainer
10,243
def evaluate_episode( task, model, ep_id, use_normalized_reward=False, reward_type='native', env_meta=None, min_time_at_goal_for_success=5, camera_names=None, image_size=84, device='cuda', max_ep_len=500, discount=1., full_state_mode=False, context=None, target_return=None, record_camera=None, write_individual_images=False, record_traj_dir=None ): if not full_state_mode: # Make sure ObsUtils is set up (each process has to run this once) # # Actually, do we need this, given that it's done by the top-level module? # Presumably, it doesn't hurt... if ObsUtils.OBS_KEYS_TO_MODALITIES is None: init_obs_preprocessing(camera_names, image_size) image_obs_list = [] if task.dataset_type in {'robosuite', 'robomimic'}: # Choosing a GPU for each episode in this way prevents all evluation env instances from running on the same GPU and potentially causing an OOM error. render_device = ep_id % torch.cuda.device_count() if device == 'cuda' else -1 if env_meta is not None and 'robosuite' in env_meta: env_meta['robosuite']['env_kwargs']['render_gpu_device_id'] = render_device env = RobosuiteEnv(task, use_normalized_reward, full_state_mode, env_meta=(env_meta['robosuite'] if env_meta is not None and 'robosuite' in env_meta else None), render_gpu_device_id=render_device, camera_names=camera_names, image_size=image_size) elif task.dataset_type == 'metaworld': env = MetaWorldEnv(task, use_normalized_reward, full_state_mode, env_meta=env_meta['metaworld'] if env_meta is not None and 'metaworld' in env_meta else None, steps_at_goal=min_time_at_goal_for_success, #render_gpu_device_id=render_device, camera_name=camera_names[0], image_size=image_size) elif task.dataset_type == 'd4rl':
def evaluate_episode( task, model, ep_id, use_normalized_reward=False, reward_type='native', env_meta=None, min_time_at_goal_for_success=5, camera_names=None, image_size=84, device='cuda', max_ep_len=500, discount=1., full_state_mode=False, context=None, target_return=None, record_camera=None, write_individual_images=False, record_traj_dir=None ): if not full_state_mode: # Make sure ObsUtils is set up (each process has to run this once) # # Actually, do we need this, given that it's done by the top-level module? # Presumably, it doesn't hurt... if ObsUtils.OBS_KEYS_TO_MODALITIES is None: init_obs_preprocessing(camera_names, image_size) image_obs_list = [] if task.dataset_type in {'robosuite', 'robomimic'}: # Choosing a GPU for each episode in this way prevents all evluation env instances from running on the same GPU and potentially causing an OOM error. render_device = ep_id % torch.cuda.device_count() if device == 'cuda' else -1 if env_meta is not None and 'robosuite' in env_meta: env_meta['robosuite']['env_kwargs']['render_gpu_device_id'] = render_device env = RobosuiteEnv(task, use_normalized_reward, full_state_mode, env_meta=(env_meta['robosuite'] if env_meta is not None and 'robosuite' in env_meta else None), render_gpu_device_id=render_device, camera_names=camera_names, image_size=image_size) elif task.dataset_type == 'metaworld': env = MetaWorldEnv(task, use_normalized_reward, full_state_mode, env_meta=env_meta['metaworld'] if env_meta is not None and 'metaworld' in env_meta else None, steps_at_goal=min_time_at_goal_for_success, #render_gpu_device_id=render_device, camera_name=camera_names[0], image_size=image_size) elif task.dataset_type == 'd4rl':
env = d4rlEnv(task, full_state_mode)
3
2023-11-06 09:38:09+00:00
12k
Giftify-Bot/Giftify-Bot
models/giveaways.py
[ { "identifier": "ChannelConfig", "path": "models/giveaway_settings.py", "snippet": "class ChannelConfig:\n \"\"\"Represents the configuration settings for a channel.\n\n Attributes\n ----------\n channel: Union[discord.TextChannel, discord.CategoryChannel]\n The channel associated wit...
import contextlib import datetime import random import asyncpg import discord from enum import Enum from typing import TYPE_CHECKING, Dict, List, Optional from models.giveaway_settings import ChannelConfig, GuildConfig from utils.constants import GIFT_EMOJI from utils.exceptions import GiveawayError from utils.functions import bold, safe_format from utils.tree import Interaction from utils.view import BaseView, GiveawayView from bot import Giftify
7,253
self.bypass_roles: List[int] = record["bypass_roles"] or [] self.multiplier_roles: Dict[int, int] = { int(role): entries for role, entries in record["multiplier_roles"].items() if entries > 1 } self.messages: Dict[int, int] = { int(member): messages for member, messages in record["messages"].items() } self.messages_required: Optional[int] = record["messages_required"] self.allowed_message_channels: Optional[List[int]] = record["messages_channel"] self.amari: Optional[int] = record["amari"] self.weekly_amari: Optional[int] = record["weekly_amari"] def __eq__(self, other: "Giveaway") -> bool: try: return ( self.guild_id == other.guild_id and self.channel_id == other.channel_id and self.message_id == other.message_id ) except AttributeError: return False def __hash__(self) -> int: return hash((self.guild_id, self.channel_id, self.message_id)) def __repr__(self) -> str: return f"<Giveaway guild_id={self.guild_id} channel_id={self.channel_id} message_id={self.message_id}>" @property def jump_to_giveaway(self) -> discord.ui.View: url = f"https://discord.com/channels/{self.guild_id}/{self.channel_id}/{self.message_id}" view = BaseView(timeout=None) button = discord.ui.Button(label="Jump To Giveaway", url=url) view.add_item(button) return view @staticmethod def create_embed( interaction: Interaction, config: GuildConfig, duration: datetime.datetime, winners: int, prize: str, required_roles: Optional[List[discord.Role]] = None, blacklisted_roles: Optional[List[discord.Role]] = None, bypass_roles: Optional[List[discord.Role]] = None, multiplier_roles: Optional[Dict[discord.Role, int]] = None, messages_required: Optional[int] = None, allowed_message_channels: Optional[List[discord.TextChannel]] = None, amari: Optional[int] = None, weekly_amari: Optional[int] = None, donor: Optional[discord.Member] = None, ) -> discord.Embed: assert interaction.guild is not None description = f"Click the {config.reaction} button to join the giveaway!\n" description += f"Hosted By: {interaction.user.mention}\n" if donor: description += f"Donor: {donor.mention}\n" description += f"Ends: {discord.utils.format_dt(duration, style='R')} ({discord.utils.format_dt(duration, style='f')})\n" embed = discord.Embed( title=prize, description=description, colour=config.color, timestamp=duration, ) embed.set_footer( text=f"{winners} winner(s) • Ends", icon_url=interaction.guild.icon or interaction.client.user.display_avatar, ) requirements = "" if required_roles: requirements += f"Required Roles: {', '.join(role.mention for role in required_roles if role is not None)}\n" if bypass_roles: requirements += f"Bypass Roles: {', '.join(role.mention for role in bypass_roles if role is not None)}\n" if blacklisted_roles: requirements += f"Blacklisted Roles: {', '.join(role.mention for role in blacklisted_roles if role is not None)}\n" if messages_required: requirements += ( f"Messages Required: **{messages_required}** message(s) (5s cooldown)\n" ) if allowed_message_channels: requirements += f"Allowed Channels: {', '.join(f'<#{c.id}>' for c in allowed_message_channels)}\n" if amari: requirements += f"Amari Level: {amari}\n" if weekly_amari: requirements += f"Weekly Amari: {weekly_amari} XP Points\n" if requirements: embed.add_field(name="Requirements", value=requirements, inline=False) if multiplier_roles: multiplier_roles_mention = "\n".join( [ f"- {entry}x ・ {role.mention}" for role, entry in multiplier_roles.items() if role is not None ] ) embed.add_field( name="Bonus Entries", value=multiplier_roles_mention, inline=False ) return embed @classmethod async def start( cls, interaction: Interaction, duration: datetime.datetime, winners: int, prize: str, config: GuildConfig,
from __future__ import annotations if TYPE_CHECKING: class Giveaway: """ Represents a giveaway object. Attributes ---------- bot: Giftify The bot instance to handle the giveaway. guild_id: int The ID of the guild (server) where the giveaway is hosted. channel_id: int The ID of the channel where the giveaway is hosted. message_id: int The ID of the giveaway message. extra_message_id: int The ID of the extra message with giveaway. host_id: int The ID of the user hosting the giveaway. donor_id: int The ID of the user donating for the giveaway. prize: int The prize of the giveaway. winner_count: int The number of winners for the giveaway. winners: List[int] The winners of the giveaway. participants: List[int] The IDs participants for the giveaway. ended: bool Indicates whether the giveaway has ended. ends: datetime.datetime The timestamp when the giveaway will be ended. required_roles: List[int] The list of role IDs required to participate in the giveaway. blacklisted_roles: List[int] The list of role IDs excluded from participating in the giveaway. bypass_roles: List[int] The list of user IDs exempted from giveaway restrictions. multiplier_roles: Optional[dict] A dictionary containing multiplier_roles criteria for the giveaway. messages: Optional[dict] A dictionary containing message-based criteria for the giveaway. messages_required: Optional[int] The number of messages required to participate in the giveaway. allowed_message_channels: Optional[List[int]] The ID of the channels where the message count is tracked. amari: Optional[int] The required Amari XP to participate in the giveaway. weekly_amari: Optional[int] The required weekly Amari XP to participate in the giveaway. """ __slots__ = ( "bot", "guild_id", "channel_id", "message_id", "extra_message_id", "prize", "host_id", "donor_id", "winner_count", "winners", "participants", "ended", "ends", "required_roles", "blacklisted_roles", "bypass_roles", "multiplier_roles", "messages", "messages_required", "allowed_message_channels", "amari", "weekly_amari", ) def __init__(self, *, bot: Giftify, record: asyncpg.Record): self.bot = bot self.guild_id: int = record["guild"] self.channel_id: int = record["channel"] self.message_id: int = record["message"] self.extra_message_id: int = record["extra_message"] self.prize: str = record["prize"] self.host_id: int = record["host"] self.donor_id: Optional[int] = record["donor"] self.winner_count: int = record["winner_count"] self.winners: List[int] = record["winners"] self.participants: List[int] = record["participants"] self.ended: bool = record["ended"] self.ends: datetime.datetime = record["ends"] self.required_roles: List[int] = record["required_roles"] or [] self.blacklisted_roles: List[int] = record["blacklisted_roles"] or [] self.bypass_roles: List[int] = record["bypass_roles"] or [] self.multiplier_roles: Dict[int, int] = { int(role): entries for role, entries in record["multiplier_roles"].items() if entries > 1 } self.messages: Dict[int, int] = { int(member): messages for member, messages in record["messages"].items() } self.messages_required: Optional[int] = record["messages_required"] self.allowed_message_channels: Optional[List[int]] = record["messages_channel"] self.amari: Optional[int] = record["amari"] self.weekly_amari: Optional[int] = record["weekly_amari"] def __eq__(self, other: "Giveaway") -> bool: try: return ( self.guild_id == other.guild_id and self.channel_id == other.channel_id and self.message_id == other.message_id ) except AttributeError: return False def __hash__(self) -> int: return hash((self.guild_id, self.channel_id, self.message_id)) def __repr__(self) -> str: return f"<Giveaway guild_id={self.guild_id} channel_id={self.channel_id} message_id={self.message_id}>" @property def jump_to_giveaway(self) -> discord.ui.View: url = f"https://discord.com/channels/{self.guild_id}/{self.channel_id}/{self.message_id}" view = BaseView(timeout=None) button = discord.ui.Button(label="Jump To Giveaway", url=url) view.add_item(button) return view @staticmethod def create_embed( interaction: Interaction, config: GuildConfig, duration: datetime.datetime, winners: int, prize: str, required_roles: Optional[List[discord.Role]] = None, blacklisted_roles: Optional[List[discord.Role]] = None, bypass_roles: Optional[List[discord.Role]] = None, multiplier_roles: Optional[Dict[discord.Role, int]] = None, messages_required: Optional[int] = None, allowed_message_channels: Optional[List[discord.TextChannel]] = None, amari: Optional[int] = None, weekly_amari: Optional[int] = None, donor: Optional[discord.Member] = None, ) -> discord.Embed: assert interaction.guild is not None description = f"Click the {config.reaction} button to join the giveaway!\n" description += f"Hosted By: {interaction.user.mention}\n" if donor: description += f"Donor: {donor.mention}\n" description += f"Ends: {discord.utils.format_dt(duration, style='R')} ({discord.utils.format_dt(duration, style='f')})\n" embed = discord.Embed( title=prize, description=description, colour=config.color, timestamp=duration, ) embed.set_footer( text=f"{winners} winner(s) • Ends", icon_url=interaction.guild.icon or interaction.client.user.display_avatar, ) requirements = "" if required_roles: requirements += f"Required Roles: {', '.join(role.mention for role in required_roles if role is not None)}\n" if bypass_roles: requirements += f"Bypass Roles: {', '.join(role.mention for role in bypass_roles if role is not None)}\n" if blacklisted_roles: requirements += f"Blacklisted Roles: {', '.join(role.mention for role in blacklisted_roles if role is not None)}\n" if messages_required: requirements += ( f"Messages Required: **{messages_required}** message(s) (5s cooldown)\n" ) if allowed_message_channels: requirements += f"Allowed Channels: {', '.join(f'<#{c.id}>' for c in allowed_message_channels)}\n" if amari: requirements += f"Amari Level: {amari}\n" if weekly_amari: requirements += f"Weekly Amari: {weekly_amari} XP Points\n" if requirements: embed.add_field(name="Requirements", value=requirements, inline=False) if multiplier_roles: multiplier_roles_mention = "\n".join( [ f"- {entry}x ・ {role.mention}" for role, entry in multiplier_roles.items() if role is not None ] ) embed.add_field( name="Bonus Entries", value=multiplier_roles_mention, inline=False ) return embed @classmethod async def start( cls, interaction: Interaction, duration: datetime.datetime, winners: int, prize: str, config: GuildConfig,
channel_config: Optional[ChannelConfig],
0
2023-11-09 15:00:15+00:00
12k
Zjy0401/CoCoFormer
model/CoCoFormer.py
[ { "identifier": "get_device", "path": "utilities/device.py", "snippet": "def get_device():\n\n if((not USE_CUDA) or (TORCH_CUDA_DEVICE is None)):\n return TORCH_CPU_DEVICE\n else:\n return TORCH_CUDA_DEVICE" }, { "identifier": "PositionalEncoding", "path": "model/position...
import torch import torch.nn as nn import random import pickle from torch.nn.modules.normalization import LayerNorm from utilities.constants import * from utilities.device import get_device from tqdm import tqdm from .positional_encoding import PositionalEncoding from .rpr import TransformerEncoderRPR, TransformerEncoderLayerRPR, TransformerEncoderLayerRPR_, \ TransformerEncoderPastLayer, TransformerEncoderLayer, TransformerEncoder from typing import Dict, Iterable, Callable from torch.nn.init import * from utilities.argument_funcs import parse_train_args, print_train_args, write_model_params
7,954
# MusicTransformer class CoCoformer(nn.Module): def __init__(self, word2event, event2word, n_layers=6, num_heads=8, d_model=512, dim_feedforward=1024, dropout=0.1, max_sequence=2048, c_max_seq=256, b_max_seq=1024, rpr=False): super(CoCoformer, self).__init__() self.dummy = DummyDecoder() self.nlayers = n_layers self.nhead = num_heads self.d_model = d_model self.d_ff = dim_feedforward self.dropout = dropout self.max_seq = max_sequence self.c_max_seq = c_max_seq self.b_max_seq = b_max_seq self.rpr = rpr # word2event and event2word: self.word2event = word2event self.event2word = event2word # past layer of chord self.cpast_layer_dmodel = d_model self.cpast_layer_nhead = 8 self.cpast_dim_forward = 256 self.cpast_layer_max_seq = 256 self.cpast_layer_nlayers = 1 # past layer of beats self.bpast_layer_dmodel = d_model self.bpast_layer_nhead = 8 self.bpast_dim_forward = 256 self.bpast_layer_max_seq = 1024 self.bpast_layer_nlayers = 1 # Input embedding self.n_embedding = nn.Embedding(VOCAB_SIZE, self.d_model) self.c_embedding = nn.Embedding(VOCAB_SIZE, self.cpast_layer_dmodel) self.b_embedding = nn.Embedding(VOCAB_SIZE, self.bpast_layer_dmodel) # Positional encoding self.n_positional_encoding = PositionalEncoding(self.d_model, self.dropout, self.max_seq) self.c_positional_encoding = PositionalEncoding(self.cpast_layer_dmodel, self.dropout, self.cpast_layer_max_seq) self.b_positional_encoding = PositionalEncoding(self.bpast_layer_dmodel, self.dropout, self.bpast_layer_max_seq) # Base transformer if not self.rpr: # To make a decoder-only transformer we need to use masked encoder layers # Dummy decoder to essentially just return the encoder output encoder_norm = LayerNorm(self.d_model) encoder_past_layer = TransformerEncoderPastLayer(self.cpast_layer_dmodel, self.cpast_layer_nhead, self.cpast_dim_forward, self.bpast_layer_dmodel, self.bpast_layer_nhead, self.bpast_dim_forward, self.d_model, self.nhead, self.d_ff, self.dropout) encoder_layer = TransformerEncoderLayer(self.d_model, self.nhead, self.d_ff, self.dropout) encoder = TransformerEncoder(encoder_layer, self.nlayers, encoder_past_layer, self.max_seq, self.c_max_seq, self.b_max_seq, encoder_norm) self.transformer = nn.Transformer( d_model=self.d_model, nhead=self.nhead, num_encoder_layers=self.nlayers, num_decoder_layers=0, dropout=self.dropout, # activation=self.ff_activ, dim_feedforward=self.d_ff, custom_encoder=encoder, custom_decoder=self.dummy ) # RPR Transformer elif self.rpr: encoder_norm = LayerNorm(self.d_model) encoder_layer = TransformerEncoderLayerRPR(self.d_model, self.nhead, self.d_ff, self.dropout, er_len=self.max_seq) encoder_past_layer = TransformerEncoderLayerRPR_(self.cpast_layer_dmodel, self.cpast_layer_nhead, self.cpast_dim_forward, self.bpast_layer_dmodel, self.bpast_layer_nhead, self.bpast_dim_forward, self.d_model, self.nhead, self.d_ff, self.dropout, er_len=self.max_seq) encoder = TransformerEncoderRPR(encoder_layer, self.nlayers, encoder_past_layer, self.max_seq, self.c_max_seq, self.b_max_seq, encoder_norm) self.transformer = nn.Transformer( d_model=self.d_model, nhead=self.nhead, num_encoder_layers=self.nlayers, num_decoder_layers=0, dropout=self.dropout, # activation=self.ff_activ, dim_feedforward=self.d_ff, custom_decoder=self.dummy, custom_encoder=encoder ) # Final output is a softmaxed linear layer # TODO: verify the size of linear self.Norm1 = nn.LayerNorm(1024) self.ReLU = nn.ReLU() self.Norm2 = nn.LayerNorm(181) self.Dropout = nn.Dropout(dropout) self.transLinear = nn.Linear(256, 256) self.Wout1 = nn.Linear(self.d_model, 1024) self.Wout2 = nn.Linear(1024, 1024) self.Wout3 = nn.Linear(1024, VOCAB_SIZE) self.softmax = nn.Softmax(dim=-1) def _reset_parameters(self): r"""Initiate parameters in the transformer model.""" for p in self.parameters(): if p.dim() > 1: xavier_uniform_(p) # forward def forward(self, x1, x2, x3, mask=True):
# MusicTransformer class CoCoformer(nn.Module): def __init__(self, word2event, event2word, n_layers=6, num_heads=8, d_model=512, dim_feedforward=1024, dropout=0.1, max_sequence=2048, c_max_seq=256, b_max_seq=1024, rpr=False): super(CoCoformer, self).__init__() self.dummy = DummyDecoder() self.nlayers = n_layers self.nhead = num_heads self.d_model = d_model self.d_ff = dim_feedforward self.dropout = dropout self.max_seq = max_sequence self.c_max_seq = c_max_seq self.b_max_seq = b_max_seq self.rpr = rpr # word2event and event2word: self.word2event = word2event self.event2word = event2word # past layer of chord self.cpast_layer_dmodel = d_model self.cpast_layer_nhead = 8 self.cpast_dim_forward = 256 self.cpast_layer_max_seq = 256 self.cpast_layer_nlayers = 1 # past layer of beats self.bpast_layer_dmodel = d_model self.bpast_layer_nhead = 8 self.bpast_dim_forward = 256 self.bpast_layer_max_seq = 1024 self.bpast_layer_nlayers = 1 # Input embedding self.n_embedding = nn.Embedding(VOCAB_SIZE, self.d_model) self.c_embedding = nn.Embedding(VOCAB_SIZE, self.cpast_layer_dmodel) self.b_embedding = nn.Embedding(VOCAB_SIZE, self.bpast_layer_dmodel) # Positional encoding self.n_positional_encoding = PositionalEncoding(self.d_model, self.dropout, self.max_seq) self.c_positional_encoding = PositionalEncoding(self.cpast_layer_dmodel, self.dropout, self.cpast_layer_max_seq) self.b_positional_encoding = PositionalEncoding(self.bpast_layer_dmodel, self.dropout, self.bpast_layer_max_seq) # Base transformer if not self.rpr: # To make a decoder-only transformer we need to use masked encoder layers # Dummy decoder to essentially just return the encoder output encoder_norm = LayerNorm(self.d_model) encoder_past_layer = TransformerEncoderPastLayer(self.cpast_layer_dmodel, self.cpast_layer_nhead, self.cpast_dim_forward, self.bpast_layer_dmodel, self.bpast_layer_nhead, self.bpast_dim_forward, self.d_model, self.nhead, self.d_ff, self.dropout) encoder_layer = TransformerEncoderLayer(self.d_model, self.nhead, self.d_ff, self.dropout) encoder = TransformerEncoder(encoder_layer, self.nlayers, encoder_past_layer, self.max_seq, self.c_max_seq, self.b_max_seq, encoder_norm) self.transformer = nn.Transformer( d_model=self.d_model, nhead=self.nhead, num_encoder_layers=self.nlayers, num_decoder_layers=0, dropout=self.dropout, # activation=self.ff_activ, dim_feedforward=self.d_ff, custom_encoder=encoder, custom_decoder=self.dummy ) # RPR Transformer elif self.rpr: encoder_norm = LayerNorm(self.d_model) encoder_layer = TransformerEncoderLayerRPR(self.d_model, self.nhead, self.d_ff, self.dropout, er_len=self.max_seq) encoder_past_layer = TransformerEncoderLayerRPR_(self.cpast_layer_dmodel, self.cpast_layer_nhead, self.cpast_dim_forward, self.bpast_layer_dmodel, self.bpast_layer_nhead, self.bpast_dim_forward, self.d_model, self.nhead, self.d_ff, self.dropout, er_len=self.max_seq) encoder = TransformerEncoderRPR(encoder_layer, self.nlayers, encoder_past_layer, self.max_seq, self.c_max_seq, self.b_max_seq, encoder_norm) self.transformer = nn.Transformer( d_model=self.d_model, nhead=self.nhead, num_encoder_layers=self.nlayers, num_decoder_layers=0, dropout=self.dropout, # activation=self.ff_activ, dim_feedforward=self.d_ff, custom_decoder=self.dummy, custom_encoder=encoder ) # Final output is a softmaxed linear layer # TODO: verify the size of linear self.Norm1 = nn.LayerNorm(1024) self.ReLU = nn.ReLU() self.Norm2 = nn.LayerNorm(181) self.Dropout = nn.Dropout(dropout) self.transLinear = nn.Linear(256, 256) self.Wout1 = nn.Linear(self.d_model, 1024) self.Wout2 = nn.Linear(1024, 1024) self.Wout3 = nn.Linear(1024, VOCAB_SIZE) self.softmax = nn.Softmax(dim=-1) def _reset_parameters(self): r"""Initiate parameters in the transformer model.""" for p in self.parameters(): if p.dim() > 1: xavier_uniform_(p) # forward def forward(self, x1, x2, x3, mask=True):
args = parse_train_args()
8
2023-11-01 08:33:08+00:00
12k
serl-robot/serl
serl/agents/vice/vice_learner.py
[ { "identifier": "batched_random_crop", "path": "serl/utils/augmentations.py", "snippet": "def batched_random_crop(key, obs, pixel_key, padding=4):\n imgs = obs[pixel_key]\n keys = jax.random.split(key, imgs.shape[0])\n imgs = jax.vmap(random_crop, (0, 0, None))(keys, imgs, padding)\n return ...
from functools import partial from itertools import zip_longest from typing import Callable, Dict, Optional, Sequence, Tuple, OrderedDict from collections import OrderedDict from jax import numpy as jnp from flax import struct from flax.core import FrozenDict, freeze from flax.training.train_state import TrainState from serl.utils.augmentations import batched_random_crop from serl.agents.sac.sac_learner import SACLearner from serl.agents.drq.drq_learner import DrQLearner from serl.agents.sac.temperature import Temperature from serl.data.dataset import DatasetDict from serl.distributions import TanhNormal from serl.networks import MLP, Ensemble, PixelMultiplexer, StateActionValue from serl.networks.encoders import TwoMobileNetEncoder, MobileNetEncoder, TwoD4PGEncoder from serl.networks.encoded_encoder import EncodedEncoder from serl.networks.one_d_output import OneDimOutput from serl.utils.commons import _unpack, _share_encoder from jeffnet.linen import create_model, EfficientNet import gym import jax import optax import flax.linen as nn
8,215
"""Implementations of algorithms for continuous control.""" class VICELearner(DrQLearner): vice_classifiers: OrderedDict[str, TrainState] vice_label_smoothing: float vice_goal_pool: jnp.ndarray vice_encoder: TrainState vice_encoder_params: FrozenDict @classmethod def create( cls, seed: int, observation_space: gym.Space, action_space: gym.Space, actor_lr: float = 3e-4, critic_lr: float = 3e-4, vice_lr: float = 3e-4, temp_lr: float = 3e-4, cnn_features: Sequence[int] = (32, 32, 32, 32), cnn_filters: Sequence[int] = (3, 3, 3, 3), cnn_strides: Sequence[int] = (2, 1, 1, 1), cnn_padding: str = "VALID", latent_dim: int = 50, encoder: str = "d4pg", hidden_dims: Sequence[int] = (256, 256), discount: float = 0.99, tau: float = 0.005, num_qs: int = 2, num_min_qs: Optional[int] = None, critic_dropout_rate: Optional[float] = None, vice_dropout_rate: Optional[float] = None, vice_label_smoothing: float = 0.1, critic_layer_norm: bool = False, target_entropy: Optional[float] = None, init_temperature: float = 1.0, backup_entropy: bool = True, pixel_keys: Tuple[str, ...] = ("pixels",), depth_keys: Tuple[str, ...] = (), vice_goal_pool: jnp.ndarray = None ): """ An implementation of the version of Soft-Actor-Critic described in https://arxiv.org/abs/1812.05905 """ action_dim = action_space.shape[-1] observations = observation_space.sample() actions = action_space.sample() if target_entropy is None: target_entropy = -action_dim rng = jax.random.PRNGKey(seed) rng, actor_key, critic_key, temp_key, vice_encoder_key = jax.random.split(rng, 5) rng_vice_keys = jax.random.split(rng, 1 + len(pixel_keys)) rng, vice_keys = rng_vice_keys[0], rng_vice_keys[1:] if encoder == "d4pg": encoder_cls = partial( TwoD4PGEncoder, features=cnn_features, filters=cnn_filters, strides=cnn_strides, padding=cnn_padding, ) elif encoder == "resnet": raise NotImplementedError elif encoder == "mobilenet": MobileNet, mobilenet_variables = create_model('tf_mobilenetv3_large_100', pretrained=True) encoder_cls = partial(TwoMobileNetEncoder, mobilenet=MobileNet, params=mobilenet_variables) actor_base_cls = partial(MLP, hidden_dims=hidden_dims, activate_final=True) actor_cls = partial(TanhNormal, base_cls=actor_base_cls, action_dim=action_dim)
"""Implementations of algorithms for continuous control.""" class VICELearner(DrQLearner): vice_classifiers: OrderedDict[str, TrainState] vice_label_smoothing: float vice_goal_pool: jnp.ndarray vice_encoder: TrainState vice_encoder_params: FrozenDict @classmethod def create( cls, seed: int, observation_space: gym.Space, action_space: gym.Space, actor_lr: float = 3e-4, critic_lr: float = 3e-4, vice_lr: float = 3e-4, temp_lr: float = 3e-4, cnn_features: Sequence[int] = (32, 32, 32, 32), cnn_filters: Sequence[int] = (3, 3, 3, 3), cnn_strides: Sequence[int] = (2, 1, 1, 1), cnn_padding: str = "VALID", latent_dim: int = 50, encoder: str = "d4pg", hidden_dims: Sequence[int] = (256, 256), discount: float = 0.99, tau: float = 0.005, num_qs: int = 2, num_min_qs: Optional[int] = None, critic_dropout_rate: Optional[float] = None, vice_dropout_rate: Optional[float] = None, vice_label_smoothing: float = 0.1, critic_layer_norm: bool = False, target_entropy: Optional[float] = None, init_temperature: float = 1.0, backup_entropy: bool = True, pixel_keys: Tuple[str, ...] = ("pixels",), depth_keys: Tuple[str, ...] = (), vice_goal_pool: jnp.ndarray = None ): """ An implementation of the version of Soft-Actor-Critic described in https://arxiv.org/abs/1812.05905 """ action_dim = action_space.shape[-1] observations = observation_space.sample() actions = action_space.sample() if target_entropy is None: target_entropy = -action_dim rng = jax.random.PRNGKey(seed) rng, actor_key, critic_key, temp_key, vice_encoder_key = jax.random.split(rng, 5) rng_vice_keys = jax.random.split(rng, 1 + len(pixel_keys)) rng, vice_keys = rng_vice_keys[0], rng_vice_keys[1:] if encoder == "d4pg": encoder_cls = partial( TwoD4PGEncoder, features=cnn_features, filters=cnn_filters, strides=cnn_strides, padding=cnn_padding, ) elif encoder == "resnet": raise NotImplementedError elif encoder == "mobilenet": MobileNet, mobilenet_variables = create_model('tf_mobilenetv3_large_100', pretrained=True) encoder_cls = partial(TwoMobileNetEncoder, mobilenet=MobileNet, params=mobilenet_variables) actor_base_cls = partial(MLP, hidden_dims=hidden_dims, activate_final=True) actor_cls = partial(TanhNormal, base_cls=actor_base_cls, action_dim=action_dim)
actor_def = PixelMultiplexer(
8
2023-11-02 23:32:24+00:00
12k
tiendatnguyen-vision/Orbit-symmetrize
RotatedMNIST/LPS/emlp-pytorch/emlp_pytorch/reps/representation.py
[ { "identifier": "Group", "path": "RotatedMNIST/LPS/emlp-pytorch/emlp_pytorch/groups.py", "snippet": "class Group(nn.Module):\n \"\"\" Abstract Group Object which new groups should inherit from. \"\"\"\n\n def __init__(self):\n super().__init__()\n self.lie_algebra = NotImplemented #...
import math import logging import itertools import torch from functools import lru_cache as cache, reduce from collections import defaultdict from plum import dispatch from torch import nn from ..groups import Group from .linear_operator_base import LinearOperator from .linear_operators import ConcatLazy, I, lazify, densify, LazyJVP, LazyPerm, \ LazyDirectSum, LazyKron, LazyKronsum, lazy_direct_matmat, product from .utils import orthogonal_complement, krylov_constraint_solve, get_device
9,066
""" The base Representation class. """ class Rep(nn.Module): """ The base Representation class. Representation objects formalize the vector space V on which the group acts, the group representation matrix ρ(g), and the Lie Algebra representation dρ(A) in a single object. Representations act as types for vectors coming from V. These types can be manipulated and transformed with the built in operators ⊕,⊗,dual, as well as incorporating custom representations. Representation objects should be immutable. At minimum, new representations need to implement ``rho``, ``__str__``.""" def __init__(self): super().__init__() self.is_permutation = False self._size = None self.G = None def rho(self, M): """ Group representation of the matrix M of shape (d,d)""" raise NotImplementedError def drho(self, A): """ Lie Algebra representation of the matrix A of shape (d,d)""" In = torch.eye(A.size(0), dtype=A.dtype, device=A.device)
""" The base Representation class. """ class Rep(nn.Module): """ The base Representation class. Representation objects formalize the vector space V on which the group acts, the group representation matrix ρ(g), and the Lie Algebra representation dρ(A) in a single object. Representations act as types for vectors coming from V. These types can be manipulated and transformed with the built in operators ⊕,⊗,dual, as well as incorporating custom representations. Representation objects should be immutable. At minimum, new representations need to implement ``rho``, ``__str__``.""" def __init__(self): super().__init__() self.is_permutation = False self._size = None self.G = None def rho(self, M): """ Group representation of the matrix M of shape (d,d)""" raise NotImplementedError def drho(self, A): """ Lie Algebra representation of the matrix A of shape (d,d)""" In = torch.eye(A.size(0), dtype=A.dtype, device=A.device)
return LazyJVP(self.rho, In, A)
6
2023-11-01 07:19:02+00:00
12k
xenxxxx/BitPay-Crypto-Signal-Trading-Bot
tests/conftest.py
[ { "identifier": "leverage_trade", "path": "tests/conftest_trades.py", "snippet": "def leverage_trade(fee):\n \"\"\"\n 5 hour short limit trade on kraken\n\n Short trade\n fee: 0.25% base\n interest_rate: 0.05% per day\n open_rate: 0.123 base\n close_rate: 0.128 b...
import json import logging import re import numpy as np import pandas as pd import pytest import builtins from copy import deepcopy from datetime import timedelta from pathlib import Path from typing import Optional from unittest.mock import MagicMock, Mock, PropertyMock from freqtrade import constants from freqtrade.commands import Arguments from freqtrade.data.converter import ohlcv_to_dataframe, trades_list_to_df from freqtrade.edge import PairInfo from freqtrade.enums import CandleType, MarginMode, RunMode, SignalDirection, TradingMode from freqtrade.exchange import Exchange from freqtrade.exchange.exchange import timeframe_to_minutes from freqtrade.freqtradebot import FreqtradeBot from freqtrade.persistence import LocalTrade, Order, Trade, init_db from freqtrade.resolvers import ExchangeResolver from freqtrade.util import dt_ts from freqtrade.util.datetime_helpers import dt_now from freqtrade.worker import Worker from tests.conftest_trades import (leverage_trade, mock_trade_1, mock_trade_2, mock_trade_3, mock_trade_4, mock_trade_5, mock_trade_6, short_trade) from tests.conftest_trades_usdt import (mock_trade_usdt_1, mock_trade_usdt_2, mock_trade_usdt_3, mock_trade_usdt_4, mock_trade_usdt_5, mock_trade_usdt_6, mock_trade_usdt_7)
7,390
""" patch_freqtradebot(mocker, config) return FreqtradeBot(config) def get_patched_worker(mocker, config) -> Worker: """ This function patches _init_modules() to not call dependencies :param mocker: a Mocker object to apply patches :param config: Config to pass to the bot :return: Worker """ patch_freqtradebot(mocker, config) return Worker(args=None, config=config) def patch_get_signal( freqtrade: FreqtradeBot, enter_long=True, exit_long=False, enter_short=False, exit_short=False, enter_tag: Optional[str] = None, exit_tag: Optional[str] = None, ) -> None: """ :param mocker: mocker to patch IStrategy class :return: None """ # returns (Signal-direction, signaname) def patched_get_entry_signal(*args, **kwargs): direction = None if enter_long and not any([exit_long, enter_short]): direction = SignalDirection.LONG if enter_short and not any([exit_short, enter_long]): direction = SignalDirection.SHORT return direction, enter_tag freqtrade.strategy.get_entry_signal = patched_get_entry_signal def patched_get_exit_signal(pair, timeframe, dataframe, is_short): if is_short: return enter_short, exit_short, exit_tag else: return enter_long, exit_long, exit_tag # returns (enter, exit) freqtrade.strategy.get_exit_signal = patched_get_exit_signal freqtrade.exchange.refresh_latest_ohlcv = lambda p: None def create_mock_trades(fee, is_short: Optional[bool] = False, use_db: bool = True): """ Create some fake trades ... :param is_short: Optional bool, None creates a mix of long and short trades. """ def add_trade(trade): if use_db: Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) is_short1 = is_short if is_short is not None else True is_short2 = is_short if is_short is not None else False # Simulate dry_run entries trade = mock_trade_1(fee, is_short1) add_trade(trade) trade = mock_trade_2(fee, is_short1) add_trade(trade) trade = mock_trade_3(fee, is_short2) add_trade(trade) trade = mock_trade_4(fee, is_short2) add_trade(trade) trade = mock_trade_5(fee, is_short2) add_trade(trade) trade = mock_trade_6(fee, is_short1) add_trade(trade) if use_db: Trade.commit() def create_mock_trades_with_leverage(fee, use_db: bool = True): """ Create some fake trades ... """ if use_db: Trade.session.rollback() def add_trade(trade): if use_db: Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) # Simulate dry_run entries trade = mock_trade_1(fee, False) add_trade(trade) trade = mock_trade_2(fee, False) add_trade(trade) trade = mock_trade_3(fee, False) add_trade(trade) trade = mock_trade_4(fee, False) add_trade(trade) trade = mock_trade_5(fee, False) add_trade(trade) trade = mock_trade_6(fee, False) add_trade(trade)
# pragma pylint: disable=missing-docstring logging.getLogger('').setLevel(logging.INFO) # Do not mask numpy errors as warnings that no one read, raise the exсeption np.seterr(all='raise') CURRENT_TEST_STRATEGY = 'StrategyTestV3' TRADE_SIDES = ('long', 'short') EXMS = 'freqtrade.exchange.exchange.Exchange' def pytest_addoption(parser): parser.addoption('--longrun', action='store_true', dest="longrun", default=False, help="Enable long-run tests (ccxt compat)") def pytest_configure(config): config.addinivalue_line( "markers", "longrun: mark test that is running slowly and should not be run regularily" ) if not config.option.longrun: setattr(config.option, 'markexpr', 'not longrun') def log_has(line, logs): """Check if line is found on some caplog's message.""" return any(line == message for message in logs.messages) def log_has_when(line, logs, when): """Check if line is found in caplog's messages during a specified stage""" return any(line == message.message for message in logs.get_records(when)) def log_has_re(line, logs): """Check if line matches some caplog's message.""" return any(re.match(line, message) for message in logs.messages) def num_log_has(line, logs): """Check how many times line is found in caplog's messages.""" return sum(line == message for message in logs.messages) def num_log_has_re(line, logs): """Check how many times line matches caplog's messages.""" return sum(bool(re.match(line, message)) for message in logs.messages) def get_args(args): return Arguments(args).get_parsed_arg() def generate_test_data(timeframe: str, size: int, start: str = '2020-07-05'): np.random.seed(42) tf_mins = timeframe_to_minutes(timeframe) base = np.random.normal(20, 2, size=size) date = pd.date_range(start, periods=size, freq=f'{tf_mins}min', tz='UTC') df = pd.DataFrame({ 'date': date, 'open': base, 'high': base + np.random.normal(2, 1, size=size), 'low': base - np.random.normal(2, 1, size=size), 'close': base + np.random.normal(0, 1, size=size), 'volume': np.random.normal(200, size=size) } ) df = df.dropna() return df def generate_test_data_raw(timeframe: str, size: int, start: str = '2020-07-05'): """ Generates data in the ohlcv format used by ccxt """ df = generate_test_data(timeframe, size, start) df['date'] = df.loc[:, 'date'].view(np.int64) // 1000 // 1000 return list(list(x) for x in zip(*(df[x].values.tolist() for x in df.columns))) # Source: https://stackoverflow.com/questions/29881236/how-to-mock-asyncio-coroutines # TODO: This should be replaced with AsyncMock once support for python 3.7 is dropped. def get_mock_coro(return_value=None, side_effect=None): async def mock_coro(*args, **kwargs): if side_effect: if isinstance(side_effect, list): effect = side_effect.pop(0) else: effect = side_effect if isinstance(effect, Exception): raise effect if callable(effect): return effect(*args, **kwargs) return effect else: return return_value return Mock(wraps=mock_coro) def patched_configuration_load_config_file(mocker, config) -> None: mocker.patch( 'freqtrade.configuration.load_config.load_config_file', lambda *args, **kwargs: config ) def patch_exchange( mocker, api_mock=None, id='binance', mock_markets=True, mock_supported_modes=True ) -> None: mocker.patch(f'{EXMS}._load_async_markets', return_value={}) mocker.patch(f'{EXMS}.validate_config', MagicMock()) mocker.patch(f'{EXMS}.validate_timeframes', MagicMock()) mocker.patch(f'{EXMS}.id', PropertyMock(return_value=id)) mocker.patch(f'{EXMS}.name', PropertyMock(return_value=id.title())) mocker.patch(f'{EXMS}.precisionMode', PropertyMock(return_value=2)) if mock_markets: if isinstance(mock_markets, bool): mock_markets = get_markets() mocker.patch(f'{EXMS}.markets', PropertyMock(return_value=mock_markets)) if mock_supported_modes: mocker.patch( f'freqtrade.exchange.{id}.{id.capitalize()}._supported_trading_mode_margin_pairs', PropertyMock(return_value=[ (TradingMode.MARGIN, MarginMode.CROSS), (TradingMode.MARGIN, MarginMode.ISOLATED), (TradingMode.FUTURES, MarginMode.CROSS), (TradingMode.FUTURES, MarginMode.ISOLATED) ]) ) if api_mock: mocker.patch(f'{EXMS}._init_ccxt', return_value=api_mock) else: mocker.patch(f'{EXMS}._init_ccxt', MagicMock()) mocker.patch(f'{EXMS}.timeframes', PropertyMock( return_value=['5m', '15m', '1h', '1d'])) def get_patched_exchange(mocker, config, api_mock=None, id='binance', mock_markets=True, mock_supported_modes=True) -> Exchange: patch_exchange(mocker, api_mock, id, mock_markets, mock_supported_modes) config['exchange']['name'] = id try: exchange = ExchangeResolver.load_exchange(config, load_leverage_tiers=True) except ImportError: exchange = Exchange(config) return exchange def patch_wallet(mocker, free=999.9) -> None: mocker.patch('freqtrade.wallets.Wallets.get_free', MagicMock( return_value=free )) def patch_whitelist(mocker, conf) -> None: mocker.patch('freqtrade.freqtradebot.FreqtradeBot._refresh_active_whitelist', MagicMock(return_value=conf['exchange']['pair_whitelist'])) def patch_edge(mocker) -> None: # "ETH/BTC", # "LTC/BTC", # "XRP/BTC", # "NEO/BTC" mocker.patch('freqtrade.edge.Edge._cached_pairs', mocker.PropertyMock( return_value={ 'NEO/BTC': PairInfo(-0.20, 0.66, 3.71, 0.50, 1.71, 10, 25), 'LTC/BTC': PairInfo(-0.21, 0.66, 3.71, 0.50, 1.71, 11, 20), } )) mocker.patch('freqtrade.edge.Edge.calculate', MagicMock(return_value=True)) # Functions for recurrent object patching def patch_freqtradebot(mocker, config) -> None: """ This function patch _init_modules() to not call dependencies :param mocker: a Mocker object to apply patches :param config: Config to pass to the bot :return: None """ mocker.patch('freqtrade.freqtradebot.RPCManager', MagicMock()) patch_exchange(mocker) mocker.patch('freqtrade.freqtradebot.RPCManager._init', MagicMock()) mocker.patch('freqtrade.freqtradebot.RPCManager.send_msg', MagicMock()) patch_whitelist(mocker, config) mocker.patch('freqtrade.freqtradebot.ExternalMessageConsumer') mocker.patch('freqtrade.configuration.config_validation._validate_consumers') def get_patched_freqtradebot(mocker, config) -> FreqtradeBot: """ This function patches _init_modules() to not call dependencies :param mocker: a Mocker object to apply patches :param config: Config to pass to the bot :return: FreqtradeBot """ patch_freqtradebot(mocker, config) return FreqtradeBot(config) def get_patched_worker(mocker, config) -> Worker: """ This function patches _init_modules() to not call dependencies :param mocker: a Mocker object to apply patches :param config: Config to pass to the bot :return: Worker """ patch_freqtradebot(mocker, config) return Worker(args=None, config=config) def patch_get_signal( freqtrade: FreqtradeBot, enter_long=True, exit_long=False, enter_short=False, exit_short=False, enter_tag: Optional[str] = None, exit_tag: Optional[str] = None, ) -> None: """ :param mocker: mocker to patch IStrategy class :return: None """ # returns (Signal-direction, signaname) def patched_get_entry_signal(*args, **kwargs): direction = None if enter_long and not any([exit_long, enter_short]): direction = SignalDirection.LONG if enter_short and not any([exit_short, enter_long]): direction = SignalDirection.SHORT return direction, enter_tag freqtrade.strategy.get_entry_signal = patched_get_entry_signal def patched_get_exit_signal(pair, timeframe, dataframe, is_short): if is_short: return enter_short, exit_short, exit_tag else: return enter_long, exit_long, exit_tag # returns (enter, exit) freqtrade.strategy.get_exit_signal = patched_get_exit_signal freqtrade.exchange.refresh_latest_ohlcv = lambda p: None def create_mock_trades(fee, is_short: Optional[bool] = False, use_db: bool = True): """ Create some fake trades ... :param is_short: Optional bool, None creates a mix of long and short trades. """ def add_trade(trade): if use_db: Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) is_short1 = is_short if is_short is not None else True is_short2 = is_short if is_short is not None else False # Simulate dry_run entries trade = mock_trade_1(fee, is_short1) add_trade(trade) trade = mock_trade_2(fee, is_short1) add_trade(trade) trade = mock_trade_3(fee, is_short2) add_trade(trade) trade = mock_trade_4(fee, is_short2) add_trade(trade) trade = mock_trade_5(fee, is_short2) add_trade(trade) trade = mock_trade_6(fee, is_short1) add_trade(trade) if use_db: Trade.commit() def create_mock_trades_with_leverage(fee, use_db: bool = True): """ Create some fake trades ... """ if use_db: Trade.session.rollback() def add_trade(trade): if use_db: Trade.session.add(trade) else: LocalTrade.add_bt_trade(trade) # Simulate dry_run entries trade = mock_trade_1(fee, False) add_trade(trade) trade = mock_trade_2(fee, False) add_trade(trade) trade = mock_trade_3(fee, False) add_trade(trade) trade = mock_trade_4(fee, False) add_trade(trade) trade = mock_trade_5(fee, False) add_trade(trade) trade = mock_trade_6(fee, False) add_trade(trade)
trade = short_trade(fee)
7
2023-11-07 18:46:03+00:00
12k
awslabs/optimizing-multitask-training-through-dynamic-pipelines
scripts/simulation/compare_batching_methods.py
[ { "identifier": "ProfileBasedCostModelWithRC", "path": "dynapipe/data_opt/cost_models.py", "snippet": "class ProfileBasedCostModelWithRC(object):\n \"\"\"\n Wrapper class for multiple ProfileBasedCostModel objects, one for each\n tensor parallel degree and recomputation method.\n \"\"\"\n\n ...
import argparse import math import jsonlines import numpy as np import pickle from multiprocessing import Pool from typing import Optional from tqdm import tqdm from dynapipe.data_opt.cost_models import ProfileBasedCostModelWithRC from dynapipe.data_opt.optimizer import DataAssignmentOptimizer from dynapipe.model import TransformerModelSpec
8,779
global_batch, method, model, mbs=None, dataopt: Optional[DataAssignmentOptimizer] = None, ): if method == "none": # no micro-batching, directly pad to max sequence length batch_np = np.array(global_batch) max_input_seqlen = np.max(batch_np[:, 0]) max_target_seqlen = np.max(batch_np[:, 1]) mbs = len(global_batch) return [(mbs, max_input_seqlen, max_target_seqlen)], "none" elif method == "dynamic": enc_seqlens = [x[0] for x in global_batch] dec_seqlens = [x[1] for x in global_batch] out = dataopt.generate_microbatches( enc_seqlens, decoder_sample_sequence_lengths=dec_seqlens if model == "t5" else None, bottleneck_tsp=False, partition_method="dp", enable_packing=False, tsp_dist_function="sum", ) if out[0] is None: with open("dataopt.pkl", "wb") as f: pickle.dump(dataopt, f) with open("global_batch.pkl", "wb") as f: pickle.dump(global_batch, f) return None, None ( objective_values, microbatches, memory_type, rc_type, (avail_mem, model_state, per_mb_memory_limit), ) = out micro_batch_shapes = [] assert len(microbatches) == 1 for microbatch in microbatches[0]: mbs = len(microbatch) max_enc_seqlen = 0 max_dec_seqlen = 0 for sequence in microbatch: assert len(sequence) == 1 enc_seqlen = enc_seqlens[sequence[0]] dec_seqlen = dec_seqlens[sequence[0]] max_enc_seqlen = max(max_enc_seqlen, enc_seqlen) max_dec_seqlen = max(max_dec_seqlen, dec_seqlen) micro_batch_shapes.append((mbs, max_enc_seqlen, max_dec_seqlen)) return micro_batch_shapes, rc_type elif method in ["fixed_mbs", "packing"]: assert mbs is not None microbatches = [] sorted_batch = sorted(global_batch, reverse=True) for i in range(0, len(sorted_batch), mbs): batch_np = np.array(sorted_batch[i : i + mbs]) max_input_seqlen = np.max(batch_np[:, 0]) max_target_seqlen = np.max(batch_np[:, 1]) microbatches.append( (len(batch_np), max_input_seqlen, max_target_seqlen) ) return microbatches, "none" elif method == "fixed_tokens": assert mbs is not None enc_seqlens = [x[0] for x in global_batch] dec_seqlens = [x[1] for x in global_batch] out = dataopt.generate_microbatches( enc_seqlens, decoder_sample_sequence_lengths=dec_seqlens if args.model == "t5" else None, bottleneck_tsp=False, partition_method="token_based", enable_packing=False, token_based_partition_mb_tokens=mbs, tsp_dist_function="sum", ) ( objective_values, microbatches, memory_type, rc_type, (avail_mem, model_state, per_mb_memory_limit), ) = out if out[0] is None: return None, None micro_batch_shapes = [] assert len(microbatches) == 1 for microbatch in microbatches[0]: mbs = len(microbatch) max_enc_seqlen = 0 max_dec_seqlen = 0 for sequence in microbatch: assert len(sequence) == 1 enc_seqlen = enc_seqlens[sequence[0]] dec_seqlen = dec_seqlens[sequence[0]] max_enc_seqlen = max(max_enc_seqlen, enc_seqlen) max_dec_seqlen = max(max_dec_seqlen, dec_seqlen) micro_batch_shapes.append((mbs, max_enc_seqlen, max_dec_seqlen)) return micro_batch_shapes, rc_type else: raise ValueError( "Unsupported micro-batching method: {}".format(method) ) def count_tokens(microbatches): total_tokens = 0 for mbs, enc_seqlen, dec_seqlen in microbatches: total_tokens += mbs * (enc_seqlen + dec_seqlen) return total_tokens def get_execution_time_and_memory( microbatches, rc_type,
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 def parse_args(): parser = argparse.ArgumentParser("Compare batching methods") parser.add_argument( "-t", "--method", type=str, choices=["none", "packing", "dynamic", "fixed_mbs", "fixed_tokens"], required=True, help="Micro-batching method to use.", ) parser.add_argument( "-s", "--max-seqlen-range", type=str, default="2048", help="Range of maximum sequence length to simulate. " "Format as comma separated list of integers.", ) parser.add_argument( "-di", "--input-dataset", type=str, required=True, help="Path to a Megatron-LM processed indexfile, " "which records the sequence length of samples in npy " "format. For input sequences.", ) parser.add_argument( "-dt", "--target-dataset", type=str, required=True, help="Dataset path for target sequences.", ) parser.add_argument( "-c", "--cost-model", type=str, required=True, help="Path to a cost model file, needed for dynamic " " batching.", ) parser.add_argument( "-m", "--model", type=str, required=True, choices=["gpt", "t5"], help="Model to use.", ) parser.add_argument( "-g", "--global-batch-size", type=int, default=65536, help="Global batch size.", ) parser.add_argument( "-o", "--output", type=str, default="compare_batching_methods.jsonl", help="Output file.", ) parser.add_argument( "-ml", "--mem-limit", type=float, default=float("inf"), help="Memory limit for the data assignment optimizer.", ) parser.add_argument( "-ppr", "--pp-degree-range", type=str, default="1", help="Range of pipeline stages to simulate.", ) parser.add_argument( "-tpd", "--tp-degree", type=int, default=1, help="TP degree to simulate.", ) parser.add_argument( "-p", "--num-processes", type=int, default=64, help="Number of processes to use.", ) args = parser.parse_args() args.max_seqlen_range = [int(x) for x in args.max_seqlen_range.split(",")] args.pp_degree_range = [int(x) for x in args.pp_degree_range.split(",")] return args def get_powers_of_2_up_to(n): return [2**i for i in range(math.floor(math.log2(n)) + 1)] def get_candidate_mbs(maxn=512): return get_powers_of_2_up_to(maxn) def get_candidate_tokens(maxn=65536): return [x for x in get_powers_of_2_up_to(maxn) if x >= 32] def get_sequence_lengths(dataset_path, max_seqlen): """Get the sequence lengths from a Megatron-LM processed dataset.""" with open(dataset_path, "rb") as f: dataset = np.load(f) # dataset contains 3 columns: [start_id, end_id, sequence_length] # we only need the sequence length return np.clip(dataset[:, 2], 1, max_seqlen).astype(np.int32)[:100000] def get_global_batches(input_seqlens, target_seqlens, gbs=65536): """Get the number of global batches for a given global batch size.""" global_batches = [] current_batch = [] current_batch_size = 0 for input_seqlen, target_seqlen in zip(input_seqlens, target_seqlens): if current_batch_size + input_seqlen + target_seqlen > gbs: global_batches.append(current_batch.copy()) current_batch = [] current_batch_size = 0 current_batch.append((input_seqlen, target_seqlen)) current_batch_size += input_seqlen + target_seqlen if current_batch: global_batches.append(current_batch.copy()) return global_batches def get_model_spec(pp_degree, model="gpt"): if model == "gpt": return TransformerModelSpec(4 * pp_degree, 0, 4096, 32, 16384, 128) elif model == "t5": return TransformerModelSpec( 2 * pp_degree, 2 * pp_degree, 1024, 128, 65536, 128 ) else: raise ValueError("Unsupported model: {}".format(model)) def get_dataopt( pp_degree, cost_model, model="gpt", memlimit=float("inf"), tp_degree=1 ): num_stages = pp_degree model_spec = get_model_spec(pp_degree, model) zero_stage = 0 n_layers_per_stage = 4 dp_size = 1 dataopt = DataAssignmentOptimizer( cost_model, model_spec, num_stages, n_layers_per_stage, n_chunks_per_device=1, dp_size=dp_size, tp_size=tp_degree, zero_stage=zero_stage, device_memory_limit=memlimit, seqlen_offset=1 if model == "gpt" else 0, ) return dataopt def pack_sequences(enc_seqlens, dec_seqlens, max_seqlen, model): current_enc_seq_len = 0 current_dec_seq_len = 0 packed_enc_seqlens = [] packed_dec_seqlens = [] for enc_seqlen, dec_seqlen in zip(enc_seqlens, dec_seqlens): if ( current_enc_seq_len + enc_seqlen > max_seqlen or current_dec_seq_len + dec_seqlen > max_seqlen ): packed_enc_seqlens.append(max_seqlen) if model == "gpt": packed_dec_seqlens.append(0) else: packed_dec_seqlens.append(max_seqlen) current_enc_seq_len = 0 current_dec_seq_len = 0 current_enc_seq_len += enc_seqlen current_dec_seq_len += dec_seqlen if current_enc_seq_len > 0: packed_enc_seqlens.append(max_seqlen) if model == "gpt": packed_dec_seqlens.append(0) else: packed_dec_seqlens.append(max_seqlen) return packed_enc_seqlens, packed_dec_seqlens def get_microbatches( global_batch, method, model, mbs=None, dataopt: Optional[DataAssignmentOptimizer] = None, ): if method == "none": # no micro-batching, directly pad to max sequence length batch_np = np.array(global_batch) max_input_seqlen = np.max(batch_np[:, 0]) max_target_seqlen = np.max(batch_np[:, 1]) mbs = len(global_batch) return [(mbs, max_input_seqlen, max_target_seqlen)], "none" elif method == "dynamic": enc_seqlens = [x[0] for x in global_batch] dec_seqlens = [x[1] for x in global_batch] out = dataopt.generate_microbatches( enc_seqlens, decoder_sample_sequence_lengths=dec_seqlens if model == "t5" else None, bottleneck_tsp=False, partition_method="dp", enable_packing=False, tsp_dist_function="sum", ) if out[0] is None: with open("dataopt.pkl", "wb") as f: pickle.dump(dataopt, f) with open("global_batch.pkl", "wb") as f: pickle.dump(global_batch, f) return None, None ( objective_values, microbatches, memory_type, rc_type, (avail_mem, model_state, per_mb_memory_limit), ) = out micro_batch_shapes = [] assert len(microbatches) == 1 for microbatch in microbatches[0]: mbs = len(microbatch) max_enc_seqlen = 0 max_dec_seqlen = 0 for sequence in microbatch: assert len(sequence) == 1 enc_seqlen = enc_seqlens[sequence[0]] dec_seqlen = dec_seqlens[sequence[0]] max_enc_seqlen = max(max_enc_seqlen, enc_seqlen) max_dec_seqlen = max(max_dec_seqlen, dec_seqlen) micro_batch_shapes.append((mbs, max_enc_seqlen, max_dec_seqlen)) return micro_batch_shapes, rc_type elif method in ["fixed_mbs", "packing"]: assert mbs is not None microbatches = [] sorted_batch = sorted(global_batch, reverse=True) for i in range(0, len(sorted_batch), mbs): batch_np = np.array(sorted_batch[i : i + mbs]) max_input_seqlen = np.max(batch_np[:, 0]) max_target_seqlen = np.max(batch_np[:, 1]) microbatches.append( (len(batch_np), max_input_seqlen, max_target_seqlen) ) return microbatches, "none" elif method == "fixed_tokens": assert mbs is not None enc_seqlens = [x[0] for x in global_batch] dec_seqlens = [x[1] for x in global_batch] out = dataopt.generate_microbatches( enc_seqlens, decoder_sample_sequence_lengths=dec_seqlens if args.model == "t5" else None, bottleneck_tsp=False, partition_method="token_based", enable_packing=False, token_based_partition_mb_tokens=mbs, tsp_dist_function="sum", ) ( objective_values, microbatches, memory_type, rc_type, (avail_mem, model_state, per_mb_memory_limit), ) = out if out[0] is None: return None, None micro_batch_shapes = [] assert len(microbatches) == 1 for microbatch in microbatches[0]: mbs = len(microbatch) max_enc_seqlen = 0 max_dec_seqlen = 0 for sequence in microbatch: assert len(sequence) == 1 enc_seqlen = enc_seqlens[sequence[0]] dec_seqlen = dec_seqlens[sequence[0]] max_enc_seqlen = max(max_enc_seqlen, enc_seqlen) max_dec_seqlen = max(max_dec_seqlen, dec_seqlen) micro_batch_shapes.append((mbs, max_enc_seqlen, max_dec_seqlen)) return micro_batch_shapes, rc_type else: raise ValueError( "Unsupported micro-batching method: {}".format(method) ) def count_tokens(microbatches): total_tokens = 0 for mbs, enc_seqlen, dec_seqlen in microbatches: total_tokens += mbs * (enc_seqlen + dec_seqlen) return total_tokens def get_execution_time_and_memory( microbatches, rc_type,
cost_model: ProfileBasedCostModelWithRC,
0
2023-11-08 07:58:20+00:00
12k
apple/ml-reed
reed/data/preference_dataset.py
[ { "identifier": "TrajectoryReplayBuffer", "path": "BPref/replay_buffer.py", "snippet": "class TrajectoryReplayBuffer:\n \"\"\"\n Buffer to store trajectories of environment transitions. Unlike ReplayBuffer, which stores all transitions in a\n flat manner, transitions are sorted by trajectory. E...
import typing as t import time import shutil import yaml import numpy as np import torch import torch.functional as F from pathlib import Path from zipfile import ZipFile from BPref.replay_buffer import TrajectoryReplayBuffer from reed.data.preprocess_images import PreProcessInference
9,365
batch_size = 100 with torch.no_grad(): total_dists = [] for full_idx in range(len(obs) // batch_size + 1): full_start = full_idx * batch_size if full_start < len(obs): full_end = (full_idx + 1) * batch_size dists = [] for idx in range(len(full_obs) // batch_size + 1): start = idx * batch_size if start < len(full_obs): end = (idx + 1) * batch_size dist = torch.norm( obs[full_start:full_end, None, :].to(device) - full_obs[None, start:end, :].to(device), dim=-1, p=2 ) dists.append(dist) dists = torch.cat(dists, dim=1) small_dists = torch.torch.min(dists, dim=1).values total_dists.append(small_dists) total_dists = torch.cat(total_dists) return total_dists.unsqueeze(1) class _PreferenceLabeller: def __init__(self, label_margin: float = 0.0, teacher_beta: float = -1, teacher_gamma: float = 1, teacher_eps_mistake: float = 0, teacher_eps_skip: float = 0, teacher_eps_equal: float = 0): """ Assigns preference labels to the trajectory pairs following the strategy specified by the parameters Args: label_margin: teacher_beta teacher_gamma: used to determine how much influence each reward has on the preference label based on order within the trajectory. Used to compute the return teacher_eps_mistake: the frequency with which the teacher assigns an incorrect label teacher_eps_skip: the frequency with which the teacher does not assign a label teacher_eps_equal: the maximum difference between trajectory returns for the two trajectories to be labelled as equally preferred """ self.teacher_beta = teacher_beta self.teacher_gamma = teacher_gamma self.teacher_eps_mistake = teacher_eps_mistake self.teacher_eps_skip = teacher_eps_skip self.teacher_eps_equal = teacher_eps_equal self.teacher_thres_skip = 0 self.teacher_thres_equal = 0 self.label_margin = label_margin self.label_target = 1 - 2 * self.label_margin def get_label(self, sa_t_1, sa_t_2, r_t_1, r_t_2): """ For each trajectory pair, assign a preference label Assigning a preference label can involve not labelling a trajectory pair, in which case the trajectory pair is removed from trajectories one and trajectories two Args: sa_t_1: the state-action pairs from trajectories one sa_t_2: the state-action pairs from trajectories two r_t_1: the reward per transition in the trajectories one r_t_2: the reward per transition in the trajectories two """ sum_r_t_1 = np.sum(r_t_1, axis=1) sum_r_t_2 = np.sum(r_t_2, axis=1) # skip the query if self.teacher_thres_skip > 0: max_r_t = np.maximum(sum_r_t_1, sum_r_t_2) max_index = (max_r_t > self.teacher_thres_skip).reshape(-1) if sum(max_index) == 0: return None, None, None, None, [] sa_t_1 = sa_t_1[max_index] sa_t_2 = sa_t_2[max_index] r_t_1 = r_t_1[max_index] r_t_2 = r_t_2[max_index] sum_r_t_1 = np.sum(r_t_1, axis=1) sum_r_t_2 = np.sum(r_t_2, axis=1) # equally preferable margin_index = (np.abs(sum_r_t_1 - sum_r_t_2) < self.teacher_thres_equal).reshape(-1) # perfectly rational seg_size = r_t_1.shape[1] temp_r_t_1 = r_t_1.copy() temp_r_t_2 = r_t_2.copy() for index in range(seg_size - 1): temp_r_t_1[:, :index + 1] *= self.teacher_gamma temp_r_t_2[:, :index + 1] *= self.teacher_gamma sum_r_t_1 = np.sum(temp_r_t_1, axis=1) sum_r_t_2 = np.sum(temp_r_t_2, axis=1) rational_labels = 1 * (sum_r_t_1 < sum_r_t_2) if self.teacher_beta > 0: # Bradley-Terry rational model r_hat = torch.cat([torch.Tensor(sum_r_t_1), torch.Tensor(sum_r_t_2)], dim=-1) r_hat = r_hat * self.teacher_beta ent = F.softmax(r_hat, dim=-1)[:, 1] labels = torch.bernoulli(ent).int().numpy().reshape(-1, 1).to_numpy() else: labels = rational_labels # making a mistake len_labels = labels.shape[0] rand_num = np.random.rand(len_labels) noise_index = rand_num <= self.teacher_eps_mistake labels[noise_index] = 1 - labels[noise_index] # equally preferable labels[margin_index] = -1 return sa_t_1, sa_t_2, r_t_1, r_t_2, labels class PreferenceDataset: def __init__(self, observation_dim: t.Union[t.Tuple, int], action_dim: t.Union[t.Tuple, int], capacity: int, size_segment: int, out_path: Path, image_observations: bool, grayscale_images: bool,
# # For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. # PREFERENCE_TRIPLET = t.Tuple[np.ndarray, np.ndarray, np.ndarray] PREFERENCE_TRIPLET_BATCH = t.Tuple[np.ndarray, np.ndarray, np.ndarray] def KCenterGreedy(obs, full_obs, num_new_sample): selected_index = [] current_index = list(range(obs.shape[0])) new_obs = obs new_full_obs = full_obs start_time = time.time() for count in range(num_new_sample): dist = compute_smallest_dist(new_obs, new_full_obs) max_index = torch.argmax(dist) max_index = max_index.item() if count == 0: selected_index.append(max_index) else: selected_index.append(current_index[max_index]) current_index = current_index[0:max_index] + current_index[max_index + 1:] new_obs = obs[current_index] new_full_obs = np.concatenate([ full_obs, obs[selected_index]], axis=0) return selected_index def compute_smallest_dist(obs, full_obs, device: torch.device): obs = torch.from_numpy(obs).float() full_obs = torch.from_numpy(full_obs).float() batch_size = 100 with torch.no_grad(): total_dists = [] for full_idx in range(len(obs) // batch_size + 1): full_start = full_idx * batch_size if full_start < len(obs): full_end = (full_idx + 1) * batch_size dists = [] for idx in range(len(full_obs) // batch_size + 1): start = idx * batch_size if start < len(full_obs): end = (idx + 1) * batch_size dist = torch.norm( obs[full_start:full_end, None, :].to(device) - full_obs[None, start:end, :].to(device), dim=-1, p=2 ) dists.append(dist) dists = torch.cat(dists, dim=1) small_dists = torch.torch.min(dists, dim=1).values total_dists.append(small_dists) total_dists = torch.cat(total_dists) return total_dists.unsqueeze(1) class _PreferenceLabeller: def __init__(self, label_margin: float = 0.0, teacher_beta: float = -1, teacher_gamma: float = 1, teacher_eps_mistake: float = 0, teacher_eps_skip: float = 0, teacher_eps_equal: float = 0): """ Assigns preference labels to the trajectory pairs following the strategy specified by the parameters Args: label_margin: teacher_beta teacher_gamma: used to determine how much influence each reward has on the preference label based on order within the trajectory. Used to compute the return teacher_eps_mistake: the frequency with which the teacher assigns an incorrect label teacher_eps_skip: the frequency with which the teacher does not assign a label teacher_eps_equal: the maximum difference between trajectory returns for the two trajectories to be labelled as equally preferred """ self.teacher_beta = teacher_beta self.teacher_gamma = teacher_gamma self.teacher_eps_mistake = teacher_eps_mistake self.teacher_eps_skip = teacher_eps_skip self.teacher_eps_equal = teacher_eps_equal self.teacher_thres_skip = 0 self.teacher_thres_equal = 0 self.label_margin = label_margin self.label_target = 1 - 2 * self.label_margin def get_label(self, sa_t_1, sa_t_2, r_t_1, r_t_2): """ For each trajectory pair, assign a preference label Assigning a preference label can involve not labelling a trajectory pair, in which case the trajectory pair is removed from trajectories one and trajectories two Args: sa_t_1: the state-action pairs from trajectories one sa_t_2: the state-action pairs from trajectories two r_t_1: the reward per transition in the trajectories one r_t_2: the reward per transition in the trajectories two """ sum_r_t_1 = np.sum(r_t_1, axis=1) sum_r_t_2 = np.sum(r_t_2, axis=1) # skip the query if self.teacher_thres_skip > 0: max_r_t = np.maximum(sum_r_t_1, sum_r_t_2) max_index = (max_r_t > self.teacher_thres_skip).reshape(-1) if sum(max_index) == 0: return None, None, None, None, [] sa_t_1 = sa_t_1[max_index] sa_t_2 = sa_t_2[max_index] r_t_1 = r_t_1[max_index] r_t_2 = r_t_2[max_index] sum_r_t_1 = np.sum(r_t_1, axis=1) sum_r_t_2 = np.sum(r_t_2, axis=1) # equally preferable margin_index = (np.abs(sum_r_t_1 - sum_r_t_2) < self.teacher_thres_equal).reshape(-1) # perfectly rational seg_size = r_t_1.shape[1] temp_r_t_1 = r_t_1.copy() temp_r_t_2 = r_t_2.copy() for index in range(seg_size - 1): temp_r_t_1[:, :index + 1] *= self.teacher_gamma temp_r_t_2[:, :index + 1] *= self.teacher_gamma sum_r_t_1 = np.sum(temp_r_t_1, axis=1) sum_r_t_2 = np.sum(temp_r_t_2, axis=1) rational_labels = 1 * (sum_r_t_1 < sum_r_t_2) if self.teacher_beta > 0: # Bradley-Terry rational model r_hat = torch.cat([torch.Tensor(sum_r_t_1), torch.Tensor(sum_r_t_2)], dim=-1) r_hat = r_hat * self.teacher_beta ent = F.softmax(r_hat, dim=-1)[:, 1] labels = torch.bernoulli(ent).int().numpy().reshape(-1, 1).to_numpy() else: labels = rational_labels # making a mistake len_labels = labels.shape[0] rand_num = np.random.rand(len_labels) noise_index = rand_num <= self.teacher_eps_mistake labels[noise_index] = 1 - labels[noise_index] # equally preferable labels[margin_index] = -1 return sa_t_1, sa_t_2, r_t_1, r_t_2, labels class PreferenceDataset: def __init__(self, observation_dim: t.Union[t.Tuple, int], action_dim: t.Union[t.Tuple, int], capacity: int, size_segment: int, out_path: Path, image_observations: bool, grayscale_images: bool,
collect_image_pref_dataset: bool, state_action_formatter: PreProcessInference,
1
2023-11-06 23:14:20+00:00
12k
ApolloAuto/apollo-model-yolox
yolox/models/yolox.py
[ { "identifier": "YOLOXHead", "path": "yolox/models/yolo_head.py", "snippet": "class YOLOXHead(nn.Module):\n def __init__(\n self,\n num_classes,\n width=1.0,\n strides=[8, 16, 32],\n in_channels=[256, 512, 1024],\n act=\"silu\",\n depthwise=False,\n ...
import torch.nn as nn from .yolo_head import YOLOXHead from .yolo_pafpn import YOLOPAFPN
7,744
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) Megvii Inc. All rights reserved. class YOLOX(nn.Module): """ YOLOX model module. The module list is defined by create_yolov3_modules function. The network returns loss values from three YOLO layers during training and detection results during test. """ def __init__(self, backbone=None, head=None): super().__init__() if backbone is None: backbone = YOLOPAFPN() if head is None:
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) Megvii Inc. All rights reserved. class YOLOX(nn.Module): """ YOLOX model module. The module list is defined by create_yolov3_modules function. The network returns loss values from three YOLO layers during training and detection results during test. """ def __init__(self, backbone=None, head=None): super().__init__() if backbone is None: backbone = YOLOPAFPN() if head is None:
head = YOLOXHead(80)
0
2023-11-08 07:07:24+00:00
12k
ndiamant/spice
experiments/train_eval.py
[ { "identifier": "ConditionalHist", "path": "spice/conditional_histogram.py", "snippet": "class ConditionalHist(BaseLightning):\n def __init__(\n self, input_dim: int, hidden_dim: int,\n max_iter: int, bins: torch.Tensor,\n y_min: float,\n lr: float = 1e-3, wd: float = 0,\n...
import argparse import os import wandb from pytorch_lightning import seed_everything, Trainer from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping, LearningRateMonitor from spice.conditional_histogram import ConditionalHist from spice.chr import CHR from spice.datasets import RegressionData from spice.cqr import CQR from spice.pcp import PCP from spice.utils import timestamp, rename_metrics, WANDB_PROJECT from spice.spice_n2 import SPICEn2, smart_bin_init from spice.spice_n1 import SPICEn1 from spice.spice_n1 import smart_bin_init as spice_n1_smart_bin_init
8,036
def setup_trainer_and_data( name: str, wandb_log_dir: str, epochs: int, version: str, checkpoint_folder: str, dataset_name: str, seed: int, y_scaling: str = "min_max", discretize_n_bins: int = None, smart_discretize: bool = True, ) -> tuple[Trainer, WandbLogger, ModelCheckpoint, RegressionData]: data = RegressionData( dataset_name, train_seed=seed, y_scaling=y_scaling, discretize_n_bins=discretize_n_bins, smart_discretize=smart_discretize, ) logger = WandbLogger( project=WANDB_PROJECT, save_dir=wandb_log_dir, name=name, group=version, version=f"{version}_{name}", ) checkpoint = ModelCheckpoint( dirpath=os.path.join(checkpoint_folder, name) ) max_steps_per_epoch = 100 max_val_steps = 10 train_batches = data.train_batches(max_steps_per_epoch) trainer = Trainer( logger=logger, callbacks=[ EarlyStopping(monitor="val/loss", patience=epochs // 4, mode="min"), LearningRateMonitor(), checkpoint, ], accelerator="gpu", max_steps=epochs * max_steps_per_epoch, check_val_every_n_epoch=1, limit_train_batches=train_batches, limit_val_batches=data.val_batches(max_val_steps), enable_progress_bar=False, gradient_clip_val=5, log_every_n_steps=train_batches, ) return trainer, logger, checkpoint, data def run_conditional_histogram( dataset_name: str, lr: float, wd: float, epochs: int, hidden: int, n_bins: int, seed: int, alphas: list[float], smart_bin_positions: bool, # saving settings checkpoint_folder: str, version: str, wandb_log_dir: str, # run_test: bool = False, ): # set up data ts = timestamp() name = f"conditional_hist_version-{version}_{ts}" trainer, logger, checkpoint, data = setup_trainer_and_data( name=name, wandb_log_dir=wandb_log_dir, epochs=epochs, version=version, dataset_name=dataset_name, seed=seed, checkpoint_folder=checkpoint_folder, discretize_n_bins=n_bins, smart_discretize=smart_bin_positions, ) seed_everything(seed) wandb.config.update({ "dataset_name": dataset_name, "alphas": alphas, "model": "conditional_hist", "n_bins": n_bins, "smart_bin_positions": smart_bin_positions, "seed": seed, }) # set up model x_train, y_train = data.train_dset.tensors
def setup_trainer_and_data( name: str, wandb_log_dir: str, epochs: int, version: str, checkpoint_folder: str, dataset_name: str, seed: int, y_scaling: str = "min_max", discretize_n_bins: int = None, smart_discretize: bool = True, ) -> tuple[Trainer, WandbLogger, ModelCheckpoint, RegressionData]: data = RegressionData( dataset_name, train_seed=seed, y_scaling=y_scaling, discretize_n_bins=discretize_n_bins, smart_discretize=smart_discretize, ) logger = WandbLogger( project=WANDB_PROJECT, save_dir=wandb_log_dir, name=name, group=version, version=f"{version}_{name}", ) checkpoint = ModelCheckpoint( dirpath=os.path.join(checkpoint_folder, name) ) max_steps_per_epoch = 100 max_val_steps = 10 train_batches = data.train_batches(max_steps_per_epoch) trainer = Trainer( logger=logger, callbacks=[ EarlyStopping(monitor="val/loss", patience=epochs // 4, mode="min"), LearningRateMonitor(), checkpoint, ], accelerator="gpu", max_steps=epochs * max_steps_per_epoch, check_val_every_n_epoch=1, limit_train_batches=train_batches, limit_val_batches=data.val_batches(max_val_steps), enable_progress_bar=False, gradient_clip_val=5, log_every_n_steps=train_batches, ) return trainer, logger, checkpoint, data def run_conditional_histogram( dataset_name: str, lr: float, wd: float, epochs: int, hidden: int, n_bins: int, seed: int, alphas: list[float], smart_bin_positions: bool, # saving settings checkpoint_folder: str, version: str, wandb_log_dir: str, # run_test: bool = False, ): # set up data ts = timestamp() name = f"conditional_hist_version-{version}_{ts}" trainer, logger, checkpoint, data = setup_trainer_and_data( name=name, wandb_log_dir=wandb_log_dir, epochs=epochs, version=version, dataset_name=dataset_name, seed=seed, checkpoint_folder=checkpoint_folder, discretize_n_bins=n_bins, smart_discretize=smart_bin_positions, ) seed_everything(seed) wandb.config.update({ "dataset_name": dataset_name, "alphas": alphas, "model": "conditional_hist", "n_bins": n_bins, "smart_bin_positions": smart_bin_positions, "seed": seed, }) # set up model x_train, y_train = data.train_dset.tensors
model = ConditionalHist(
0
2023-11-01 18:04:29+00:00
12k
nik-sm/com-hom-emg
scripts/collect_fresh_classifier_stats.py
[ { "identifier": "DataModule", "path": "com_hom_emg/data.py", "snippet": "class DataModule(LightningDataModule):\n @staticmethod\n def add_argparse_args(parent_parser):\n parser = parent_parser.add_argument_group(\"DataModule\")\n parser.add_argument(\"--fold\", type=int, required=Tru...
import argparse import re import sys import numpy as np import pandas as pd import torch import yaml from copy import deepcopy from pathlib import Path from typing import List, Optional from ablation_settings import settings_names as ablation_settings_names from loguru import logger from pytorch_lightning import seed_everything from regular_settings import settings_names as regular_settings_names from rich.console import Console from rich.table import Table from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA from sklearn.ensemble import RandomForestClassifier as RF from sklearn.linear_model import LogisticRegression as LogR from sklearn.neighbors import KNeighborsClassifier as KNN from sklearn.tree import DecisionTreeClassifier as DT from tqdm import tqdm from utils import table_to_csv from com_hom_emg.data import DataModule, get_per_subj_data from com_hom_emg.model import LearnedEmbedding from com_hom_emg.parallel_models import ControlModel_RandomGuess, ParallelA from com_hom_emg.scoring import get_combo_conf_mat from com_hom_emg.utils import PROJECT_PATH
8,435
"""Train fresh classifiers using test checkpoints""" device = torch.device("cuda" if torch.cuda.is_available() else "cpu") logger.remove() logger.add(lambda msg: tqdm.write(msg, end=""), colorize=True) class FailedRunError(Exception): pass def load_one(folder: Path, which="best"): """Extract train, val, and test metrics from the specified checkpoint (best or last). Also extract hyperparams from hparams.yaml file.""" # Given a checkpoint like this: best__epoch=38__step=14664__val_aug_overall_acc=0.569.ckpt # We want to extract the step: 14664 ckpts = folder / "checkpoints" matching_ckpts = list(ckpts.glob(f"{which}*.ckpt")) if len(matching_ckpts) == 0: raise FailedRunError(f"No checkpoint found for {which} in {folder}") # When there are multiple runs, take the most recent. # Since only 1 metrics.csv is kept, this matches the latest ckpt chosen_ckpt = max(matching_ckpts, key=lambda x: x.stat().st_mtime) step = int(re.match(rf"{which}__epoch=\d+__step=(\d+)", chosen_ckpt.name).group(1)) metrics = pd.read_csv(folder / "metrics.csv") results = {} # NOTE - for this experiment, we ignore the test results, which come from fine-tuning, # since we will train a fresh classifier instead for split in ["train", "val"]: cols = [col for col in metrics.columns if col.startswith(split)] if len(cols) == 0: raise FailedRunError(f"No {split} metrics found in {folder}") cols.append("step") subset = metrics[cols].dropna().set_index("step") subset = subset.iloc[subset.index.get_indexer([step], method="nearest")] assert len(subset) == 1 results.update(**subset.to_dict(orient="records")[0]) hparams = yaml.safe_load((folder / "hparams.yaml").read_text()) return hparams, results, chosen_ckpt def subset_one_class(X, Y, N): idx = np.random.choice(len(X), size=N, replace=False) return X[idx], Y[idx] def subset_each_class(X, Y, N): result_x, result_y = [], [] for y in Y.unique(dim=0): idx = (Y == y).all(-1) x = X[idx] y = Y[idx] x, y = subset_one_class(x, y, N) result_x.append(x) result_y.append(y) return torch.cat(result_x), torch.cat(result_y) def get_clf(name: str): if name == "logr": return LogR(class_weight="balanced", max_iter=4000, n_jobs=-1) elif name == "lda": return LDA() elif name == "knn": return KNN(n_jobs=-1) elif name == "rf": return RF(n_jobs=-1, class_weight="balanced") elif name == "dt": return DT(class_weight="balanced") else: raise ValueError(f"Unknown classifier name: {name}") @torch.no_grad() def try_fresh_classifier(embedding, test_loader, clf_name: str, test_frac=0.2, N_aug_each_class=500): # Get features embedding.to(device) features, labels, is_single = [], [], [] for batch_data, batch_labels, batch_is_single, _subj_ids in test_loader: features.append(embedding(batch_data.to(device))) labels.append(batch_labels.to(device)) is_single.append(batch_is_single) features = torch.cat(features) labels = torch.cat(labels) is_single = torch.cat(is_single) # Create a single train/test split N_single = is_single.sum().item() N_single_test = int(N_single * test_frac) N_double = (~is_single).sum().item() N_double_test = int(N_double * test_frac) np.random.seed(0) single_perm = np.random.permutation(N_single) test_single_feat = features[is_single][single_perm[:N_single_test]] test_single_labels = labels[is_single][single_perm[:N_single_test]] train_single_feat = features[is_single][single_perm[N_single_test:]] train_single_labels = labels[is_single][single_perm[N_single_test:]] double_perm = np.random.permutation(N_double) test_double_feat = features[~is_single][double_perm[:N_double_test]] test_double_labels = labels[~is_single][double_perm[:N_double_test]] train_double_feat = features[~is_single][double_perm[N_double_test:]] train_double_labels = labels[~is_single][double_perm[N_double_test:]] # Define function to train a single sklearn clf def try_once(which: str): # logger.info(f"Train an example model for scenario: {which}")
"""Train fresh classifiers using test checkpoints""" device = torch.device("cuda" if torch.cuda.is_available() else "cpu") logger.remove() logger.add(lambda msg: tqdm.write(msg, end=""), colorize=True) class FailedRunError(Exception): pass def load_one(folder: Path, which="best"): """Extract train, val, and test metrics from the specified checkpoint (best or last). Also extract hyperparams from hparams.yaml file.""" # Given a checkpoint like this: best__epoch=38__step=14664__val_aug_overall_acc=0.569.ckpt # We want to extract the step: 14664 ckpts = folder / "checkpoints" matching_ckpts = list(ckpts.glob(f"{which}*.ckpt")) if len(matching_ckpts) == 0: raise FailedRunError(f"No checkpoint found for {which} in {folder}") # When there are multiple runs, take the most recent. # Since only 1 metrics.csv is kept, this matches the latest ckpt chosen_ckpt = max(matching_ckpts, key=lambda x: x.stat().st_mtime) step = int(re.match(rf"{which}__epoch=\d+__step=(\d+)", chosen_ckpt.name).group(1)) metrics = pd.read_csv(folder / "metrics.csv") results = {} # NOTE - for this experiment, we ignore the test results, which come from fine-tuning, # since we will train a fresh classifier instead for split in ["train", "val"]: cols = [col for col in metrics.columns if col.startswith(split)] if len(cols) == 0: raise FailedRunError(f"No {split} metrics found in {folder}") cols.append("step") subset = metrics[cols].dropna().set_index("step") subset = subset.iloc[subset.index.get_indexer([step], method="nearest")] assert len(subset) == 1 results.update(**subset.to_dict(orient="records")[0]) hparams = yaml.safe_load((folder / "hparams.yaml").read_text()) return hparams, results, chosen_ckpt def subset_one_class(X, Y, N): idx = np.random.choice(len(X), size=N, replace=False) return X[idx], Y[idx] def subset_each_class(X, Y, N): result_x, result_y = [], [] for y in Y.unique(dim=0): idx = (Y == y).all(-1) x = X[idx] y = Y[idx] x, y = subset_one_class(x, y, N) result_x.append(x) result_y.append(y) return torch.cat(result_x), torch.cat(result_y) def get_clf(name: str): if name == "logr": return LogR(class_weight="balanced", max_iter=4000, n_jobs=-1) elif name == "lda": return LDA() elif name == "knn": return KNN(n_jobs=-1) elif name == "rf": return RF(n_jobs=-1, class_weight="balanced") elif name == "dt": return DT(class_weight="balanced") else: raise ValueError(f"Unknown classifier name: {name}") @torch.no_grad() def try_fresh_classifier(embedding, test_loader, clf_name: str, test_frac=0.2, N_aug_each_class=500): # Get features embedding.to(device) features, labels, is_single = [], [], [] for batch_data, batch_labels, batch_is_single, _subj_ids in test_loader: features.append(embedding(batch_data.to(device))) labels.append(batch_labels.to(device)) is_single.append(batch_is_single) features = torch.cat(features) labels = torch.cat(labels) is_single = torch.cat(is_single) # Create a single train/test split N_single = is_single.sum().item() N_single_test = int(N_single * test_frac) N_double = (~is_single).sum().item() N_double_test = int(N_double * test_frac) np.random.seed(0) single_perm = np.random.permutation(N_single) test_single_feat = features[is_single][single_perm[:N_single_test]] test_single_labels = labels[is_single][single_perm[:N_single_test]] train_single_feat = features[is_single][single_perm[N_single_test:]] train_single_labels = labels[is_single][single_perm[N_single_test:]] double_perm = np.random.permutation(N_double) test_double_feat = features[~is_single][double_perm[:N_double_test]] test_double_labels = labels[~is_single][double_perm[:N_double_test]] train_double_feat = features[~is_single][double_perm[N_double_test:]] train_double_labels = labels[~is_single][double_perm[N_double_test:]] # Define function to train a single sklearn clf def try_once(which: str): # logger.info(f"Train an example model for scenario: {which}")
clf = ParallelA(dir_clf=get_clf(clf_name), mod_clf=get_clf(clf_name))
4
2023-11-01 21:12:05+00:00
12k
SqueezeAILab/LLMCompiler
src/chains/llm_math_chain.py
[ { "identifier": "Chain", "path": "src/chains/chain.py", "snippet": "class Chain(Serializable, Runnable[Dict[str, Any], Dict[str, Any]], ABC):\n \"\"\"Abstract base class for creating structured sequences of calls to components.\n\n Chains should be used to encode a sequence of calls to components ...
import ast import math import re import warnings import numexpr from typing import Any, Dict, List, Optional from langchain.callbacks.manager import ( AsyncCallbackManagerForChainRun, CallbackManagerForChainRun, ) from langchain.prompts.prompt import PromptTemplate from langchain.pydantic_v1 import Extra, root_validator from langchain.schema import BasePromptTemplate from langchain.schema.language_model import BaseLanguageModel from src.chains.chain import Chain from src.chains.llm_chain import LLMChain
9,496
# flake8: noqa _PROMPT_TEMPLATE = """Translate a math problem into a expression that can be executed using Python's numexpr library. Use the output of running this code to answer the question. You MUST follow the following guidelines: - Do not use "where(...)" expressions in your code since it is not supported. - Do not use "fmax(...)" expression in your code since it is not supported. Use "max(...)" instead. - Never introduce a variable. For instance "gazelle_max_speed * 1.4" is not allowed. Pick up a correct number from the given context. Question: ${{Question with math problem.}} ```text ${{single line mathematical expression that solves the problem}} ``` ...numexpr.evaluate(text)... ```output ${{Output of running the code}} ``` Answer: ${{Answer}} Begin. Question: What is 37593 * 67? ```text 37593 * 67 ``` ...numexpr.evaluate("37593 * 67")... ```output 2518731 ``` Answer: 2518731 Question: 37593^(1/5) ```text 37593**(1/5) ``` ...numexpr.evaluate("37593**(1/5)")... ```output 8.222831614237718 ``` Answer: 8.222831614237718 Question: {question} """ PROMPT = PromptTemplate( input_variables=["question"], template=_PROMPT_TEMPLATE, ) # helper functions to handle min and max functions def compute_function(match): func, values = match.groups() # Extract numbers and remove commas from between digits numbers = [float(re.sub(r"(?<=\d),(?=\d)", "", v)) for v in values.split(",")] # Compute the min or max based on the detected function result = min(numbers) if func == "min" else max(numbers) return str(result) class MaxTransformer(ast.NodeTransformer): def visit_Call(self, node): self.generic_visit(node) # Apply the transformation to child nodes first if isinstance(node.func, ast.Name) and node.func.id in ("max", "min"): if all(isinstance(arg, (ast.Num, ast.Constant)) for arg in node.args): # Calculate the max value # print(node.args) args_as_strings = (ast.unparse(arg) for arg in node.args) args_str = ", ".join(args_as_strings) print(args_str) if node.func.id == "min": value = min( arg.n if isinstance(arg, ast.Num) else arg.value for arg in node.args ) else: value = max( arg.n if isinstance(arg, ast.Num) else arg.value for arg in node.args ) # Replace the max call with the max value directly return ast.copy_location(ast.Constant(value=value), node) return node def replace_min_max_functions(expression): # Parse the expression into an AST parsed_expression = ast.parse(expression, mode="eval") # Transform the AST transformer = MaxTransformer() transformed_ast = transformer.visit(parsed_expression) # Fix the missing locations in the AST transformed_ast = ast.fix_missing_locations(transformed_ast) # Compile the transformed AST compiled_code = compile(transformed_ast, "<string>", "eval") # Evaluate the compiled code result = eval(compiled_code) return str(result) class LLMMathChain(Chain): """Chain that interprets a prompt and executes python code to do math. Example: .. code-block:: python from langchain import LLMMathChain, OpenAI llm_math = LLMMathChain.from_llm(OpenAI()) """
"""Chain that interprets a prompt and executes python code to do math.""" from __future__ import annotations # flake8: noqa _PROMPT_TEMPLATE = """Translate a math problem into a expression that can be executed using Python's numexpr library. Use the output of running this code to answer the question. You MUST follow the following guidelines: - Do not use "where(...)" expressions in your code since it is not supported. - Do not use "fmax(...)" expression in your code since it is not supported. Use "max(...)" instead. - Never introduce a variable. For instance "gazelle_max_speed * 1.4" is not allowed. Pick up a correct number from the given context. Question: ${{Question with math problem.}} ```text ${{single line mathematical expression that solves the problem}} ``` ...numexpr.evaluate(text)... ```output ${{Output of running the code}} ``` Answer: ${{Answer}} Begin. Question: What is 37593 * 67? ```text 37593 * 67 ``` ...numexpr.evaluate("37593 * 67")... ```output 2518731 ``` Answer: 2518731 Question: 37593^(1/5) ```text 37593**(1/5) ``` ...numexpr.evaluate("37593**(1/5)")... ```output 8.222831614237718 ``` Answer: 8.222831614237718 Question: {question} """ PROMPT = PromptTemplate( input_variables=["question"], template=_PROMPT_TEMPLATE, ) # helper functions to handle min and max functions def compute_function(match): func, values = match.groups() # Extract numbers and remove commas from between digits numbers = [float(re.sub(r"(?<=\d),(?=\d)", "", v)) for v in values.split(",")] # Compute the min or max based on the detected function result = min(numbers) if func == "min" else max(numbers) return str(result) class MaxTransformer(ast.NodeTransformer): def visit_Call(self, node): self.generic_visit(node) # Apply the transformation to child nodes first if isinstance(node.func, ast.Name) and node.func.id in ("max", "min"): if all(isinstance(arg, (ast.Num, ast.Constant)) for arg in node.args): # Calculate the max value # print(node.args) args_as_strings = (ast.unparse(arg) for arg in node.args) args_str = ", ".join(args_as_strings) print(args_str) if node.func.id == "min": value = min( arg.n if isinstance(arg, ast.Num) else arg.value for arg in node.args ) else: value = max( arg.n if isinstance(arg, ast.Num) else arg.value for arg in node.args ) # Replace the max call with the max value directly return ast.copy_location(ast.Constant(value=value), node) return node def replace_min_max_functions(expression): # Parse the expression into an AST parsed_expression = ast.parse(expression, mode="eval") # Transform the AST transformer = MaxTransformer() transformed_ast = transformer.visit(parsed_expression) # Fix the missing locations in the AST transformed_ast = ast.fix_missing_locations(transformed_ast) # Compile the transformed AST compiled_code = compile(transformed_ast, "<string>", "eval") # Evaluate the compiled code result = eval(compiled_code) return str(result) class LLMMathChain(Chain): """Chain that interprets a prompt and executes python code to do math. Example: .. code-block:: python from langchain import LLMMathChain, OpenAI llm_math = LLMMathChain.from_llm(OpenAI()) """
llm_chain: LLMChain
1
2023-12-06 21:12:54+00:00
12k
bytedance/ImageDream
threestudio/systems/base.py
[ { "identifier": "Exporter", "path": "threestudio/models/exporters/base.py", "snippet": "class Exporter(BaseObject):\n @dataclass\n class Config(BaseObject.Config):\n save_video: bool = False\n\n cfg: Config\n\n def configure(\n self,\n geometry: BaseImplicitGeometry,\n ...
import os import pytorch_lightning as pl import torch.nn.functional as F import threestudio from dataclasses import dataclass, field from threestudio.models.exporters.base import Exporter, ExporterOutput from threestudio.systems.utils import parse_optimizer, parse_scheduler from threestudio.utils.base import Updateable, update_if_possible from threestudio.utils.config import parse_structured from threestudio.utils.misc import C, cleanup, get_device, load_module_weights from threestudio.utils.saving import SaverMixin from threestudio.utils.typing import * from threestudio.utils.config import load_config, parse_structured
10,307
update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_predict_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "predict") self.dataset = self.trainer.predict_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False): pass def on_before_optimizer_step(self, optimizer): """ # some gradient-related debugging goes here, example: from lightning.pytorch.utilities import grad_norm norms = grad_norm(self.geometry, norm_type=2) print(norms) """ pass class BaseLift3DSystem(BaseSystem): @dataclass class Config(BaseSystem.Config): geometry_type: str = "" geometry: dict = field(default_factory=dict) geometry_convert_from: Optional[str] = None geometry_convert_inherit_texture: bool = False # used to override configurations of the previous geometry being converted from, # for example isosurface_threshold geometry_convert_override: dict = field(default_factory=dict) material_type: str = "" material: dict = field(default_factory=dict) background_type: str = "" background: dict = field(default_factory=dict) renderer_type: str = "" renderer: dict = field(default_factory=dict) guidance_type: str = "" guidance: dict = field(default_factory=dict) prompt_processor_type: str = "" prompt_processor: dict = field(default_factory=dict) # geometry export configurations, no need to specify in training exporter_type: str = "mesh-exporter" exporter: dict = field(default_factory=dict) cfg: Config def configure(self) -> None: if ( self.cfg.geometry_convert_from # from_coarse must be specified and not self.cfg.weights # not initialized from coarse when weights are specified and not self.resumed # not initialized from coarse when resumed from checkpoints ): threestudio.info("Initializing geometry from a given checkpoint ...") prev_cfg = load_config( os.path.join( os.path.dirname(self.cfg.geometry_convert_from), "../configs/parsed.yaml", ) ) # TODO: hard-coded relative path prev_system_cfg: BaseLift3DSystem.Config = parse_structured( self.Config, prev_cfg.system ) prev_geometry_cfg = prev_system_cfg.geometry prev_geometry_cfg.update(self.cfg.geometry_convert_override) prev_geometry = threestudio.find(prev_system_cfg.geometry_type)( prev_geometry_cfg ) state_dict, epoch, global_step = load_module_weights( self.cfg.geometry_convert_from, module_name="geometry", map_location="cpu", ) prev_geometry.load_state_dict(state_dict, strict=False) # restore step-dependent states prev_geometry.do_update_step(epoch, global_step, on_load_weights=True) # convert from coarse stage geometry prev_geometry = prev_geometry.to(get_device()) self.geometry = threestudio.find(self.cfg.geometry_type).create_from( prev_geometry, self.cfg.geometry, copy_net=self.cfg.geometry_convert_inherit_texture, ) del prev_geometry cleanup() else: self.geometry = threestudio.find(self.cfg.geometry_type)(self.cfg.geometry) self.material = threestudio.find(self.cfg.material_type)(self.cfg.material) self.background = threestudio.find(self.cfg.background_type)( self.cfg.background ) self.renderer = threestudio.find(self.cfg.renderer_type)( self.cfg.renderer, geometry=self.geometry, material=self.material, background=self.background, ) def on_fit_start(self) -> None: if self._save_dir is not None: threestudio.info(f"Validation results will be saved to {self._save_dir}") else: threestudio.warn( f"Saving directory not set for the system, visualization results will not be saved" ) def on_test_end(self) -> None: if self._save_dir is not None: threestudio.info(f"Test results saved to {self._save_dir}") def on_predict_start(self) -> None:
class BaseSystem(pl.LightningModule, Updateable, SaverMixin): @dataclass class Config: loggers: dict = field(default_factory=dict) loss: dict = field(default_factory=dict) optimizer: dict = field(default_factory=dict) scheduler: Optional[dict] = None weights: Optional[str] = None weights_ignore_modules: Optional[List[str]] = None cleanup_after_validation_step: bool = False cleanup_after_test_step: bool = False cfg: Config def __init__(self, cfg, resumed=False) -> None: super().__init__() self.cfg = parse_structured(self.Config, cfg) self._save_dir: Optional[str] = None self._resumed: bool = resumed self._resumed_eval: bool = False self._resumed_eval_status: dict = {"global_step": 0, "current_epoch": 0} if "loggers" in cfg: self.create_loggers(cfg.loggers) self.configure() if self.cfg.weights is not None: self.load_weights(self.cfg.weights, self.cfg.weights_ignore_modules) self.post_configure() def load_weights(self, weights: str, ignore_modules: Optional[List[str]] = None): state_dict, epoch, global_step = load_module_weights( weights, ignore_modules=ignore_modules, map_location="cpu" ) self.load_state_dict(state_dict, strict=False) # restore step-dependent states self.do_update_step(epoch, global_step, on_load_weights=True) def set_resume_status(self, current_epoch: int, global_step: int): # restore correct epoch and global step in eval self._resumed_eval = True self._resumed_eval_status["current_epoch"] = current_epoch self._resumed_eval_status["global_step"] = global_step @property def resumed(self): # whether from resumed checkpoint return self._resumed @property def true_global_step(self): if self._resumed_eval: return self._resumed_eval_status["global_step"] else: return self.global_step @property def true_current_epoch(self): if self._resumed_eval: return self._resumed_eval_status["current_epoch"] else: return self.current_epoch def configure(self) -> None: pass def post_configure(self) -> None: """ executed after weights are loaded """ pass def C(self, value: Any) -> float: return C(value, self.true_current_epoch, self.true_global_step) def configure_optimizers(self): optim = parse_optimizer(self.cfg.optimizer, self) ret = { "optimizer": optim, } if self.cfg.scheduler is not None: ret.update( { "lr_scheduler": parse_scheduler(self.cfg.scheduler, optim), } ) return ret def training_step(self, batch, batch_idx): raise NotImplementedError def validation_step(self, batch, batch_idx): raise NotImplementedError def on_validation_batch_end(self, outputs, batch, batch_idx): if self.cfg.cleanup_after_validation_step: # cleanup to save vram cleanup() def on_validation_epoch_end(self): raise NotImplementedError def test_step(self, batch, batch_idx): raise NotImplementedError def on_test_batch_end(self, outputs, batch, batch_idx): if self.cfg.cleanup_after_test_step: # cleanup to save vram cleanup() def on_test_epoch_end(self): pass def predict_step(self, batch, batch_idx): raise NotImplementedError def on_predict_batch_end(self, outputs, batch, batch_idx): if self.cfg.cleanup_after_test_step: # cleanup to save vram cleanup() def on_predict_epoch_end(self): pass def preprocess_data(self, batch, stage): pass """ Implementing on_after_batch_transfer of DataModule does the same. But on_after_batch_transfer does not support DP. """ def on_train_batch_start(self, batch, batch_idx, unused=0): self.preprocess_data(batch, "train") self.dataset = self.trainer.train_dataloader.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_validation_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "validation") self.dataset = self.trainer.val_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_test_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "test") self.dataset = self.trainer.test_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def on_predict_batch_start(self, batch, batch_idx, dataloader_idx=0): self.preprocess_data(batch, "predict") self.dataset = self.trainer.predict_dataloaders.dataset update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step) self.do_update_step(self.true_current_epoch, self.true_global_step) def update_step(self, epoch: int, global_step: int, on_load_weights: bool = False): pass def on_before_optimizer_step(self, optimizer): """ # some gradient-related debugging goes here, example: from lightning.pytorch.utilities import grad_norm norms = grad_norm(self.geometry, norm_type=2) print(norms) """ pass class BaseLift3DSystem(BaseSystem): @dataclass class Config(BaseSystem.Config): geometry_type: str = "" geometry: dict = field(default_factory=dict) geometry_convert_from: Optional[str] = None geometry_convert_inherit_texture: bool = False # used to override configurations of the previous geometry being converted from, # for example isosurface_threshold geometry_convert_override: dict = field(default_factory=dict) material_type: str = "" material: dict = field(default_factory=dict) background_type: str = "" background: dict = field(default_factory=dict) renderer_type: str = "" renderer: dict = field(default_factory=dict) guidance_type: str = "" guidance: dict = field(default_factory=dict) prompt_processor_type: str = "" prompt_processor: dict = field(default_factory=dict) # geometry export configurations, no need to specify in training exporter_type: str = "mesh-exporter" exporter: dict = field(default_factory=dict) cfg: Config def configure(self) -> None: if ( self.cfg.geometry_convert_from # from_coarse must be specified and not self.cfg.weights # not initialized from coarse when weights are specified and not self.resumed # not initialized from coarse when resumed from checkpoints ): threestudio.info("Initializing geometry from a given checkpoint ...") prev_cfg = load_config( os.path.join( os.path.dirname(self.cfg.geometry_convert_from), "../configs/parsed.yaml", ) ) # TODO: hard-coded relative path prev_system_cfg: BaseLift3DSystem.Config = parse_structured( self.Config, prev_cfg.system ) prev_geometry_cfg = prev_system_cfg.geometry prev_geometry_cfg.update(self.cfg.geometry_convert_override) prev_geometry = threestudio.find(prev_system_cfg.geometry_type)( prev_geometry_cfg ) state_dict, epoch, global_step = load_module_weights( self.cfg.geometry_convert_from, module_name="geometry", map_location="cpu", ) prev_geometry.load_state_dict(state_dict, strict=False) # restore step-dependent states prev_geometry.do_update_step(epoch, global_step, on_load_weights=True) # convert from coarse stage geometry prev_geometry = prev_geometry.to(get_device()) self.geometry = threestudio.find(self.cfg.geometry_type).create_from( prev_geometry, self.cfg.geometry, copy_net=self.cfg.geometry_convert_inherit_texture, ) del prev_geometry cleanup() else: self.geometry = threestudio.find(self.cfg.geometry_type)(self.cfg.geometry) self.material = threestudio.find(self.cfg.material_type)(self.cfg.material) self.background = threestudio.find(self.cfg.background_type)( self.cfg.background ) self.renderer = threestudio.find(self.cfg.renderer_type)( self.cfg.renderer, geometry=self.geometry, material=self.material, background=self.background, ) def on_fit_start(self) -> None: if self._save_dir is not None: threestudio.info(f"Validation results will be saved to {self._save_dir}") else: threestudio.warn( f"Saving directory not set for the system, visualization results will not be saved" ) def on_test_end(self) -> None: if self._save_dir is not None: threestudio.info(f"Test results saved to {self._save_dir}") def on_predict_start(self) -> None:
self.exporter: Exporter = threestudio.find(self.cfg.exporter_type)(
0
2023-12-13 21:09:37+00:00
12k
TencentARC/MotionCtrl
lvdm/models/ddpm3d.py
[ { "identifier": "disabled_train", "path": "lvdm/basics.py", "snippet": "def disabled_train(self, mode=True):\n \"\"\"Overwrite model.train with this function to make sure train/eval mode\n does not change anymore.\"\"\"\n return self" }, { "identifier": "default", "path": "lvdm/comm...
import logging import os import random import numpy as np import pytorch_lightning as pl import torch import torch.nn as nn from contextlib import contextmanager from functools import partial from einops import rearrange, repeat from tqdm import tqdm from pytorch_lightning.utilities import rank_zero_only from torch.optim.lr_scheduler import CosineAnnealingLR, LambdaLR from torchvision.utils import make_grid from lvdm.basics import disabled_train from lvdm.common import default, exists, extract_into_tensor, noise_like from lvdm.distributions import DiagonalGaussianDistribution, normal_kl from lvdm.ema import LitEma from lvdm.models.samplers.ddim import DDIMSampler from lvdm.models.utils_diffusion import make_beta_schedule from utils.utils import instantiate_from_config
8,589
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) if self.parameterization == "eps": lvlb_weights = self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)) elif self.parameterization == "x0": lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod)) else: raise NotImplementedError("mu not supported") # TODO how to choose this term lvlb_weights[0] = lvlb_weights[1] self.register_buffer('lvlb_weights', lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: mainlogger.info(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: mainlogger.info(f"{context}: Restored training weights") def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): mainlogger.info("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) mainlogger.info(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: mainlogger.info(f"Missing Keys: {missing}") if len(unexpected) > 0: mainlogger.info(f"Unexpected Keys: {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop((batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None):
""" wild mixture of https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py https://github.com/CompVis/taming-transformers -- merci """ mainlogger = logging.getLogger('mainlogger') __conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} 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=None, 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 mainlogger.info(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.channels = channels self.temporal_length = unet_config.params.temporal_length self.image_size = image_size # try conv? if isinstance(self.image_size, int): self.image_size = [self.image_size, self.image_size] 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) mainlogger.info(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if monitor is not None: self.monitor = monitor if ckpt_path is not None: self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet) self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) self.loss_type = loss_type self.learn_logvar = learn_logvar self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) if self.learn_logvar: self.logvar = nn.Parameter(self.logvar, requires_grad=True) def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): if exists(given_betas): betas = given_betas else: betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s) alphas = 1. - betas alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) timesteps, = betas.shape self.num_timesteps = int(timesteps) self.linear_start = linear_start self.linear_end = linear_end assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' to_torch = partial(torch.tensor, dtype=torch.float32) self.register_buffer('betas', to_torch(betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) # calculations for diffusion q(x_t | x_{t-1}) and others self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) # calculations for posterior q(x_{t-1} | x_t, x_0) posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / ( 1. - alphas_cumprod) + self.v_posterior * betas # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) self.register_buffer('posterior_variance', to_torch(posterior_variance)) # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20)))) self.register_buffer('posterior_mean_coef1', to_torch( betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod))) self.register_buffer('posterior_mean_coef2', to_torch( (1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod))) if self.parameterization == "eps": lvlb_weights = self.betas ** 2 / ( 2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)) elif self.parameterization == "x0": lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod)) else: raise NotImplementedError("mu not supported") # TODO how to choose this term lvlb_weights[0] = lvlb_weights[1] self.register_buffer('lvlb_weights', lvlb_weights, persistent=False) assert not torch.isnan(self.lvlb_weights).all() @contextmanager def ema_scope(self, context=None): if self.use_ema: self.model_ema.store(self.model.parameters()) self.model_ema.copy_to(self.model) if context is not None: mainlogger.info(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: mainlogger.info(f"{context}: Restored training weights") def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): mainlogger.info("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) mainlogger.info(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: mainlogger.info(f"Missing Keys: {missing}") if len(unexpected) > 0: mainlogger.info(f"Unexpected Keys: {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop((batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None):
noise = default(noise, lambda: torch.randn_like(x_start))
1
2023-12-06 07:27:45+00:00
12k
TianxingWu/FreeInit
examples/AnimateDiff/animatediff/models/unet.py
[ { "identifier": "CrossAttnDownBlock3D", "path": "examples/AnimateDiff/animatediff/models/unet_blocks.py", "snippet": "class CrossAttnDownBlock3D(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n temb_channels: int,\n dropout: float = 0.0...
from dataclasses import dataclass from typing import List, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.modeling_utils import ModelMixin from diffusers.utils import BaseOutput, logging from diffusers.models.embeddings import TimestepEmbedding, Timesteps from .unet_blocks import ( CrossAttnDownBlock3D, CrossAttnUpBlock3D, DownBlock3D, UNetMidBlock3DCrossAttn, UpBlock3D, get_down_block, get_up_block, ) from .resnet import InflatedConv3d, InflatedGroupNorm from diffusers.utils import WEIGHTS_NAME import os import json import pdb import torch import torch.nn as nn import torch.utils.checkpoint
8,036
in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ( "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D", ), mid_block_type: str = "UNetMidBlock3DCrossAttn", up_block_types: Tuple[str] = ( "UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D" ), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", use_inflated_groupnorm=False, # Additional use_motion_module = False, motion_module_resolutions = ( 1,2,4,8 ), motion_module_mid_block = False, motion_module_decoder_only = False, motion_module_type = None, motion_module_kwargs = {}, unet_use_cross_frame_attention = None, unet_use_temporal_attention = None, ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): res = 2 ** i input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block, in_channels=input_channel, out_channels=output_channel, temb_channels=time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_inflated_groupnorm=use_inflated_groupnorm, use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock3DCrossAttn":
# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNet3DConditionOutput(BaseOutput): sample: torch.FloatTensor class UNet3DConditionModel(ModelMixin, ConfigMixin): _supports_gradient_checkpointing = True @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 4, out_channels: int = 4, center_input_sample: bool = False, flip_sin_to_cos: bool = True, freq_shift: int = 0, down_block_types: Tuple[str] = ( "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D", ), mid_block_type: str = "UNetMidBlock3DCrossAttn", up_block_types: Tuple[str] = ( "UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D" ), only_cross_attention: Union[bool, Tuple[bool]] = False, block_out_channels: Tuple[int] = (320, 640, 1280, 1280), layers_per_block: int = 2, downsample_padding: int = 1, mid_block_scale_factor: float = 1, act_fn: str = "silu", norm_num_groups: int = 32, norm_eps: float = 1e-5, cross_attention_dim: int = 1280, attention_head_dim: Union[int, Tuple[int]] = 8, dual_cross_attention: bool = False, use_linear_projection: bool = False, class_embed_type: Optional[str] = None, num_class_embeds: Optional[int] = None, upcast_attention: bool = False, resnet_time_scale_shift: str = "default", use_inflated_groupnorm=False, # Additional use_motion_module = False, motion_module_resolutions = ( 1,2,4,8 ), motion_module_mid_block = False, motion_module_decoder_only = False, motion_module_type = None, motion_module_kwargs = {}, unet_use_cross_frame_attention = None, unet_use_temporal_attention = None, ): super().__init__() self.sample_size = sample_size time_embed_dim = block_out_channels[0] * 4 # input self.conv_in = InflatedConv3d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) # time self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) # class embedding if class_embed_type is None and num_class_embeds is not None: self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim) elif class_embed_type == "timestep": self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) elif class_embed_type == "identity": self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim) else: self.class_embedding = None self.down_blocks = nn.ModuleList([]) self.mid_block = None self.up_blocks = nn.ModuleList([]) if isinstance(only_cross_attention, bool): only_cross_attention = [only_cross_attention] * len(down_block_types) if isinstance(attention_head_dim, int): attention_head_dim = (attention_head_dim,) * len(down_block_types) # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): res = 2 ** i input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block, in_channels=input_channel, out_channels=output_channel, temb_channels=time_embed_dim, add_downsample=not is_final_block, resnet_eps=norm_eps, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[i], downsample_padding=downsample_padding, dual_cross_attention=dual_cross_attention, use_linear_projection=use_linear_projection, only_cross_attention=only_cross_attention[i], upcast_attention=upcast_attention, resnet_time_scale_shift=resnet_time_scale_shift, unet_use_cross_frame_attention=unet_use_cross_frame_attention, unet_use_temporal_attention=unet_use_temporal_attention, use_inflated_groupnorm=use_inflated_groupnorm, use_motion_module=use_motion_module and (res in motion_module_resolutions) and (not motion_module_decoder_only), motion_module_type=motion_module_type, motion_module_kwargs=motion_module_kwargs, ) self.down_blocks.append(down_block) # mid if mid_block_type == "UNetMidBlock3DCrossAttn":
self.mid_block = UNetMidBlock3DCrossAttn(
3
2023-12-12 13:11:24+00:00
12k
allenai/unified-io-2
t5x/precompile.py
[ { "identifier": "models", "path": "t5x/models.py", "snippet": "class TokensIdsToLogitsCallable(typing_extensions.Protocol):\nclass DecodeFnCallable(typing_extensions.Protocol):\nclass BaseModel(abc.ABC):\nclass BaseTransformerModel(BaseModel):\nclass EncoderDecoderModel(BaseTransformerModel):\nclass Dec...
import os import clu.data import jax import numpy as np import t5.data.mixtures # pylint:disable=unused-import import tensorflow as tf from typing import Callable, Optional from jax import random from t5x import models from t5x import partitioning from t5x import trainer as trainer_lib from t5x import utils
8,427
# Copyright 2022 The T5X Authors. # # 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. r"""Precompile and generates HLO from TPU metadata backend. TPU Metadata backend is a TPU backend without real TPU devices while supporting any TPU topologies, to allow work that doesn't require real TPUs to run as if it is, e.g., compiling/lowering a HLO graph with the backend. Ideally, the precompile defaults to cpu backend for default device array placement since metadata backend does not have memory allocation. The pjit function is pinned to use available TPU Metadata backend, for getting a proper lowering under TPU mesh. """ def precompile( *,
# Copyright 2022 The T5X Authors. # # 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. r"""Precompile and generates HLO from TPU metadata backend. TPU Metadata backend is a TPU backend without real TPU devices while supporting any TPU topologies, to allow work that doesn't require real TPUs to run as if it is, e.g., compiling/lowering a HLO graph with the backend. Ideally, the precompile defaults to cpu backend for default device array placement since metadata backend does not have memory allocation. The pjit function is pinned to use available TPU Metadata backend, for getting a proper lowering under TPU mesh. """ def precompile( *,
model: models.BaseTransformerModel,
0
2023-12-12 20:23:33+00:00
12k
SafeAILab/EAGLE
train/main.py
[ { "identifier": "Model", "path": "model/cnets.py", "snippet": "class Model(nn.Module):\r\n def __init__(self,config,load_emb=False,path=None):\r\n super().__init__()\r\n\r\n\r\n\r\n\r\n self.gradient_checkpointing = True\r\n self.padding_idx = config.pad_token_id\r\n self....
import argparse import json import os import torch import numpy as np import wandb from safetensors import safe_open from accelerate import Accelerator from accelerate.utils import set_seed from model.cnets import Model from model.configs import EConfig from typing import Any, Dict, List from torch import nn, optim from torch.utils.data import Dataset, DataLoader from tqdm import tqdm from transformers import get_linear_schedule_with_warmup, AutoConfig
9,193
max_length = max(item['hidden_state_big'].shape[1] for item in features) batch_input_ids = torch.cat([self.paddingtensor2D(item['input_ids'], max_length) for item in features]) batch_hidden_states = torch.cat([self.paddingtensor(item['hidden_state_big'], max_length) for item in features]) batch_target = torch.cat([self.paddingtensor(item['target'], max_length) for item in features]) batch_loss_mask = torch.tensor( [item['loss_mask'] + [0] * (max_length - len(item['loss_mask'])) for item in features]) batch_attention_mask = torch.tensor( [item['attention_mask'] + [0] * (max_length - len(item['attention_mask'])) for item in features]) # batch_loss_mask = torch.ones_like(batch_loss_mask) # batch_attention_mask=torch.ones_like(batch_attention_mask) batch = { "input_ids": batch_input_ids, "hidden_states": batch_hidden_states, "target": batch_target, "attention_mask": batch_attention_mask, "loss_mask": batch_loss_mask, } return batch def top_accuracy(output, target, topk=(1,)): # output.shape (bs, num_classes), target.shape (bs, ) """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) res.append(correct_k) return res @torch.no_grad() def getkacc(model, data, head, max_length=5): hidden_states = data["hidden_states"] input_ids = data["input_ids"] # attention_mask=data["attention_mask"] loss_mask = data["loss_mask"] # sample_mask=data["sample_mask"] target = data["target"] total = [0 for _ in range(max_length)] correct = [0 for _ in range(max_length)] bs, sl = hidden_states.shape[0], hidden_states.shape[1] target_headout = head(target) hidden_states_headout = head(hidden_states) for i in range(bs): for j in range(sl): single_hidden_states = hidden_states[i, :j] single_input_ids = input_ids[i, :j] single_hidden_states = single_hidden_states[None, :, :] single_input_ids = single_input_ids[None, :] for k in range(max_length): if loss_mask[i, single_hidden_states.shape[1] - 1] == 0: break tmp_in_target_headout = hidden_states_headout[i, single_hidden_states.shape[1] - 1] tmp_out_target_headout = target_headout[i, single_hidden_states.shape[1] - 1] target_in_token = torch.argmax(tmp_in_target_headout) target_out_token = torch.argmax(tmp_out_target_headout) tmp_token = input_ids[i, single_hidden_states.shape[1] - 1] # tmp_sample_mask=sample_mask[i,single_hidden_states.shape[1]-1] if not (target_in_token == tmp_token): break out_hidden = model(single_hidden_states, input_ids=single_input_ids) last_hidden = out_hidden[:, -1] last_headout = head(last_hidden) token = torch.argmax(last_headout) total[k] += 1 if token == target_out_token: correct[k] += 1 else: for kk in range(k + 1, max_length): total[kk] += 1 break single_hidden_states = torch.cat((single_hidden_states, out_hidden[:, -1:]), dim=1) single_input_ids = torch.cat((single_input_ids, torch.tensor([[token]]).to(single_input_ids.device)), dim=1) acc = [correct[i] / total[i] for i in range(len(correct))] return acc if train_config["data_noise"]: if train_config["noise"] == "uniform": aug = AddUniformNoise(std=train_config["std"]) else: aug = AddGaussianNoise(mean=train_config["mean"], std=train_config["std"]) else: aug = None datapath = list_files(train_config["datapath"]) traindatapath = datapath[:int(len(datapath) * 0.95)] testdatapath = datapath[int(len(datapath) * 0.95):] # print('td',train_config["datapath"]) # print(datapath) # exit() traindataset = CustomDataset(traindatapath, transform=aug) testdataset = CustomDataset(testdatapath) train_loader = DataLoader(traindataset, batch_size=train_config["bs"], shuffle=True, collate_fn=DataCollatorWithPadding(), num_workers=train_config["num_workers"], pin_memory=True) test_loader = DataLoader(testdataset, batch_size=train_config["bs"], shuffle=False, collate_fn=DataCollatorWithPadding(), num_workers=train_config["num_workers"], pin_memory=True) # for batch_data in train_loader: # print(batch_data) if accelerator.is_main_process: if not os.path.exists(args.cpdir): os.makedirs(args.cpdir)
parser = argparse.ArgumentParser(description='sp') parser.add_argument('--basepath', type=str, default='/home/lyh/weights/hf/vicuna_v13/7B/') parser.add_argument('--configpath', type=str, default="config.json") parser.add_argument('--lr', type=float, default=3e-5) parser.add_argument('--bs', type=int, default=4) parser.add_argument('--gradient-accumulation-steps', type=int, default=8) parser.add_argument('--tmpdir', type=str, default='0') parser.add_argument('--outdir', type=str, default='0') parser.add_argument('--cpdir', type=str, default='0') args = parser.parse_args() train_config = { "lr": args.lr, "bs": args.bs, "gradient_accumulation_steps": args.gradient_accumulation_steps, "datapath": f"{args.tmpdir}", "is_warmup": True, "num_epochs": 20, # Depending on your data and model size, the larger the model, the higher the sample efficiency. We recommend setting it between 20-40. "num_warmup_steps": 2000, "total_steps": 800000, "p_w": 0.1, "v_w": 1.0, "head_w": 0.1, "num_workers": 2, "embeding": True, "act": "No", "data_noise": True, "noise": "uniform", "mean": 0.0, "std": 0.2, "residual": "true,norm", "max_len": 2048, # During training, truncating the training sequences means that the larger the setting, the more training data is used, and the better the effect, but it also consumes more VRAM. "config_path": args.configpath, "b1": 0.9, "b2": 0.95, "grad_clip": 0.5, "save_freq": 5 } # from transformers import AutoModelForCausalLM, AutoTokenizer,AutoModelForSequenceClassification # os.environ["CUDA_VISIBLE_DEVICES"] = "0,1" torch.backends.cuda.matmul.allow_tf32 = True set_seed(0) accelerator = Accelerator(mixed_precision='bf16', gradient_accumulation_steps=train_config["gradient_accumulation_steps"]) # import accelerate if accelerator.is_main_process: wandb.init(project="ess", entity="yuhui-li", config=train_config) baseconfig = AutoConfig.from_pretrained(args.basepath) head = torch.nn.Linear(baseconfig.hidden_size, baseconfig.vocab_size, bias=False) try: with open(os.path.join(args.basepath, "model.safetensors.index.json"), "r") as f: index_json = json.loads(f.read()) head_path = index_json["weight_map"]["lm_head.weight"] with safe_open(os.path.join(args.basepath, head_path), framework="pt", device="cpu") as f: tensor_slice = f.get_slice("lm_head.weight") vocab_size, hidden_dim = tensor_slice.get_shape() tensor = tensor_slice[:, :hidden_dim].float() except: with open(os.path.join(args.basepath, "pytorch_model.bin.index.json"), "r") as f: index_json = json.loads(f.read()) head_path = index_json["weight_map"]["lm_head.weight"] weights = torch.load(os.path.join(args.basepath, head_path)) tensor = weights["lm_head.weight"].float() head.weight.data = tensor head.eval() for param in head.parameters(): param.requires_grad = False def list_files(path): datapath = [] for root, directories, files in os.walk(path): for file in files: file_path = os.path.join(root, file) datapath.append(file_path) return datapath class AddGaussianNoise: def __init__(self, mean=0.0, std=0.0): self.mean = mean self.std = std def __call__(self, data): tensor = data["hidden_state_big"] noise = torch.randn(tensor.size()) * self.std + self.mean noisy_tensor = tensor + noise data["hidden_state_big"] = noisy_tensor return data class AddUniformNoise: def __init__(self, std=0.0): self.std = std def __call__(self, data): tensor = data["hidden_state_big"] noise = (torch.rand_like(tensor) - 0.5) * self.std * 512 / tensor.shape[1] noisy_tensor = tensor + noise data["hidden_state_big"] = noisy_tensor return data class CustomDataset(Dataset): def __init__(self, datapath, transform=None): self.data = datapath self.transform = transform def __len__(self): return len(self.data) def __getitem__(self, index): # try: data = torch.load(self.data[index]) new_data = {} hidden_state = data['hidden_state'][:train_config["max_len"]][None, :] input_ids = data['input_ids'][:train_config["max_len"]][None, :] loss_mask = data["loss_mask"][:train_config["max_len"]][None, :] # except: # with open("error_path.txt", "w") as file: # file.write(self.data[index]) # print('error path',self.data[index]) length = hidden_state.shape[1] # length_q = data['query_ids'].shape[1] attention_mask = [1] * length loss_mask = loss_mask[0].tolist() loss_mask[-1] = 0 input_ids_target = input_ids[:, 1:] zeropadding = torch.tensor([[0]]) input_ids_target = torch.cat((input_ids_target, zeropadding), dim=1) target = hidden_state[:, 1:, :] zeropadding = torch.zeros(1, 1, target.shape[2]) target = torch.cat((target, zeropadding), dim=1) loss_mask[-1] = 0 new_data["attention_mask"] = attention_mask new_data["loss_mask"] = loss_mask new_data["target"] = target new_data["hidden_state_big"] = hidden_state new_data["input_ids"] = input_ids_target # sample = torch.cat((data['xs'],data['xb'])) # sample=torch.cat((self.data[index]['x'],self.data[index]['logits'])) # label = data['y'] if self.transform: new_data = self.transform(new_data) return new_data class DataCollatorWithPadding: def paddingtensor(self, intensors, N): B, n, S = intensors.shape # padding_tensor = torch.zeros(B, N - n, S,dtype=intensors.dtype) padding_tensor = torch.zeros(B, N - n, S) outtensors = torch.cat((intensors, padding_tensor), dim=1) return outtensors def paddingtensor2D(self, intensors, N): B, n = intensors.shape padding_tensor = torch.zeros(B, N - n, dtype=intensors.dtype) outtensors = torch.cat((intensors, padding_tensor), dim=1) return outtensors def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: max_length = max(item['hidden_state_big'].shape[1] for item in features) batch_input_ids = torch.cat([self.paddingtensor2D(item['input_ids'], max_length) for item in features]) batch_hidden_states = torch.cat([self.paddingtensor(item['hidden_state_big'], max_length) for item in features]) batch_target = torch.cat([self.paddingtensor(item['target'], max_length) for item in features]) batch_loss_mask = torch.tensor( [item['loss_mask'] + [0] * (max_length - len(item['loss_mask'])) for item in features]) batch_attention_mask = torch.tensor( [item['attention_mask'] + [0] * (max_length - len(item['attention_mask'])) for item in features]) # batch_loss_mask = torch.ones_like(batch_loss_mask) # batch_attention_mask=torch.ones_like(batch_attention_mask) batch = { "input_ids": batch_input_ids, "hidden_states": batch_hidden_states, "target": batch_target, "attention_mask": batch_attention_mask, "loss_mask": batch_loss_mask, } return batch def top_accuracy(output, target, topk=(1,)): # output.shape (bs, num_classes), target.shape (bs, ) """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) res.append(correct_k) return res @torch.no_grad() def getkacc(model, data, head, max_length=5): hidden_states = data["hidden_states"] input_ids = data["input_ids"] # attention_mask=data["attention_mask"] loss_mask = data["loss_mask"] # sample_mask=data["sample_mask"] target = data["target"] total = [0 for _ in range(max_length)] correct = [0 for _ in range(max_length)] bs, sl = hidden_states.shape[0], hidden_states.shape[1] target_headout = head(target) hidden_states_headout = head(hidden_states) for i in range(bs): for j in range(sl): single_hidden_states = hidden_states[i, :j] single_input_ids = input_ids[i, :j] single_hidden_states = single_hidden_states[None, :, :] single_input_ids = single_input_ids[None, :] for k in range(max_length): if loss_mask[i, single_hidden_states.shape[1] - 1] == 0: break tmp_in_target_headout = hidden_states_headout[i, single_hidden_states.shape[1] - 1] tmp_out_target_headout = target_headout[i, single_hidden_states.shape[1] - 1] target_in_token = torch.argmax(tmp_in_target_headout) target_out_token = torch.argmax(tmp_out_target_headout) tmp_token = input_ids[i, single_hidden_states.shape[1] - 1] # tmp_sample_mask=sample_mask[i,single_hidden_states.shape[1]-1] if not (target_in_token == tmp_token): break out_hidden = model(single_hidden_states, input_ids=single_input_ids) last_hidden = out_hidden[:, -1] last_headout = head(last_hidden) token = torch.argmax(last_headout) total[k] += 1 if token == target_out_token: correct[k] += 1 else: for kk in range(k + 1, max_length): total[kk] += 1 break single_hidden_states = torch.cat((single_hidden_states, out_hidden[:, -1:]), dim=1) single_input_ids = torch.cat((single_input_ids, torch.tensor([[token]]).to(single_input_ids.device)), dim=1) acc = [correct[i] / total[i] for i in range(len(correct))] return acc if train_config["data_noise"]: if train_config["noise"] == "uniform": aug = AddUniformNoise(std=train_config["std"]) else: aug = AddGaussianNoise(mean=train_config["mean"], std=train_config["std"]) else: aug = None datapath = list_files(train_config["datapath"]) traindatapath = datapath[:int(len(datapath) * 0.95)] testdatapath = datapath[int(len(datapath) * 0.95):] # print('td',train_config["datapath"]) # print(datapath) # exit() traindataset = CustomDataset(traindatapath, transform=aug) testdataset = CustomDataset(testdatapath) train_loader = DataLoader(traindataset, batch_size=train_config["bs"], shuffle=True, collate_fn=DataCollatorWithPadding(), num_workers=train_config["num_workers"], pin_memory=True) test_loader = DataLoader(testdataset, batch_size=train_config["bs"], shuffle=False, collate_fn=DataCollatorWithPadding(), num_workers=train_config["num_workers"], pin_memory=True) # for batch_data in train_loader: # print(batch_data) if accelerator.is_main_process: if not os.path.exists(args.cpdir): os.makedirs(args.cpdir)
config = EConfig.from_pretrained(train_config["config_path"])
1
2023-12-07 19:08:39+00:00
12k
zju3dv/EasyVolcap
scripts/ray_tracing/ray_tracing.py
[ { "identifier": "log", "path": "easyvolcap/utils/console_utils.py", "snippet": "def log(*stuff,\n back=1,\n file: Optional[IO[str]] = None,\n no_prefix=False,\n module_color=blue,\n func_color=green,\n console: Optional[Console] = console,\n **kwargs):\n ...
import os import torch import argparse import numpy as np import sys from tqdm import tqdm from os.path import join from termcolor import colored from bvh_ray_tracing import BVH from pytorch3d.structures import Meshes from easyvolcap.utils.console_utils import log from easyvolcap.utils.base_utils import dotdict from easyvolcap.utils.easy_utils import read_camera from easyvolcap.utils.parallel_utils import parallel_execution from easyvolcap.utils.data_utils import load_mesh, save_unchanged from easyvolcap.utils.net_utils import multi_gather_tris, normalize from easyvolcap.utils.relight_utils import read_hdr, sample_envmap_image from easyvolcap.utils.sh_utils import spher2cart, spherical_uniform_sampling_upper from easyvolcap.utils.raster_utils import render_nvdiffrast, get_ndc_perspective_matrix
10,425
if surf.ndim == 4: surf = surf.view(surf.shape[0], -1, 3) if norm.ndim == 4: norm = norm.view(surf.shape[0], -1, 3) B, P, _ = surf.shape T = B * N * P # Generate sample_count uniformly and stratified samples over the sphere # See http://www.bogotobogo.com/Algorithms/uniform_distribution_sphere.php theta, phi = spherical_uniform_sampling_upper(T, device=surf.device) # T, T, ray_d = spher2cart(theta, phi) # T, 3, z always bigger than zero # Preparing shapes norm = norm[:, None].expand(B, N, P, 3).reshape(T, 3) # T, 3 ray_o = surf[:, None].expand(B, N, P, 3).reshape(T, 3) # T, 3 # Transform ray_d to be pointing upward from normal direction R = torch.zeros([T, 3, 3], device=norm.device) R[..., 0, 0] = 1.0 R[..., :3, 2] = norm # c2w, z axis is normal direction R[..., :3, 1] = normalize(torch.cross(R[..., :3, 2], R[..., :3, 0])) R[..., :3, 0] = normalize(torch.cross(R[..., :3, 1], R[..., :3, 2])) ray_d = (R @ ray_d[..., None])[..., 0] # Compute shading ldot = (ray_d * norm).sum(dim=-1).reshape(T) # T def ray_tracing_intersection(ray_o: torch.Tensor, ray_d: torch.Tensor, tris: torch.Tensor) -> torch.Tensor: # assume all tris batch are the same sh = ray_o.shape # B, S, 3 tris = tris[:1] # 1, F, 3, 3 ray_o = ray_o.view(-1, 3)[None] # 1, B * S, 3 ray_d = ray_d.view(-1, 3)[None] # 1, B * S, 3 bvh = BVH() # is this too wasteful, reconstructing the BVH in every iteration? # pts: 1, P, 3 dists_sq, points, face_ids, barys = bvh(tris, ray_o + ray_d * 0.01, ray_d) # 1, P, 3 lvis: torch.Tensor = 1 - (dists_sq > 0).float() # all barycentri coordinates are valid -> intersection -> zero vis lvis = lvis.view(*sh[:-1]) # TODO: messy shapes lvis.nan_to_num(0.) # sometimes the moller trumbore returns nan...? return lvis # Here lren is the indices of the ray direction and pixel to render # Perform rendering on lren ray-pixel pair if compute_lvis: lvis = ray_tracing_intersection(ray_o, ray_d, tris) else: lvis = torch.ones_like(ldot) lvis = lvis.view(B, N, P) ldot = ldot.view(B, N, P) ray_d = ray_d.view(B, N, P, 3) return lvis, ldot, ray_d def main(): """ We have a few assumptions about the ground truth rendering process We require a pivot mesh for textures, and other meshes can be loaded with only the vertices Since animation should only be about changing the positions of the vertices (without topology warps) We don't need to render the full model, only 1. Normal (geometry only) 2. Ray-tracing soft shadow (geometry only) (visibility) 3. Albedo (diffuse albedo map) 4. Roughness (roughness value map) 5. Full rendering pipeline? (no, since the material model and indirection illumation is not implemented) What do we do? """ # All other related stuff should have been loaded implicitly from the object file's definition parser = argparse.ArgumentParser() parser.add_argument('--mode', type=str, default='normal', choices=['normal', 'depth', 'surf', 'shade', 'ibl', 'ao']) parser.add_argument('--ext', type=str, default='.obj') # should not change this parser.add_argument('--device', type=str, default='cuda') # should not change this # Input output related parser.add_argument('--data_root', type=str, default='data/synthetic_human/jody') parser.add_argument('--mesh', type=str, default="object/000000.obj") parser.add_argument('--width', type=str, default=1024) parser.add_argument('--height', type=str, default=1024) parser.add_argument('--ratio', type=float, default=0.5) parser.add_argument('--extri', type=str, default='extri.yml') parser.add_argument('--intri', type=str, default='intri.yml') parser.add_argument('--output', type=str, default='ray_tracing') # Environment map related parser.add_argument('--envmap_root', type=str, default='data/lighting/16x32') parser.add_argument('--envmap', type=str, default='gym_entrance.hdr') # Visualization related parser.add_argument('--depth_min', type=float, default=1.0) parser.add_argument('--depth_max', type=float, default=5.0) parser.add_argument('--surf_min', type=float, default=-3.0) parser.add_argument('--surf_max', type=float, default=3.0) parser.add_argument('--shading_albedo', type=float, default=0.8) # Misc stuff # parser.add_argument('--remesh', action='store_true', help='whether to perform remesh before the visibility computation') # slow parser.add_argument('--transpose', action='store_true', help='transpose the y and z axis for the synthetic human dataset') parser.add_argument('--ground', action='store_true', help='whether the visibility term should consider the ground?') parser.add_argument('--sub', nargs='*') # Visibility and shading related parser.add_argument('--chunk_size', type=int, default=2500, help='chunk size of monte carlo samples (w.r.t. 1 x 512 x 512 image)') parser.add_argument('--n_light_sample', type=int, default=50000, help='number of monte carlo samples for each pixel') parser.add_argument('--ground_origin', type=float, default=[0, 0, 0], required=False, nargs='*', help='origin of the ground') parser.add_argument('--ground_normal', type=float, default=[0, 0, 1], required=False, nargs='*', help='normal of the ground') # Prepare arguments args = parser.parse_args() args.mesh = join(args.data_root, args.mesh) args.extri = join(args.data_root, args.extri) args.intri = join(args.data_root, args.intri) args.output = join(args.data_root, args.output, args.mode) # {data_root}/ray_tracing/{mode} args.envmap = join(args.envmap_root, args.envmap) # do not merge envmap with data_root assert args.ext == '.obj', 'Only obj files are supported' # Loading camera intrinsics and extrinsics log(f'Loading cameras from {colored(args.intri, "blue")} and {colored(args.extri, "blue")} onto {colored(args.device, "magenta")}')
# this file loads obj with textures and mlt files, then perform rasteization with ray traced shadow # it can also render components like normal, albedo, roughness, visibility etc. # this should only be used for rendering ground truth values to compute metrics # for visibility, we should compute metrics on visibility or the whole shading? only for soft-shadow? # maybe both would be better... # fmt: off sys.path.append(".") # fmt: on def light_visibility(surf: torch.Tensor, # B, P, 3 norm: torch.Tensor, # B, P, 3 tris: torch.Tensor, N: int = 100, # number of samples per pixel (randomly distribute on sphere) compute_lvis: bool = True, ): # this function will compute both lvis and ldot # Prepare shapes of verts and faces (could have same batch size as surf and norm) if surf.ndim == 4: surf = surf.view(surf.shape[0], -1, 3) if norm.ndim == 4: norm = norm.view(surf.shape[0], -1, 3) B, P, _ = surf.shape T = B * N * P # Generate sample_count uniformly and stratified samples over the sphere # See http://www.bogotobogo.com/Algorithms/uniform_distribution_sphere.php theta, phi = spherical_uniform_sampling_upper(T, device=surf.device) # T, T, ray_d = spher2cart(theta, phi) # T, 3, z always bigger than zero # Preparing shapes norm = norm[:, None].expand(B, N, P, 3).reshape(T, 3) # T, 3 ray_o = surf[:, None].expand(B, N, P, 3).reshape(T, 3) # T, 3 # Transform ray_d to be pointing upward from normal direction R = torch.zeros([T, 3, 3], device=norm.device) R[..., 0, 0] = 1.0 R[..., :3, 2] = norm # c2w, z axis is normal direction R[..., :3, 1] = normalize(torch.cross(R[..., :3, 2], R[..., :3, 0])) R[..., :3, 0] = normalize(torch.cross(R[..., :3, 1], R[..., :3, 2])) ray_d = (R @ ray_d[..., None])[..., 0] # Compute shading ldot = (ray_d * norm).sum(dim=-1).reshape(T) # T def ray_tracing_intersection(ray_o: torch.Tensor, ray_d: torch.Tensor, tris: torch.Tensor) -> torch.Tensor: # assume all tris batch are the same sh = ray_o.shape # B, S, 3 tris = tris[:1] # 1, F, 3, 3 ray_o = ray_o.view(-1, 3)[None] # 1, B * S, 3 ray_d = ray_d.view(-1, 3)[None] # 1, B * S, 3 bvh = BVH() # is this too wasteful, reconstructing the BVH in every iteration? # pts: 1, P, 3 dists_sq, points, face_ids, barys = bvh(tris, ray_o + ray_d * 0.01, ray_d) # 1, P, 3 lvis: torch.Tensor = 1 - (dists_sq > 0).float() # all barycentri coordinates are valid -> intersection -> zero vis lvis = lvis.view(*sh[:-1]) # TODO: messy shapes lvis.nan_to_num(0.) # sometimes the moller trumbore returns nan...? return lvis # Here lren is the indices of the ray direction and pixel to render # Perform rendering on lren ray-pixel pair if compute_lvis: lvis = ray_tracing_intersection(ray_o, ray_d, tris) else: lvis = torch.ones_like(ldot) lvis = lvis.view(B, N, P) ldot = ldot.view(B, N, P) ray_d = ray_d.view(B, N, P, 3) return lvis, ldot, ray_d def main(): """ We have a few assumptions about the ground truth rendering process We require a pivot mesh for textures, and other meshes can be loaded with only the vertices Since animation should only be about changing the positions of the vertices (without topology warps) We don't need to render the full model, only 1. Normal (geometry only) 2. Ray-tracing soft shadow (geometry only) (visibility) 3. Albedo (diffuse albedo map) 4. Roughness (roughness value map) 5. Full rendering pipeline? (no, since the material model and indirection illumation is not implemented) What do we do? """ # All other related stuff should have been loaded implicitly from the object file's definition parser = argparse.ArgumentParser() parser.add_argument('--mode', type=str, default='normal', choices=['normal', 'depth', 'surf', 'shade', 'ibl', 'ao']) parser.add_argument('--ext', type=str, default='.obj') # should not change this parser.add_argument('--device', type=str, default='cuda') # should not change this # Input output related parser.add_argument('--data_root', type=str, default='data/synthetic_human/jody') parser.add_argument('--mesh', type=str, default="object/000000.obj") parser.add_argument('--width', type=str, default=1024) parser.add_argument('--height', type=str, default=1024) parser.add_argument('--ratio', type=float, default=0.5) parser.add_argument('--extri', type=str, default='extri.yml') parser.add_argument('--intri', type=str, default='intri.yml') parser.add_argument('--output', type=str, default='ray_tracing') # Environment map related parser.add_argument('--envmap_root', type=str, default='data/lighting/16x32') parser.add_argument('--envmap', type=str, default='gym_entrance.hdr') # Visualization related parser.add_argument('--depth_min', type=float, default=1.0) parser.add_argument('--depth_max', type=float, default=5.0) parser.add_argument('--surf_min', type=float, default=-3.0) parser.add_argument('--surf_max', type=float, default=3.0) parser.add_argument('--shading_albedo', type=float, default=0.8) # Misc stuff # parser.add_argument('--remesh', action='store_true', help='whether to perform remesh before the visibility computation') # slow parser.add_argument('--transpose', action='store_true', help='transpose the y and z axis for the synthetic human dataset') parser.add_argument('--ground', action='store_true', help='whether the visibility term should consider the ground?') parser.add_argument('--sub', nargs='*') # Visibility and shading related parser.add_argument('--chunk_size', type=int, default=2500, help='chunk size of monte carlo samples (w.r.t. 1 x 512 x 512 image)') parser.add_argument('--n_light_sample', type=int, default=50000, help='number of monte carlo samples for each pixel') parser.add_argument('--ground_origin', type=float, default=[0, 0, 0], required=False, nargs='*', help='origin of the ground') parser.add_argument('--ground_normal', type=float, default=[0, 0, 1], required=False, nargs='*', help='normal of the ground') # Prepare arguments args = parser.parse_args() args.mesh = join(args.data_root, args.mesh) args.extri = join(args.data_root, args.extri) args.intri = join(args.data_root, args.intri) args.output = join(args.data_root, args.output, args.mode) # {data_root}/ray_tracing/{mode} args.envmap = join(args.envmap_root, args.envmap) # do not merge envmap with data_root assert args.ext == '.obj', 'Only obj files are supported' # Loading camera intrinsics and extrinsics log(f'Loading cameras from {colored(args.intri, "blue")} and {colored(args.extri, "blue")} onto {colored(args.device, "magenta")}')
camera = read_camera(args.intri, args.extri) # camera dictionary
2
2023-12-07 08:53:42+00:00
12k
alibaba/animate-anything
models/unet_3d_condition_mask.py
[ { "identifier": "CrossAttnDownBlock3D", "path": "models/unet_3d_blocks.py", "snippet": "class CrossAttnDownBlock3D(nn.Module):\n def __init__(\n self,\n in_channels: int,\n out_channels: int,\n temb_channels: int,\n dropout: float = 0.0,\n num_layers: int = 1...
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 diffusers.models.embeddings import TimestepEmbedding, Timesteps from diffusers.models.modeling_utils import ModelMixin from diffusers.models.transformer_temporal import TransformerTemporalModel from einops import rearrange, repeat from .unet_3d_blocks import ( CrossAttnDownBlock3D, CrossAttnUpBlock3D, DownBlock3D, UNetMidBlock3DCrossAttn, UpBlock3D, get_down_block, get_up_block, transformer_g_c ) import torch import torch.nn as nn import torch.utils.checkpoint
8,921
reversed_block_out_channels = list(reversed(block_out_channels)) reversed_attention_head_dim = list(reversed(attention_head_dim)) output_channel = reversed_block_out_channels[0] for i, up_block_type in enumerate(up_block_types): is_final_block = i == len(block_out_channels) - 1 prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] # add upsample block for all BUT final layer if not is_final_block: add_upsample = True self.num_upsamplers += 1 else: add_upsample = False up_block = get_up_block( up_block_type, num_layers=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=False, ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out if norm_num_groups is not None: self.conv_norm_out = nn.GroupNorm( num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps ) self.conv_act = nn.SiLU() else: self.conv_norm_out = None self.conv_act = None conv_out_padding = (conv_out_kernel - 1) // 2 self.conv_out = nn.Conv2d( block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding ) 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, value=False): self.gradient_checkpointing = value self.mid_block.gradient_checkpointing = value for module in self.down_blocks + self.up_blocks:
# 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 = True @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, motion_mask = False, motion_strength = False, ): super().__init__() self.motion_mask = motion_mask self.motion_strength = motion_strength print(f"motion mask {self.motion_mask}, motion_strength {self.motion_strength}") self.sample_size = sample_size self.gradient_checkpointing = False # 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 ) self.conv_in2 = nn.Conv2d( 5, 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, cond_proj_dim=block_out_channels[0], ) self.motion_proj = Timesteps(block_out_channels[0], True, 0) self.motion_embedding = nn.Sequential( nn.Linear(timestep_input_dim, time_embed_dim), nn.SiLU(), nn.Linear(time_embed_dim, time_embed_dim)) nn.init.zeros_(self.motion_embedding[-1].weight) nn.init.zeros_(self.motion_embedding[-1].bias) self.transformer_in = TransformerTemporalModel( num_attention_heads=8, attention_head_dim=attention_head_dim, in_channels=block_out_channels[0], num_layers=1, ) # class embedding self.down_blocks = nn.ModuleList([]) self.up_blocks = nn.ModuleList([]) 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 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=False, ) self.down_blocks.append(down_block) # mid self.mid_block = UNetMidBlock3DCrossAttn( in_channels=block_out_channels[-1], temb_channels=time_embed_dim, resnet_eps=norm_eps, resnet_act_fn=act_fn, output_scale_factor=mid_block_scale_factor, cross_attention_dim=cross_attention_dim, attn_num_head_channels=attention_head_dim[-1], resnet_groups=norm_num_groups, dual_cross_attention=False, ) # 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)) output_channel = reversed_block_out_channels[0] for i, up_block_type in enumerate(up_block_types): is_final_block = i == len(block_out_channels) - 1 prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] # add upsample block for all BUT final layer if not is_final_block: add_upsample = True self.num_upsamplers += 1 else: add_upsample = False up_block = get_up_block( up_block_type, num_layers=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=False, ) self.up_blocks.append(up_block) prev_output_channel = output_channel # out if norm_num_groups is not None: self.conv_norm_out = nn.GroupNorm( num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps ) self.conv_act = nn.SiLU() else: self.conv_norm_out = None self.conv_act = None conv_out_padding = (conv_out_kernel - 1) // 2 self.conv_out = nn.Conv2d( block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding ) 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, value=False): self.gradient_checkpointing = value self.mid_block.gradient_checkpointing = value for module in self.down_blocks + self.up_blocks:
if isinstance(module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)):
0
2023-12-07 08:26:29+00:00
12k
octo-models/octo
scripts/finetune.py
[ { "identifier": "make_single_dataset", "path": "octo/data/dataset.py", "snippet": "def make_single_dataset(\n dataset_kwargs: dict,\n *,\n train: bool,\n traj_transform_kwargs: dict = {},\n frame_transform_kwargs: dict = {},\n) -> dl.DLataset:\n \"\"\"Creates a single dataset from kwar...
import datetime import imp import os import flax import jax import optax import tensorflow as tf import tqdm import wandb from functools import partial from absl import app, flags, logging from flax.traverse_util import flatten_dict from jax.sharding import Mesh, NamedSharding, PartitionSpec from ml_collections import config_flags, ConfigDict from octo.data.dataset import make_single_dataset from octo.model.octo_model import OctoModel from octo.utils.jax_utils import initialize_compilation_cache from octo.utils.spec import ModuleSpec from octo.utils.train_callbacks import ( RolloutVisualizationCallback, SaveCallback, ValidationCallback, VisualizationCallback, ) from octo.utils.train_utils import ( check_config_diff, create_optimizer, format_name_with_config, merge_params, process_text, Timer, TrainState, ) from jax_smi import initialise_tracking # type: ignore
10,139
try: initialise_tracking() except ImportError: pass FLAGS = flags.FLAGS flags.DEFINE_string("name", "experiment", "Experiment name.") flags.DEFINE_bool("debug", False, "Debug config (no wandb logging)") default_config_file = os.path.join( os.path.dirname(__file__), "configs/finetune_config.py" ) config_flags.DEFINE_config_file( "config", default_config_file, "File path to the training hyperparameter configuration.", lock_config=False, ) def main(_): initialize_compilation_cache() devices = jax.devices() logging.info( f""" Octo Finetuning Script ====================== Pretrained model: {FLAGS.config.pretrained_path} Finetuning Dataset: {FLAGS.config.dataset_kwargs.name} Data dir: {FLAGS.config.dataset_kwargs.data_dir} Task Modality: {FLAGS.config.modality} Finetuning Mode: {FLAGS.config.finetuning_mode} # Devices: {jax.device_count()} Batch size: {FLAGS.config.batch_size} ({FLAGS.config.batch_size // len(devices) } per device) # Steps: {FLAGS.config.num_steps} """ ) ######### # # Setup Jax Data Parallelism # ######### assert ( FLAGS.config.batch_size % len(devices) == 0 ), f"Batch size ({FLAGS.config.batch_size}) must be divisible by the number of devices ({len(devices)})" assert ( FLAGS.config.viz_kwargs.eval_batch_size % len(devices) == 0 ), f"Eval batch size ({FLAGS.config.viz_kwargs.eval_batch_size}) must be divisible by the number of devices ({len(devices)})" # create a 1D mesh with a single axis named "batch" mesh = Mesh(jax.devices(), axis_names="batch") # Our batches will be data-parallel sharded -- each device will get a slice of the batch dp_sharding = NamedSharding(mesh, PartitionSpec("batch")) # Our model will be replicated across devices (we are only doing data parallelism, not model parallelism) replicated_sharding = NamedSharding(mesh, PartitionSpec()) # prevent tensorflow from using GPU memory since it's only used for data loading tf.config.set_visible_devices([], "GPU") ######### # # Setup WandB # ######### name = format_name_with_config( FLAGS.name, FLAGS.config.to_dict(), ) wandb_id = "{name}_{time}".format( name=name, time=datetime.datetime.now().strftime("%Y%m%d_%H%M%S"), ) wandb.init( config=FLAGS.config.to_dict(), id=wandb_id, name=name, mode="disabled" if FLAGS.debug else None, **FLAGS.config.wandb, ) ######### # # Load Pretrained model + optionally modify config # ######### pretrained_model = OctoModel.load_pretrained( FLAGS.config.pretrained_path, step=FLAGS.config.pretrained_step, ) flat_config = flax.traverse_util.flatten_dict( pretrained_model.config, keep_empty_nodes=True ) for d_key in flax.traverse_util.flatten_dict( FLAGS.config.get("config_delete_keys", ConfigDict()).to_dict() ): for c_key in list(flat_config.keys()): if ".".join(c_key).startswith(".".join(d_key)): del flat_config[c_key] config = ConfigDict(flax.traverse_util.unflatten_dict(flat_config)) config.update(FLAGS.config.get("update_config", ConfigDict())) config = config.to_dict()
try: initialise_tracking() except ImportError: pass FLAGS = flags.FLAGS flags.DEFINE_string("name", "experiment", "Experiment name.") flags.DEFINE_bool("debug", False, "Debug config (no wandb logging)") default_config_file = os.path.join( os.path.dirname(__file__), "configs/finetune_config.py" ) config_flags.DEFINE_config_file( "config", default_config_file, "File path to the training hyperparameter configuration.", lock_config=False, ) def main(_): initialize_compilation_cache() devices = jax.devices() logging.info( f""" Octo Finetuning Script ====================== Pretrained model: {FLAGS.config.pretrained_path} Finetuning Dataset: {FLAGS.config.dataset_kwargs.name} Data dir: {FLAGS.config.dataset_kwargs.data_dir} Task Modality: {FLAGS.config.modality} Finetuning Mode: {FLAGS.config.finetuning_mode} # Devices: {jax.device_count()} Batch size: {FLAGS.config.batch_size} ({FLAGS.config.batch_size // len(devices) } per device) # Steps: {FLAGS.config.num_steps} """ ) ######### # # Setup Jax Data Parallelism # ######### assert ( FLAGS.config.batch_size % len(devices) == 0 ), f"Batch size ({FLAGS.config.batch_size}) must be divisible by the number of devices ({len(devices)})" assert ( FLAGS.config.viz_kwargs.eval_batch_size % len(devices) == 0 ), f"Eval batch size ({FLAGS.config.viz_kwargs.eval_batch_size}) must be divisible by the number of devices ({len(devices)})" # create a 1D mesh with a single axis named "batch" mesh = Mesh(jax.devices(), axis_names="batch") # Our batches will be data-parallel sharded -- each device will get a slice of the batch dp_sharding = NamedSharding(mesh, PartitionSpec("batch")) # Our model will be replicated across devices (we are only doing data parallelism, not model parallelism) replicated_sharding = NamedSharding(mesh, PartitionSpec()) # prevent tensorflow from using GPU memory since it's only used for data loading tf.config.set_visible_devices([], "GPU") ######### # # Setup WandB # ######### name = format_name_with_config( FLAGS.name, FLAGS.config.to_dict(), ) wandb_id = "{name}_{time}".format( name=name, time=datetime.datetime.now().strftime("%Y%m%d_%H%M%S"), ) wandb.init( config=FLAGS.config.to_dict(), id=wandb_id, name=name, mode="disabled" if FLAGS.debug else None, **FLAGS.config.wandb, ) ######### # # Load Pretrained model + optionally modify config # ######### pretrained_model = OctoModel.load_pretrained( FLAGS.config.pretrained_path, step=FLAGS.config.pretrained_step, ) flat_config = flax.traverse_util.flatten_dict( pretrained_model.config, keep_empty_nodes=True ) for d_key in flax.traverse_util.flatten_dict( FLAGS.config.get("config_delete_keys", ConfigDict()).to_dict() ): for c_key in list(flat_config.keys()): if ".".join(c_key).startswith(".".join(d_key)): del flat_config[c_key] config = ConfigDict(flax.traverse_util.unflatten_dict(flat_config)) config.update(FLAGS.config.get("update_config", ConfigDict())) config = config.to_dict()
check_config_diff(config, pretrained_model.config)
8
2023-12-13 09:58:56+00:00
12k
modelscope/richdreamer
threestudio/systems/base.py
[ { "identifier": "Exporter", "path": "threestudio/models/exporters/base.py", "snippet": "class Exporter(BaseObject):\n @dataclass\n class Config(BaseObject.Config):\n save_video: bool = False\n\n cfg: Config\n\n def configure(\n self,\n geometry: BaseImplicitGeometry,\n ...
import os import pytorch_lightning as pl import torch.nn.functional as F import threestudio from dataclasses import dataclass, field from threestudio.models.exporters.base import Exporter, ExporterOutput from threestudio.systems.utils import parse_optimizer, parse_scheduler from threestudio.utils.base import (Updateable, update_end_if_possible, update_if_possible,) from threestudio.utils.config import parse_structured from threestudio.utils.misc import C, cleanup, get_device, load_module_weights from threestudio.utils.saving import SaverMixin from threestudio.utils.typing import * from threestudio.utils.config import load_config, parse_structured
10,184
def set_resume_status(self, current_epoch: int, global_step: int): # restore correct epoch and global step in eval self._resumed_eval = True self._resumed_eval_status["current_epoch"] = current_epoch self._resumed_eval_status["global_step"] = global_step @property def resumed(self): # whether from resumed checkpoint return self._resumed @property def true_global_step(self): if self._resumed_eval: return self._resumed_eval_status["global_step"] else: return self.global_step @property def true_current_epoch(self): if self._resumed_eval: return self._resumed_eval_status["current_epoch"] else: return self.current_epoch def configure(self) -> None: pass def post_configure(self) -> None: """ executed after weights are loaded """ pass def C(self, value: Any) -> float: return C(value, self.true_current_epoch, self.true_global_step) def configure_optimizers(self): optim = parse_optimizer(self.cfg.optimizer, self) ret = { "optimizer": optim, } if self.cfg.scheduler is not None: ret.update( { "lr_scheduler": parse_scheduler(self.cfg.scheduler, optim), } ) return ret def training_step(self, batch, batch_idx): raise NotImplementedError def validation_step(self, batch, batch_idx): raise NotImplementedError def on_train_batch_end(self, outputs, batch, batch_idx): self.dataset = self.trainer.train_dataloader.dataset update_end_if_possible( self.dataset, self.true_current_epoch, self.true_global_step ) self.do_update_step_end(self.true_current_epoch, self.true_global_step) def on_validation_batch_end(self, outputs, batch, batch_idx): self.dataset = self.trainer.val_dataloaders.dataset update_end_if_possible( self.dataset, self.true_current_epoch, self.true_global_step ) self.do_update_step_end(self.true_current_epoch, self.true_global_step) if self.cfg.cleanup_after_validation_step: # cleanup to save vram cleanup() def on_validation_epoch_end(self): raise NotImplementedError def test_step(self, batch, batch_idx): raise NotImplementedError def on_test_batch_end(self, outputs, batch, batch_idx): self.dataset = self.trainer.test_dataloaders.dataset update_end_if_possible( self.dataset, self.true_current_epoch, self.true_global_step ) self.do_update_step_end(self.true_current_epoch, self.true_global_step) if self.cfg.cleanup_after_test_step: # cleanup to save vram cleanup() def on_test_epoch_end(self): pass def predict_step(self, batch, batch_idx): raise NotImplementedError def on_predict_batch_end(self, outputs, batch, batch_idx): self.dataset = self.trainer.predict_dataloaders.dataset update_end_if_possible( self.dataset, self.true_current_epoch, self.true_global_step ) self.do_update_step_end(self.true_current_epoch, self.true_global_step) if self.cfg.cleanup_after_test_step: # cleanup to save vram cleanup() def on_predict_epoch_end(self): pass def preprocess_data(self, batch, stage): pass """ Implementing on_after_batch_transfer of DataModule does the same. But on_after_batch_transfer does not support DP. """ def on_train_batch_start(self, batch, batch_idx, unused=0): self.preprocess_data(batch, "train") self.dataset = self.trainer.train_dataloader.dataset
class BaseSystem(pl.LightningModule, Updateable, SaverMixin): @dataclass class Config: loggers: dict = field(default_factory=dict) loss: dict = field(default_factory=dict) optimizer: dict = field(default_factory=dict) scheduler: Optional[dict] = None weights: Optional[str] = None weights_ignore_modules: Optional[List[str]] = None cleanup_after_validation_step: bool = False cleanup_after_test_step: bool = False cfg: Config def __init__(self, cfg, resumed=False) -> None: super().__init__() self.cfg = parse_structured(self.Config, cfg) self._save_dir: Optional[str] = None self._resumed: bool = resumed self._resumed_eval: bool = False self._resumed_eval_status: dict = {"global_step": 0, "current_epoch": 0} if "loggers" in cfg: self.create_loggers(cfg.loggers) self.configure() if self.cfg.weights is not None: self.load_weights(self.cfg.weights, self.cfg.weights_ignore_modules) self.post_configure() def load_weights(self, weights: str, ignore_modules: Optional[List[str]] = None): state_dict, epoch, global_step = load_module_weights( weights, ignore_modules=ignore_modules, map_location="cpu" ) self.load_state_dict(state_dict, strict=False) # restore step-dependent states self.do_update_step(epoch, global_step, on_load_weights=True) def set_resume_status(self, current_epoch: int, global_step: int): # restore correct epoch and global step in eval self._resumed_eval = True self._resumed_eval_status["current_epoch"] = current_epoch self._resumed_eval_status["global_step"] = global_step @property def resumed(self): # whether from resumed checkpoint return self._resumed @property def true_global_step(self): if self._resumed_eval: return self._resumed_eval_status["global_step"] else: return self.global_step @property def true_current_epoch(self): if self._resumed_eval: return self._resumed_eval_status["current_epoch"] else: return self.current_epoch def configure(self) -> None: pass def post_configure(self) -> None: """ executed after weights are loaded """ pass def C(self, value: Any) -> float: return C(value, self.true_current_epoch, self.true_global_step) def configure_optimizers(self): optim = parse_optimizer(self.cfg.optimizer, self) ret = { "optimizer": optim, } if self.cfg.scheduler is not None: ret.update( { "lr_scheduler": parse_scheduler(self.cfg.scheduler, optim), } ) return ret def training_step(self, batch, batch_idx): raise NotImplementedError def validation_step(self, batch, batch_idx): raise NotImplementedError def on_train_batch_end(self, outputs, batch, batch_idx): self.dataset = self.trainer.train_dataloader.dataset update_end_if_possible( self.dataset, self.true_current_epoch, self.true_global_step ) self.do_update_step_end(self.true_current_epoch, self.true_global_step) def on_validation_batch_end(self, outputs, batch, batch_idx): self.dataset = self.trainer.val_dataloaders.dataset update_end_if_possible( self.dataset, self.true_current_epoch, self.true_global_step ) self.do_update_step_end(self.true_current_epoch, self.true_global_step) if self.cfg.cleanup_after_validation_step: # cleanup to save vram cleanup() def on_validation_epoch_end(self): raise NotImplementedError def test_step(self, batch, batch_idx): raise NotImplementedError def on_test_batch_end(self, outputs, batch, batch_idx): self.dataset = self.trainer.test_dataloaders.dataset update_end_if_possible( self.dataset, self.true_current_epoch, self.true_global_step ) self.do_update_step_end(self.true_current_epoch, self.true_global_step) if self.cfg.cleanup_after_test_step: # cleanup to save vram cleanup() def on_test_epoch_end(self): pass def predict_step(self, batch, batch_idx): raise NotImplementedError def on_predict_batch_end(self, outputs, batch, batch_idx): self.dataset = self.trainer.predict_dataloaders.dataset update_end_if_possible( self.dataset, self.true_current_epoch, self.true_global_step ) self.do_update_step_end(self.true_current_epoch, self.true_global_step) if self.cfg.cleanup_after_test_step: # cleanup to save vram cleanup() def on_predict_epoch_end(self): pass def preprocess_data(self, batch, stage): pass """ Implementing on_after_batch_transfer of DataModule does the same. But on_after_batch_transfer does not support DP. """ def on_train_batch_start(self, batch, batch_idx, unused=0): self.preprocess_data(batch, "train") self.dataset = self.trainer.train_dataloader.dataset
update_if_possible(self.dataset, self.true_current_epoch, self.true_global_step)
6
2023-12-06 07:53:11+00:00
12k
rehg-lab/RAVE
annotator/oneformer/detectron2/modeling/mmdet_wrapper.py
[ { "identifier": "ShapeSpec", "path": "annotator/oneformer/detectron2/layers/shape_spec.py", "snippet": "class ShapeSpec:\r\n \"\"\"\r\n A simple structure that contains basic shape specification about a tensor.\r\n It is often used as the auxiliary inputs/outputs of models,\r\n to complement...
import itertools import logging import numpy as np import torch from collections import OrderedDict from collections.abc import Mapping from typing import Dict, List, Optional, Tuple, Union from omegaconf import DictConfig, OmegaConf from torch import Tensor, nn from annotator.oneformer.detectron2.layers import ShapeSpec from annotator.oneformer.detectron2.structures import BitMasks, Boxes, ImageList, Instances from annotator.oneformer.detectron2.utils.events import get_event_storage from .backbone import Backbone from mmcv.utils import ConfigDict from mmdet.models import build_backbone from mmdet.models import build_neck from mmdet.models import build_detector from mmdet.core import PolygonMasks as mm_PolygonMasks, BitmapMasks as mm_BitMasks
9,484
raise ValueError( "Length of output_shapes does not match outputs from the mmdet backbone: " f"{len(outs)} != {len(self._output_shapes)}" ) return {k: v for k, v in zip(self._output_names, outs)} def output_shape(self) -> Dict[str, ShapeSpec]: return {k: v for k, v in zip(self._output_names, self._output_shapes)} class MMDetDetector(nn.Module): """ Wrapper of a mmdetection detector model, for detection and instance segmentation. Input/output formats of this class follow detectron2's convention, so a mmdetection model can be trained and evaluated in detectron2. """ def __init__( self, detector: Union[nn.Module, Mapping], *, # Default is 32 regardless of model: # https://github.com/open-mmlab/mmdetection/tree/master/configs/_base_/datasets size_divisibility=32, pixel_mean: Tuple[float], pixel_std: Tuple[float], ): """ Args: detector: a mmdet detector, or a mmdet config dict that defines a detector. size_divisibility: pad input images to multiple of this number pixel_mean: per-channel mean to normalize input image pixel_std: per-channel stddev to normalize input image """ super().__init__() if isinstance(detector, Mapping): detector = build_detector(_to_container(detector)) self.detector = detector self.detector.init_weights() self.size_divisibility = size_divisibility self.register_buffer("pixel_mean", torch.tensor(pixel_mean).view(-1, 1, 1), False) self.register_buffer("pixel_std", torch.tensor(pixel_std).view(-1, 1, 1), False) assert ( self.pixel_mean.shape == self.pixel_std.shape ), f"{self.pixel_mean} and {self.pixel_std} have different shapes!" def forward(self, batched_inputs: List[Dict[str, torch.Tensor]]): images = [x["image"].to(self.device) for x in batched_inputs] images = [(x - self.pixel_mean) / self.pixel_std for x in images] images = ImageList.from_tensors(images, size_divisibility=self.size_divisibility).tensor metas = [] rescale = {"height" in x for x in batched_inputs} if len(rescale) != 1: raise ValueError("Some inputs have original height/width, but some don't!") rescale = list(rescale)[0] output_shapes = [] for input in batched_inputs: meta = {} c, h, w = input["image"].shape meta["img_shape"] = meta["ori_shape"] = (h, w, c) if rescale: scale_factor = np.array( [w / input["width"], h / input["height"]] * 2, dtype="float32" ) ori_shape = (input["height"], input["width"]) output_shapes.append(ori_shape) meta["ori_shape"] = ori_shape + (c,) else: scale_factor = 1.0 output_shapes.append((h, w)) meta["scale_factor"] = scale_factor meta["flip"] = False padh, padw = images.shape[-2:] meta["pad_shape"] = (padh, padw, c) metas.append(meta) if self.training: gt_instances = [x["instances"].to(self.device) for x in batched_inputs] if gt_instances[0].has("gt_masks"): def convert_mask(m, shape): # mmdet mask format if isinstance(m, BitMasks): return mm_BitMasks(m.tensor.cpu().numpy(), shape[0], shape[1]) else: return mm_PolygonMasks(m.polygons, shape[0], shape[1]) gt_masks = [convert_mask(x.gt_masks, x.image_size) for x in gt_instances] losses_and_metrics = self.detector.forward_train( images, metas, [x.gt_boxes.tensor for x in gt_instances], [x.gt_classes for x in gt_instances], gt_masks=gt_masks, ) else: losses_and_metrics = self.detector.forward_train( images, metas, [x.gt_boxes.tensor for x in gt_instances], [x.gt_classes for x in gt_instances], ) return _parse_losses(losses_and_metrics) else: results = self.detector.simple_test(images, metas, rescale=rescale) results = [ {"instances": _convert_mmdet_result(r, shape)} for r, shape in zip(results, output_shapes) ] return results @property def device(self): return self.pixel_mean.device # Reference: show_result() in # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/detectors/base.py
# Copyright (c) Facebook, Inc. and its affiliates. logger = logging.getLogger(__name__) def _to_container(cfg): """ mmdet will assert the type of dict/list. So convert omegaconf objects to dict/list. """ if isinstance(cfg, DictConfig): cfg = OmegaConf.to_container(cfg, resolve=True) return ConfigDict(cfg) class MMDetBackbone(Backbone): """ Wrapper of mmdetection backbones to use in detectron2. mmdet backbones produce list/tuple of tensors, while detectron2 backbones produce a dict of tensors. This class wraps the given backbone to produce output in detectron2's convention, so it can be used in place of detectron2 backbones. """ def __init__( self, backbone: Union[nn.Module, Mapping], neck: Union[nn.Module, Mapping, None] = None, *, output_shapes: List[ShapeSpec], output_names: Optional[List[str]] = None, ): """ Args: backbone: either a backbone module or a mmdet config dict that defines a backbone. The backbone takes a 4D image tensor and returns a sequence of tensors. neck: either a backbone module or a mmdet config dict that defines a neck. The neck takes outputs of backbone and returns a sequence of tensors. If None, no neck is used. output_shapes: shape for every output of the backbone (or neck, if given). stride and channels are often needed. output_names: names for every output of the backbone (or neck, if given). By default, will use "out0", "out1", ... """ super().__init__() if isinstance(backbone, Mapping): backbone = build_backbone(_to_container(backbone)) self.backbone = backbone if isinstance(neck, Mapping): neck = build_neck(_to_container(neck)) self.neck = neck # "Neck" weights, if any, are part of neck itself. This is the interface # of mmdet so we follow it. Reference: # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/detectors/two_stage.py logger.info("Initializing mmdet backbone weights...") self.backbone.init_weights() # train() in mmdet modules is non-trivial, and has to be explicitly # called. Reference: # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/backbones/resnet.py self.backbone.train() if self.neck is not None: logger.info("Initializing mmdet neck weights ...") if isinstance(self.neck, nn.Sequential): for m in self.neck: m.init_weights() else: self.neck.init_weights() self.neck.train() self._output_shapes = output_shapes if not output_names: output_names = [f"out{i}" for i in range(len(output_shapes))] self._output_names = output_names def forward(self, x) -> Dict[str, Tensor]: outs = self.backbone(x) if self.neck is not None: outs = self.neck(outs) assert isinstance( outs, (list, tuple) ), "mmdet backbone should return a list/tuple of tensors!" if len(outs) != len(self._output_shapes): raise ValueError( "Length of output_shapes does not match outputs from the mmdet backbone: " f"{len(outs)} != {len(self._output_shapes)}" ) return {k: v for k, v in zip(self._output_names, outs)} def output_shape(self) -> Dict[str, ShapeSpec]: return {k: v for k, v in zip(self._output_names, self._output_shapes)} class MMDetDetector(nn.Module): """ Wrapper of a mmdetection detector model, for detection and instance segmentation. Input/output formats of this class follow detectron2's convention, so a mmdetection model can be trained and evaluated in detectron2. """ def __init__( self, detector: Union[nn.Module, Mapping], *, # Default is 32 regardless of model: # https://github.com/open-mmlab/mmdetection/tree/master/configs/_base_/datasets size_divisibility=32, pixel_mean: Tuple[float], pixel_std: Tuple[float], ): """ Args: detector: a mmdet detector, or a mmdet config dict that defines a detector. size_divisibility: pad input images to multiple of this number pixel_mean: per-channel mean to normalize input image pixel_std: per-channel stddev to normalize input image """ super().__init__() if isinstance(detector, Mapping): detector = build_detector(_to_container(detector)) self.detector = detector self.detector.init_weights() self.size_divisibility = size_divisibility self.register_buffer("pixel_mean", torch.tensor(pixel_mean).view(-1, 1, 1), False) self.register_buffer("pixel_std", torch.tensor(pixel_std).view(-1, 1, 1), False) assert ( self.pixel_mean.shape == self.pixel_std.shape ), f"{self.pixel_mean} and {self.pixel_std} have different shapes!" def forward(self, batched_inputs: List[Dict[str, torch.Tensor]]): images = [x["image"].to(self.device) for x in batched_inputs] images = [(x - self.pixel_mean) / self.pixel_std for x in images] images = ImageList.from_tensors(images, size_divisibility=self.size_divisibility).tensor metas = [] rescale = {"height" in x for x in batched_inputs} if len(rescale) != 1: raise ValueError("Some inputs have original height/width, but some don't!") rescale = list(rescale)[0] output_shapes = [] for input in batched_inputs: meta = {} c, h, w = input["image"].shape meta["img_shape"] = meta["ori_shape"] = (h, w, c) if rescale: scale_factor = np.array( [w / input["width"], h / input["height"]] * 2, dtype="float32" ) ori_shape = (input["height"], input["width"]) output_shapes.append(ori_shape) meta["ori_shape"] = ori_shape + (c,) else: scale_factor = 1.0 output_shapes.append((h, w)) meta["scale_factor"] = scale_factor meta["flip"] = False padh, padw = images.shape[-2:] meta["pad_shape"] = (padh, padw, c) metas.append(meta) if self.training: gt_instances = [x["instances"].to(self.device) for x in batched_inputs] if gt_instances[0].has("gt_masks"): def convert_mask(m, shape): # mmdet mask format if isinstance(m, BitMasks): return mm_BitMasks(m.tensor.cpu().numpy(), shape[0], shape[1]) else: return mm_PolygonMasks(m.polygons, shape[0], shape[1]) gt_masks = [convert_mask(x.gt_masks, x.image_size) for x in gt_instances] losses_and_metrics = self.detector.forward_train( images, metas, [x.gt_boxes.tensor for x in gt_instances], [x.gt_classes for x in gt_instances], gt_masks=gt_masks, ) else: losses_and_metrics = self.detector.forward_train( images, metas, [x.gt_boxes.tensor for x in gt_instances], [x.gt_classes for x in gt_instances], ) return _parse_losses(losses_and_metrics) else: results = self.detector.simple_test(images, metas, rescale=rescale) results = [ {"instances": _convert_mmdet_result(r, shape)} for r, shape in zip(results, output_shapes) ] return results @property def device(self): return self.pixel_mean.device # Reference: show_result() in # https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/detectors/base.py
def _convert_mmdet_result(result, shape: Tuple[int, int]) -> Instances:
3
2023-12-05 02:51:53+00:00
12k
DiffusionLight/DiffusionLight
inpaint.py
[ { "identifier": "BallInpainter", "path": "relighting/inpainter.py", "snippet": "class BallInpainter():\n def __init__(self, pipeline, sd_arch, control_generator, disable_water_mask=True):\n self.pipeline = pipeline\n self.sd_arch = sd_arch\n self.control_generator = control_gener...
import torch import argparse import numpy as np import torch.distributed as dist import os import json import relighting.dist_utils as dist_util import time from PIL import Image from tqdm.auto import tqdm from relighting.inpainter import BallInpainter from relighting.mask_utils import MaskGenerator from relighting.ball_processor import ( get_ideal_normal_ball, crop_ball ) from relighting.dataset import GeneralLoader from relighting.utils import name2hash from relighting.argument import ( SD_MODELS, CONTROLNET_MODELS, VAE_MODELS )
8,224
torch_dtype = torch_dtype, offload = args.offload ) elif args.model_option in ["sdxl", "sdxl_fast"] and not args.use_controlnet: model = SD_MODELS[args.model_option] pipe = BallInpainter.from_sdxl( model=model, controlnet=None, device=device, torch_dtype = torch_dtype, offload = args.offload ) elif args.use_controlnet: model, controlnet = SD_MODELS[args.model_option], CONTROLNET_MODELS[args.model_option] pipe = BallInpainter.from_sd( model=model, controlnet=controlnet, device=device, torch_dtype = torch_dtype, offload = args.offload ) else: model = SD_MODELS[args.model_option] pipe = BallInpainter.from_sd( model=model, controlnet=None, device=device, torch_dtype = torch_dtype, offload = args.offload ) if args.lora_scale > 0 and args.lora_path is None: raise ValueError("lora scale is not 0 but lora path is not set") if (args.lora_path is not None) and (args.use_lora): print(f"using lora path {args.lora_path}") print(f"using lora scale {args.lora_scale}") pipe.pipeline.load_lora_weights(args.lora_path) pipe.pipeline.fuse_lora(lora_scale=args.lora_scale) # fuse lora weight w' = w + \alpha \Delta w enabled_lora = True else: enabled_lora = False if args.use_torch_compile: try: print("compiling unet model") start_time = time.time() pipe.pipeline.unet = torch.compile(pipe.pipeline.unet, mode="reduce-overhead", fullgraph=True) print("Model compilation time: ", time.time() - start_time) except: pass # default height for sdxl is 1024, if not set, we set default height. if args.model_option == "sdxl" and args.img_height == 0 and args.img_width == 0: args.img_height = 1024 args.img_width = 1024 # load dataset dataset = GeneralLoader( root=args.dataset, resolution=(args.img_width, args.img_height), force_square=args.force_square, return_dict=True, random_shuffle=args.random_loader, process_id=args.idx, process_total=args.total, limit_input=args.limit_input, ) # interpolate embedding embedding_dict = interpolate_embedding(pipe, args) # prepare mask and normal ball mask_generator = MaskGenerator() normal_ball, mask_ball = get_ideal_normal_ball(size=args.ball_size+args.ball_dilate) _, mask_ball_for_crop = get_ideal_normal_ball(size=args.ball_size) # make output directory if not exist raw_output_dir = os.path.join(args.output_dir, "raw") control_output_dir = os.path.join(args.output_dir, "control") square_output_dir = os.path.join(args.output_dir, "square") os.makedirs(args.output_dir, exist_ok=True) os.makedirs(raw_output_dir, exist_ok=True) os.makedirs(control_output_dir, exist_ok=True) os.makedirs(square_output_dir, exist_ok=True) # create split seed # please DO NOT manual replace this line, use --seed option instead seeds = args.seed.split(",") for image_data in tqdm(dataset): input_image = image_data["image"] image_path = image_data["path"] for ev, (prompt_embeds, pooled_prompt_embeds) in embedding_dict.items(): # create output file name (we always use png to prevent quality loss) ev_str = str(ev).replace(".", "") if ev != 0 else "-00" outname = os.path.basename(image_path).split(".")[0] + f"_ev{ev_str}" # we use top-left corner notation (which is different from aj.aek's center point notation) x, y, r = get_ball_location(image_data, args) # create inpaint mask mask = mask_generator.generate_single( input_image, mask_ball, x - (args.ball_dilate // 2), y - (args.ball_dilate // 2), r + args.ball_dilate ) seeds = tqdm(seeds, desc="seeds") if len(seeds) > 10 else seeds #replacely create image with differnt seed for seed in seeds: start_time = time.time() # set seed, if seed auto we use file name as seed if seed == "auto": filename = os.path.basename(image_path).split(".")[0]
# inpaint the ball on an image # this one is design for general image that does not require special location to place # cross import from inpaint_multi-illum.py def create_argparser(): parser = argparse.ArgumentParser() parser.add_argument("--dataset", type=str, required=True ,help='directory that contain the image') #dataset name or directory parser.add_argument("--ball_size", type=int, default=256, help="size of the ball in pixel") parser.add_argument("--ball_dilate", type=int, default=20, help="How much pixel to dilate the ball to make a sharper edge") parser.add_argument("--prompt", type=str, default="a perfect mirrored reflective chrome ball sphere") parser.add_argument("--prompt_dark", type=str, default="a perfect black dark mirrored reflective chrome ball sphere") parser.add_argument("--negative_prompt", type=str, default="matte, diffuse, flat, dull") parser.add_argument("--model_option", default="sdxl", help='selecting fancy model option (sd15_old, sd15_new, sd21, sdxl)') # [sd15_old, sd15_new, or sd21] parser.add_argument("--output_dir", required=True, type=str, help="output directory") parser.add_argument("--img_height", type=int, default=1024, help="Dataset Image Height") parser.add_argument("--img_width", type=int, default=1024, help="Dataset Image Width") # some good seed 0, 37, 71, 125, 140, 196, 307, 434, 485, 575 | 9021, 9166, 9560, 9814, but default auto is for fairness parser.add_argument("--seed", default="auto", type=str, help="Seed: right now we use single seed instead to reduce the time, (Auto will use hash file name to generate seed)") parser.add_argument("--denoising_step", default=30, type=int, help="number of denoising step of diffusion model") parser.add_argument("--control_scale", default=0.5, type=float, help="controlnet conditioning scale") parser.add_argument('--no_controlnet', dest='use_controlnet', action='store_false', help='by default we using controlnet, we have option to disable to see the different') parser.set_defaults(use_controlnet=True) parser.add_argument('--no_force_square', dest='force_square', action='store_false', help='SDXL is trained for square image, we prefered the square input. but you use this option to disable reshape') parser.set_defaults(force_square=True) parser.add_argument('--no_random_loader', dest='random_loader', action='store_false', help="by default, we random how dataset load. This make us able to peak into the trend of result without waiting entire dataset. but can disable if prefereed") parser.set_defaults(random_loader=True) parser.add_argument('--cpu', dest='is_cpu', action='store_true', help="using CPU inference instead of GPU inference") parser.set_defaults(is_cpu=False) parser.add_argument('--offload', dest='offload', action='store_false', help="to enable diffusers cpu offload") parser.set_defaults(offload=False) parser.add_argument("--limit_input", default=0, type=int, help="limit number of image to process to n image (0 = no limit), useful for run smallset") # LoRA stuff parser.add_argument('--no_lora', dest='use_lora', action='store_false', help='by default we using lora, we have option to disable to see the different') parser.set_defaults(use_lora=True) parser.add_argument("--lora_path", default="models/ThisIsTheFinal-lora-hdr-continuous-largeT@900/0_-5/checkpoint-2500", type=str, help="LoRA Checkpoint path") parser.add_argument("--lora_scale", default=0.75, type=float, help="LoRA scale factor") # speed optimization stuff parser.add_argument('--no_torch_compile', dest='use_torch_compile', action='store_false', help='by default we using torch compile for faster processing speed. disable it if your environemnt is lower than pytorch2.0') parser.set_defaults(use_torch_compile=True) # algorithm + iterative stuff parser.add_argument("--algorithm", type=str, default="iterative", choices=["iterative", "normal"], help="Selecting between iterative or normal (single pass inpaint) algorithm") parser.add_argument("--agg_mode", default="median", type=str) parser.add_argument("--strength", default=0.8, type=float) parser.add_argument("--num_iteration", default=2, type=int) parser.add_argument("--ball_per_iteration", default=30, type=int) parser.add_argument('--no_save_intermediate', dest='save_intermediate', action='store_false') parser.set_defaults(save_intermediate=True) parser.add_argument("--cache_dir", default="./temp_inpaint_iterative", type=str, help="cache directory for iterative inpaint") # pararelle processing parser.add_argument("--idx", default=0, type=int, help="index of the current process, useful for running on multiple node") parser.add_argument("--total", default=1, type=int, help="total number of process") # for HDR stuff parser.add_argument("--max_negative_ev", default=-5, type=int, help="maximum negative EV for lora") parser.add_argument("--ev", default="0,-2.5,-5", type=str, help="EV: list of EV to generate") return parser def get_ball_location(image_data, args): if 'boundary' in image_data: # support predefined boundary if need x = image_data["boundary"]["x"] y = image_data["boundary"]["y"] r = image_data["boundary"]["size"] # support ball dilation half_dilate = args.ball_dilate // 2 # check if not left out-of-bound if x - half_dilate < 0: x += half_dilate if y - half_dilate < 0: y += half_dilate # check if not right out-of-bound if x + r + half_dilate > args.img_width: x -= half_dilate if y + r + half_dilate > args.img_height: y -= half_dilate else: # we use top-left corner notation x, y, r = ((args.img_width // 2) - (args.ball_size // 2), (args.img_height // 2) - (args.ball_size // 2), args.ball_size) return x, y, r def interpolate_embedding(pipe, args): print("interpolate embedding...") # get list of all EVs ev_list = [float(x) for x in args.ev.split(",")] interpolants = [ev / args.max_negative_ev for ev in ev_list] print("EV : ", ev_list) print("EV : ", interpolants) # calculate prompt embeddings prompt_normal = args.prompt prompt_dark = args.prompt_dark prompt_embeds_normal, _, pooled_prompt_embeds_normal, _ = pipe.pipeline.encode_prompt(prompt_normal) prompt_embeds_dark, _, pooled_prompt_embeds_dark, _ = pipe.pipeline.encode_prompt(prompt_dark) # interpolate embeddings interpolate_embeds = [] for t in interpolants: int_prompt_embeds = prompt_embeds_normal + t * (prompt_embeds_dark - prompt_embeds_normal) int_pooled_prompt_embeds = pooled_prompt_embeds_normal + t * (pooled_prompt_embeds_dark - pooled_prompt_embeds_normal) interpolate_embeds.append((int_prompt_embeds, int_pooled_prompt_embeds)) return dict(zip(ev_list, interpolate_embeds)) def main(): # load arguments args = create_argparser().parse_args() # get local rank if args.is_cpu: device = torch.device("cpu") torch_dtype = torch.float32 else: device = dist_util.dev() torch_dtype = torch.float16 # so, we need ball_dilate >= 16 (2*vae_scale_factor) to make our mask shape = (272, 272) assert args.ball_dilate % 2 == 0 # ball dilation should be symmetric # create controlnet pipeline if args.model_option in ["sdxl", "sdxl_fast"] and args.use_controlnet: model, controlnet = SD_MODELS[args.model_option], CONTROLNET_MODELS[args.model_option] pipe = BallInpainter.from_sdxl( model=model, controlnet=controlnet, device=device, torch_dtype = torch_dtype, offload = args.offload ) elif args.model_option in ["sdxl", "sdxl_fast"] and not args.use_controlnet: model = SD_MODELS[args.model_option] pipe = BallInpainter.from_sdxl( model=model, controlnet=None, device=device, torch_dtype = torch_dtype, offload = args.offload ) elif args.use_controlnet: model, controlnet = SD_MODELS[args.model_option], CONTROLNET_MODELS[args.model_option] pipe = BallInpainter.from_sd( model=model, controlnet=controlnet, device=device, torch_dtype = torch_dtype, offload = args.offload ) else: model = SD_MODELS[args.model_option] pipe = BallInpainter.from_sd( model=model, controlnet=None, device=device, torch_dtype = torch_dtype, offload = args.offload ) if args.lora_scale > 0 and args.lora_path is None: raise ValueError("lora scale is not 0 but lora path is not set") if (args.lora_path is not None) and (args.use_lora): print(f"using lora path {args.lora_path}") print(f"using lora scale {args.lora_scale}") pipe.pipeline.load_lora_weights(args.lora_path) pipe.pipeline.fuse_lora(lora_scale=args.lora_scale) # fuse lora weight w' = w + \alpha \Delta w enabled_lora = True else: enabled_lora = False if args.use_torch_compile: try: print("compiling unet model") start_time = time.time() pipe.pipeline.unet = torch.compile(pipe.pipeline.unet, mode="reduce-overhead", fullgraph=True) print("Model compilation time: ", time.time() - start_time) except: pass # default height for sdxl is 1024, if not set, we set default height. if args.model_option == "sdxl" and args.img_height == 0 and args.img_width == 0: args.img_height = 1024 args.img_width = 1024 # load dataset dataset = GeneralLoader( root=args.dataset, resolution=(args.img_width, args.img_height), force_square=args.force_square, return_dict=True, random_shuffle=args.random_loader, process_id=args.idx, process_total=args.total, limit_input=args.limit_input, ) # interpolate embedding embedding_dict = interpolate_embedding(pipe, args) # prepare mask and normal ball mask_generator = MaskGenerator() normal_ball, mask_ball = get_ideal_normal_ball(size=args.ball_size+args.ball_dilate) _, mask_ball_for_crop = get_ideal_normal_ball(size=args.ball_size) # make output directory if not exist raw_output_dir = os.path.join(args.output_dir, "raw") control_output_dir = os.path.join(args.output_dir, "control") square_output_dir = os.path.join(args.output_dir, "square") os.makedirs(args.output_dir, exist_ok=True) os.makedirs(raw_output_dir, exist_ok=True) os.makedirs(control_output_dir, exist_ok=True) os.makedirs(square_output_dir, exist_ok=True) # create split seed # please DO NOT manual replace this line, use --seed option instead seeds = args.seed.split(",") for image_data in tqdm(dataset): input_image = image_data["image"] image_path = image_data["path"] for ev, (prompt_embeds, pooled_prompt_embeds) in embedding_dict.items(): # create output file name (we always use png to prevent quality loss) ev_str = str(ev).replace(".", "") if ev != 0 else "-00" outname = os.path.basename(image_path).split(".")[0] + f"_ev{ev_str}" # we use top-left corner notation (which is different from aj.aek's center point notation) x, y, r = get_ball_location(image_data, args) # create inpaint mask mask = mask_generator.generate_single( input_image, mask_ball, x - (args.ball_dilate // 2), y - (args.ball_dilate // 2), r + args.ball_dilate ) seeds = tqdm(seeds, desc="seeds") if len(seeds) > 10 else seeds #replacely create image with differnt seed for seed in seeds: start_time = time.time() # set seed, if seed auto we use file name as seed if seed == "auto": filename = os.path.basename(image_path).split(".")[0]
seed = name2hash(filename)
5
2023-12-07 14:03:31+00:00
12k
eliphatfs/zerorf
zerorf.py
[ { "identifier": "MultiSceneNeRF", "path": "lib/models/autoencoders/multiscene_nerf.py", "snippet": "class MultiSceneNeRF(BaseNeRF):\n\n def __init__(self,\n *args,\n cache_size=0, # cache in RAM, top priority\n cache_16bit=False,\n num_...
import sys import shutil import os import cv2 import tqdm import json import numpy import wandb import torch import torch_redstone as rst import einops from sklearn.cluster import KMeans from lib.models.autoencoders import MultiSceneNeRF from mmgen.models import build_model, build_module from lib.core.optimizer import build_optimizers from lib.core.ssdnerf_gui import OrbitCamera from lib.datasets.nerf_synthetic import NerfSynthetic from lib.datasets.oppo import OppoDataset from PIL import Image from opt import config_parser from pprint import pprint
7,955
) entry = test[0] test_entry = dict( test_imgs=torch.tensor(entry['cond_imgs'][:][None]).float().to(device), test_poses=torch.tensor(entry['cond_poses'][:])[None].float().to(device), test_intrinsics=torch.tensor(entry['cond_intrinsics'][:])[None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) else: data_entry = dict( cond_imgs=images, cond_poses=torch.tensor(poses)[None].float().to(device) * 0.9, cond_intrinsics=torch.tensor(intrinsics)[None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) selected_idxs = list(range(args.n_views)) pic_h = data_entry['cond_imgs'].shape[-3] pic_w = data_entry['cond_imgs'].shape[-2] if args.load_image: args.model_res = 4 pic_h = pic_w = 320 cam = OrbitCamera('render', pic_w, pic_h, 3.2, 48) decoder_1 = dict( type='TensorialDecoder', preprocessor=dict( type='TensorialGenerator', in_ch=args.model_ch, out_ch=16, noise_res=args.model_res, tensor_config=( ['xy', 'z', 'yz', 'x', 'zx', 'y'] ) ), subreduce=1 if args.load_image else 2, reduce='cat', separate_density_and_color=False, sh_coef_only=False, sdf_mode=False, max_steps=1024 if not args.load_image else 320, n_images=args.n_views, image_h=pic_h, image_w=pic_w, has_time_dynamics=False, visualize_mesh=True ) decoder_2 = dict( type='FreqFactorizedDecoder', preprocessor=dict( type='TensorialGenerator', in_ch=args.model_ch, out_ch=16, noise_res=args.model_res, tensor_config=['xyz', 'xyz'] ), subreduce=1, reduce='cat', separate_density_and_color=False, sh_coef_only=False, sdf_mode=False, max_steps=1024 if not args.load_image else 640, n_images=args.n_views, image_h=pic_h, image_w=pic_w, has_time_dynamics=False, freq_bands=[None, 0.4], visualize_mesh=True ) patch_reg_loss = build_module(dict( type='MaskedTVLoss', power=1.5, loss_weight=0.00 )) nerf: MultiSceneNeRF = build_model(dict( type='MultiSceneNeRF', code_size=code_size, code_activation=dict(type='IdentityCode'), grid_size=64, patch_size=32, decoder=decoder_2 if args.rep == 'dif' else decoder_1, decoder_use_ema=False, bg_color=1.0, pixel_loss=dict( type='MSELoss', loss_weight=3.2 ), use_lpips_metric=torch.cuda.mem_get_info()[1] // 1000 ** 3 >= 32, cache_size=1, cache_16bit=False, init_from_mean=True ), train_cfg = dict( dt_gamma_scale=0.5, density_thresh=0.05, extra_scene_step=0, n_inverse_rays=args.n_rays_init, n_decoder_rays=args.n_rays_init, loss_coef=0.1 / (pic_h * pic_w), optimizer=dict(type='Adam', lr=0, weight_decay=0.), lr_scheduler=dict(type='ExponentialLR', gamma=0.99), cache_load_from=None, viz_dir=None, loss_denom=1.0, decoder_grad_clip=1.0 ), test_cfg = dict( img_size=(pic_h, pic_w), density_thresh=0.01, max_render_rays=pic_h * pic_w, dt_gamma_scale=0.5, n_inverse_rays=args.n_rays_init, loss_coef=0.1 / (pic_h * pic_w), n_inverse_steps=400, optimizer=dict(type='Adam', lr=0.0, weight_decay=0.), lr_scheduler=dict(type='ExponentialLR', gamma=0.998), return_depth=False )) nerf.bg_color = nerf.decoder.bg_color = torch.nn.Parameter(torch.ones(3) * args.bg_color, requires_grad=args.learn_bg) nerf.to(device) nerf.train()
sys.path.append('.') torch.backends.cuda.matmul.allow_tf32 = True def kmeans_downsample(points, n_points_to_sample): kmeans = KMeans(n_points_to_sample).fit(points) return ((points - kmeans.cluster_centers_[..., None, :]) ** 2).sum(-1).argmin(-1).tolist() args = config_parser() pprint(args) model_scaling_factor = 16 device = args.device BLENDER_TO_OPENCV_MATRIX = numpy.array([ [1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1] ], dtype=numpy.float32) code_size = (3, args.model_ch, args.model_res, args.model_res) rst.seed(args.seed) poses = [] intrinsics = [] if args.load_image: image = numpy.array(Image.open(args.load_image)).astype(numpy.float32) / 255.0 image = torch.tensor(image).cuda() images = einops.rearrange(image, '(ph h) (pw w) c -> (ph pw) h w c', ph=3, pw=2)[None] meta = json.load(open(os.path.join(os.path.dirname(__file__), "meta.json"))) poses = numpy.array([ (numpy.array(frame['transform_matrix']) @ BLENDER_TO_OPENCV_MATRIX) * 2 for frame in meta['sample_0']['view_frames'] ]) _, b, h, w, c = images.shape x, y = w / 2, h / 2 focal_length = y / numpy.tan(meta['fovy'] / 2) intrinsics = numpy.array([[focal_length, focal_length, x, y]] * args.n_views) work_dir = "results/%s" % args.proj_name os.makedirs(work_dir, exist_ok=True) os.chdir(work_dir) if not args.load_image: if args.dataset == "nerf_syn": model_scale = dict(chair=2.1, drums=2.3, ficus=2.3, hotdog=3.0, lego=2.4, materials=2.4, mic=2.5, ship=2.75) world_scale = 2 / model_scale[args.obj] dataset = NerfSynthetic([f"{args.data_dir}/{args.obj}/transforms_train.json"], rgba=True, world_scale=world_scale) val = NerfSynthetic([f"{args.data_dir}/{args.obj}/transforms_val.json"], world_scale=world_scale) test = NerfSynthetic([f"{args.data_dir}/{args.obj}/transforms_test.json"], world_scale=world_scale) entry = dataset[0] selected_idxs = kmeans_downsample(entry['cond_poses'][..., :3, 3], args.n_views) elif args.dataset == "oi": world_scale = 5.0 dataset = OppoDataset(f"{args.data_dir}/{args.obj}/output", split='train', world_scale=world_scale, rgba=True) val = OppoDataset(f"{args.data_dir}/{args.obj}/output", split='test', world_scale=world_scale) test = OppoDataset(f"{args.data_dir}/{args.obj}/output", split='test', world_scale=world_scale) entry = dataset[0] if args.n_views == 6: selected_idxs = [10, 3, 19, 22, 17, 35] elif args.n_views == 4: selected_idxs = [10, 33, 35, 6] else: selected_idxs = kmeans_downsample(entry['cond_poses'][..., :3, 3], args.n_views) data_entry = dict( cond_imgs=torch.tensor(entry['cond_imgs'][selected_idxs][None]).float().to(device), cond_poses=torch.tensor(entry['cond_poses'])[selected_idxs][None].float().to(device), cond_intrinsics=torch.tensor(entry['cond_intrinsics'])[selected_idxs][None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) entry = val[0] val_entry = dict( test_imgs=torch.tensor(entry['cond_imgs'][:args.n_val][None]).float().to(device), test_poses=torch.tensor(entry['cond_poses'][:args.n_val])[None].float().to(device), test_intrinsics=torch.tensor(entry['cond_intrinsics'][:args.n_val])[None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) entry = test[0] test_entry = dict( test_imgs=torch.tensor(entry['cond_imgs'][:][None]).float().to(device), test_poses=torch.tensor(entry['cond_poses'][:])[None].float().to(device), test_intrinsics=torch.tensor(entry['cond_intrinsics'][:])[None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) else: data_entry = dict( cond_imgs=images, cond_poses=torch.tensor(poses)[None].float().to(device) * 0.9, cond_intrinsics=torch.tensor(intrinsics)[None].float().to(device), scene_id=[0], scene_name=[args.proj_name] ) selected_idxs = list(range(args.n_views)) pic_h = data_entry['cond_imgs'].shape[-3] pic_w = data_entry['cond_imgs'].shape[-2] if args.load_image: args.model_res = 4 pic_h = pic_w = 320 cam = OrbitCamera('render', pic_w, pic_h, 3.2, 48) decoder_1 = dict( type='TensorialDecoder', preprocessor=dict( type='TensorialGenerator', in_ch=args.model_ch, out_ch=16, noise_res=args.model_res, tensor_config=( ['xy', 'z', 'yz', 'x', 'zx', 'y'] ) ), subreduce=1 if args.load_image else 2, reduce='cat', separate_density_and_color=False, sh_coef_only=False, sdf_mode=False, max_steps=1024 if not args.load_image else 320, n_images=args.n_views, image_h=pic_h, image_w=pic_w, has_time_dynamics=False, visualize_mesh=True ) decoder_2 = dict( type='FreqFactorizedDecoder', preprocessor=dict( type='TensorialGenerator', in_ch=args.model_ch, out_ch=16, noise_res=args.model_res, tensor_config=['xyz', 'xyz'] ), subreduce=1, reduce='cat', separate_density_and_color=False, sh_coef_only=False, sdf_mode=False, max_steps=1024 if not args.load_image else 640, n_images=args.n_views, image_h=pic_h, image_w=pic_w, has_time_dynamics=False, freq_bands=[None, 0.4], visualize_mesh=True ) patch_reg_loss = build_module(dict( type='MaskedTVLoss', power=1.5, loss_weight=0.00 )) nerf: MultiSceneNeRF = build_model(dict( type='MultiSceneNeRF', code_size=code_size, code_activation=dict(type='IdentityCode'), grid_size=64, patch_size=32, decoder=decoder_2 if args.rep == 'dif' else decoder_1, decoder_use_ema=False, bg_color=1.0, pixel_loss=dict( type='MSELoss', loss_weight=3.2 ), use_lpips_metric=torch.cuda.mem_get_info()[1] // 1000 ** 3 >= 32, cache_size=1, cache_16bit=False, init_from_mean=True ), train_cfg = dict( dt_gamma_scale=0.5, density_thresh=0.05, extra_scene_step=0, n_inverse_rays=args.n_rays_init, n_decoder_rays=args.n_rays_init, loss_coef=0.1 / (pic_h * pic_w), optimizer=dict(type='Adam', lr=0, weight_decay=0.), lr_scheduler=dict(type='ExponentialLR', gamma=0.99), cache_load_from=None, viz_dir=None, loss_denom=1.0, decoder_grad_clip=1.0 ), test_cfg = dict( img_size=(pic_h, pic_w), density_thresh=0.01, max_render_rays=pic_h * pic_w, dt_gamma_scale=0.5, n_inverse_rays=args.n_rays_init, loss_coef=0.1 / (pic_h * pic_w), n_inverse_steps=400, optimizer=dict(type='Adam', lr=0.0, weight_decay=0.), lr_scheduler=dict(type='ExponentialLR', gamma=0.998), return_depth=False )) nerf.bg_color = nerf.decoder.bg_color = torch.nn.Parameter(torch.ones(3) * args.bg_color, requires_grad=args.learn_bg) nerf.to(device) nerf.train()
optim = build_optimizers(nerf, dict(decoder=dict(type='AdamW', lr=args.net_lr, foreach=True, weight_decay=0.2, betas=(0.9, 0.98))))
1
2023-12-14 03:29:28+00:00
12k
u2seg/U2Seg
detectron2/data/datasets/builtin.py
[ { "identifier": "DatasetCatalog", "path": "detectron2/data/catalog.py", "snippet": "class _DatasetCatalog(UserDict):\nclass Metadata(types.SimpleNamespace):\nclass _MetadataCatalog(UserDict):\n def register(self, name, func):\n def get(self, name):\n def list(self) -> List[str]:\n def remove...
import os from detectron2.data import DatasetCatalog, MetadataCatalog from .builtin_meta import ADE20K_SEM_SEG_CATEGORIES, _get_builtin_metadata from .cityscapes import load_cityscapes_instances, load_cityscapes_semantic from .cityscapes_panoptic import register_all_cityscapes_panoptic from .coco import load_sem_seg, register_coco_instances from .coco_panoptic import register_coco_panoptic, register_coco_panoptic_separated from .lvis import get_lvis_instances_meta, register_lvis_instances from .pascal_voc import register_pascal_voc
8,230
""" # ==== Predefined datasets and splits for COCO ========== cluster_num = os.getenv('CLUSTER_NUM', '800') _PREDEFINED_SPLITS_COCO_SEMI = {} _PREDEFINED_SPLITS_COCO_SEMI["coco_semi"] = { # we use seed 42 to be consistent with previous works on SSL detection and segmentation "coco_semi_1perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/1perc_instances_train2017.json"), "coco_semi_2perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/2perc_instances_train2017.json"), "coco_semi_5perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/5perc_instances_train2017.json"), "coco_semi_10perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/10perc_instances_train2017.json"), "coco_semi_20perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/20perc_instances_train2017.json"), "coco_semi_30perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/30perc_instances_train2017.json"), "coco_semi_40perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/40perc_instances_train2017.json"), "coco_semi_50perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/50perc_instances_train2017.json"), } def register_all_coco_semi(root): for dataset_name, splits_per_dataset in _PREDEFINED_SPLITS_COCO_SEMI.items(): for key, (image_root, json_file) in splits_per_dataset.items(): # Assume pre-defined datasets live in `./datasets`. register_coco_instances( key, _get_builtin_metadata(dataset_name), os.path.join(root, json_file) if "://" not in json_file else json_file, os.path.join(root, image_root), ) _PREDEFINED_SPLITS_COCO = {} _PREDEFINED_SPLITS_COCO["coco"] = { "coco_2014_train": ("coco/train2014", "coco/annotations/instances_train2014.json"), "coco_2014_val": ("coco/val2014", "coco/annotations/instances_val2014.json"), "coco_2014_minival": ("coco/val2014", "coco/annotations/instances_minival2014.json"), "coco_2014_valminusminival": ( "coco/val2014", "coco/annotations/instances_valminusminival2014.json", ), "coco_2017_train": ("./coco/train2017", f"./prepare_ours/u2seg_annotations/ins_annotations/cocotrain_{cluster_num}.json"), "coco_2017_val": ("./coco/val2017", "./coco/annotations/instances_val2017.json"), "coco_2017_test": ("coco/test2017", "coco/annotations/image_info_test2017.json"), "coco_2017_test-dev": ("coco/test2017", "coco/annotations/image_info_test-dev2017.json"), "coco_2017_val_100": ("coco/val2017", "coco/annotations/instances_val2017_100.json"), } _PREDEFINED_SPLITS_COCO["coco_person"] = { "keypoints_coco_2014_train": ( "coco/train2014", "coco/annotations/person_keypoints_train2014.json", ), "keypoints_coco_2014_val": ("coco/val2014", "coco/annotations/person_keypoints_val2014.json"), "keypoints_coco_2014_minival": ( "coco/val2014", "coco/annotations/person_keypoints_minival2014.json", ), "keypoints_coco_2014_valminusminival": ( "coco/val2014", "coco/annotations/person_keypoints_valminusminival2014.json", ), "keypoints_coco_2017_train": ( "coco/train2017", "coco/annotations/person_keypoints_train2017.json", ), "keypoints_coco_2017_val": ("coco/val2017", "coco/annotations/person_keypoints_val2017.json"), "keypoints_coco_2017_val_100": ( "coco/val2017", "coco/annotations/person_keypoints_val2017_100.json", ), } _PREDEFINED_SPLITS_COCO_PANOPTIC = { "coco_2017_train_panoptic": ( # This is the original panoptic annotation directory f"./prepare_ours/u2seg_annotations/panoptic_annotations/cocotrain_{cluster_num}", # this should be .png format annotations f"./prepare_ours/u2seg_annotations/panoptic_annotations/cocotrain_{cluster_num}.json", #this should be .json file # This directory contains semantic annotations that are # converted from panoptic annotations. # It is used by PanopticFPN. # You can use the script at detectron2/datasets/prepare_panoptic_fpn.py # to create these directories. f"./prepare_ours/u2seg_annotations/panoptic_annotations/panoptic_stuff_cocotrain_{cluster_num}", ), "coco_2017_val_panoptic": ( "/home/niudt/u2seg_test/detectron2/datasets/datasets/coco/val2017", "/home/niudt/u2seg_test/detectron2/datasets/datasets/panoptic_anns/panoptic_val2017.json", "/home/niudt/u2seg_test/detectron2/datasets/datasets/panoptic_anns/panoptic_stuff_val2017", ), "coco_2017_val_100_panoptic": ( "coco/panoptic_val2017_100", "coco/annotations/panoptic_val2017_100.json", "coco/panoptic_stuff_val2017_100", ), } def register_all_coco(root): for dataset_name, splits_per_dataset in _PREDEFINED_SPLITS_COCO.items(): for key, (image_root, json_file) in splits_per_dataset.items(): # Assume pre-defined datasets live in `./datasets`. register_coco_instances( key, _get_builtin_metadata(dataset_name), os.path.join(root, json_file) if "://" not in json_file else json_file, os.path.join(root, image_root), ) for ( prefix, (panoptic_root, panoptic_json, semantic_root), ) in _PREDEFINED_SPLITS_COCO_PANOPTIC.items(): prefix_instances = prefix[: -len("_panoptic")] instances_meta = MetadataCatalog.get(prefix_instances) image_root, instances_json = instances_meta.image_root, instances_meta.json_file # The "separated" version of COCO panoptic segmentation dataset, # e.g. used by Panoptic FPN # import pdb # pdb.set_trace()
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. """ This file registers pre-defined datasets at hard-coded paths, and their metadata. We hard-code metadata for common datasets. This will enable: 1. Consistency check when loading the datasets 2. Use models on these standard datasets directly and run demos, without having to download the dataset annotations We hard-code some paths to the dataset that's assumed to exist in "./datasets/". Users SHOULD NOT use this file to create new dataset / metadata for new dataset. To add new dataset, refer to the tutorial "docs/DATASETS.md". """ # ==== Predefined datasets and splits for COCO ========== cluster_num = os.getenv('CLUSTER_NUM', '800') _PREDEFINED_SPLITS_COCO_SEMI = {} _PREDEFINED_SPLITS_COCO_SEMI["coco_semi"] = { # we use seed 42 to be consistent with previous works on SSL detection and segmentation "coco_semi_1perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/1perc_instances_train2017.json"), "coco_semi_2perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/2perc_instances_train2017.json"), "coco_semi_5perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/5perc_instances_train2017.json"), "coco_semi_10perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/10perc_instances_train2017.json"), "coco_semi_20perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/20perc_instances_train2017.json"), "coco_semi_30perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/30perc_instances_train2017.json"), "coco_semi_40perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/40perc_instances_train2017.json"), "coco_semi_50perc": ("/shared/group/coco/train2017", "/shared/niudt/DATASET/coco/annotations/coco-semi/50perc_instances_train2017.json"), } def register_all_coco_semi(root): for dataset_name, splits_per_dataset in _PREDEFINED_SPLITS_COCO_SEMI.items(): for key, (image_root, json_file) in splits_per_dataset.items(): # Assume pre-defined datasets live in `./datasets`. register_coco_instances( key, _get_builtin_metadata(dataset_name), os.path.join(root, json_file) if "://" not in json_file else json_file, os.path.join(root, image_root), ) _PREDEFINED_SPLITS_COCO = {} _PREDEFINED_SPLITS_COCO["coco"] = { "coco_2014_train": ("coco/train2014", "coco/annotations/instances_train2014.json"), "coco_2014_val": ("coco/val2014", "coco/annotations/instances_val2014.json"), "coco_2014_minival": ("coco/val2014", "coco/annotations/instances_minival2014.json"), "coco_2014_valminusminival": ( "coco/val2014", "coco/annotations/instances_valminusminival2014.json", ), "coco_2017_train": ("./coco/train2017", f"./prepare_ours/u2seg_annotations/ins_annotations/cocotrain_{cluster_num}.json"), "coco_2017_val": ("./coco/val2017", "./coco/annotations/instances_val2017.json"), "coco_2017_test": ("coco/test2017", "coco/annotations/image_info_test2017.json"), "coco_2017_test-dev": ("coco/test2017", "coco/annotations/image_info_test-dev2017.json"), "coco_2017_val_100": ("coco/val2017", "coco/annotations/instances_val2017_100.json"), } _PREDEFINED_SPLITS_COCO["coco_person"] = { "keypoints_coco_2014_train": ( "coco/train2014", "coco/annotations/person_keypoints_train2014.json", ), "keypoints_coco_2014_val": ("coco/val2014", "coco/annotations/person_keypoints_val2014.json"), "keypoints_coco_2014_minival": ( "coco/val2014", "coco/annotations/person_keypoints_minival2014.json", ), "keypoints_coco_2014_valminusminival": ( "coco/val2014", "coco/annotations/person_keypoints_valminusminival2014.json", ), "keypoints_coco_2017_train": ( "coco/train2017", "coco/annotations/person_keypoints_train2017.json", ), "keypoints_coco_2017_val": ("coco/val2017", "coco/annotations/person_keypoints_val2017.json"), "keypoints_coco_2017_val_100": ( "coco/val2017", "coco/annotations/person_keypoints_val2017_100.json", ), } _PREDEFINED_SPLITS_COCO_PANOPTIC = { "coco_2017_train_panoptic": ( # This is the original panoptic annotation directory f"./prepare_ours/u2seg_annotations/panoptic_annotations/cocotrain_{cluster_num}", # this should be .png format annotations f"./prepare_ours/u2seg_annotations/panoptic_annotations/cocotrain_{cluster_num}.json", #this should be .json file # This directory contains semantic annotations that are # converted from panoptic annotations. # It is used by PanopticFPN. # You can use the script at detectron2/datasets/prepare_panoptic_fpn.py # to create these directories. f"./prepare_ours/u2seg_annotations/panoptic_annotations/panoptic_stuff_cocotrain_{cluster_num}", ), "coco_2017_val_panoptic": ( "/home/niudt/u2seg_test/detectron2/datasets/datasets/coco/val2017", "/home/niudt/u2seg_test/detectron2/datasets/datasets/panoptic_anns/panoptic_val2017.json", "/home/niudt/u2seg_test/detectron2/datasets/datasets/panoptic_anns/panoptic_stuff_val2017", ), "coco_2017_val_100_panoptic": ( "coco/panoptic_val2017_100", "coco/annotations/panoptic_val2017_100.json", "coco/panoptic_stuff_val2017_100", ), } def register_all_coco(root): for dataset_name, splits_per_dataset in _PREDEFINED_SPLITS_COCO.items(): for key, (image_root, json_file) in splits_per_dataset.items(): # Assume pre-defined datasets live in `./datasets`. register_coco_instances( key, _get_builtin_metadata(dataset_name), os.path.join(root, json_file) if "://" not in json_file else json_file, os.path.join(root, image_root), ) for ( prefix, (panoptic_root, panoptic_json, semantic_root), ) in _PREDEFINED_SPLITS_COCO_PANOPTIC.items(): prefix_instances = prefix[: -len("_panoptic")] instances_meta = MetadataCatalog.get(prefix_instances) image_root, instances_json = instances_meta.image_root, instances_meta.json_file # The "separated" version of COCO panoptic segmentation dataset, # e.g. used by Panoptic FPN # import pdb # pdb.set_trace()
register_coco_panoptic_separated(
9
2023-12-05 01:13:31+00:00
12k
upfusion3d/upfusion
external/nerf/network_df.py
[ { "identifier": "trunc_exp", "path": "external/ngp_activation.py", "snippet": "class _trunc_exp(Function):\n def forward(ctx, x):\n def backward(ctx, g):" }, { "identifier": "NeRFRenderer", "path": "external/nerf/renderer_df.py", "snippet": "class NeRFRenderer(nn.Module):\n def ...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from external.ngp_activation import trunc_exp from external.nerf.renderer_df import NeRFRenderer from external.ngp_encoder import get_encoder from .utils import safe_normalize
9,828
class MLP(nn.Module): def __init__(self, dim_in, dim_out, dim_hidden, num_layers, bias=True): super().__init__() self.dim_in = dim_in self.dim_out = dim_out self.dim_hidden = dim_hidden self.num_layers = num_layers net = [] for l in range(num_layers): net.append(nn.Linear(self.dim_in if l == 0 else self.dim_hidden, self.dim_out if l == num_layers - 1 else self.dim_hidden, bias=bias)) self.net = nn.ModuleList(net) def forward(self, x): for l in range(self.num_layers): x = self.net[l](x) if l != self.num_layers - 1: x = F.relu(x, inplace=True) return x class NeRFNetwork(NeRFRenderer): def __init__(self, opt, num_layers=5, hidden_dim=128, num_layers_bg=2, hidden_dim_bg=64, ): super().__init__(opt) self.num_layers = num_layers self.hidden_dim = hidden_dim self.encoder, self.in_dim = get_encoder('frequency', input_dim=3) self.sigma_net = MLP(self.in_dim, 4, hidden_dim, num_layers, bias=True) # background network if self.bg_radius > 0: self.num_layers_bg = num_layers_bg self.hidden_dim_bg = hidden_dim_bg self.encoder_bg, self.in_dim_bg = get_encoder('frequency', input_dim=3) self.bg_net = MLP(self.in_dim_bg, 3, hidden_dim_bg, num_layers_bg, bias=True) else: self.bg_net = None def gaussian(self, x): # x: [B, N, 3] d = (x ** 2).sum(-1) g = 5 * torch.exp(-d / (2 * 0.2 ** 2)) return g def common_forward(self, x): # x: [N, 3], in [-bound, bound] # sigma h = self.encoder(x, bound=self.bound) h = self.sigma_net(h) sigma = trunc_exp(h[..., 0] + self.gaussian(x)) albedo = torch.sigmoid(h[..., 1:]) return sigma, albedo # ref: https://github.com/zhaofuq/Instant-NSR/blob/main/nerf/network_sdf.py#L192 def finite_difference_normal(self, x, epsilon=1e-2): # x: [N, 3] dx_pos, _ = self.common_forward((x + torch.tensor([[epsilon, 0.00, 0.00]], device=x.device)).clamp(-self.bound, self.bound)) dx_neg, _ = self.common_forward((x + torch.tensor([[-epsilon, 0.00, 0.00]], device=x.device)).clamp(-self.bound, self.bound)) dy_pos, _ = self.common_forward((x + torch.tensor([[0.00, epsilon, 0.00]], device=x.device)).clamp(-self.bound, self.bound)) dy_neg, _ = self.common_forward((x + torch.tensor([[0.00, -epsilon, 0.00]], device=x.device)).clamp(-self.bound, self.bound)) dz_pos, _ = self.common_forward((x + torch.tensor([[0.00, 0.00, epsilon]], device=x.device)).clamp(-self.bound, self.bound)) dz_neg, _ = self.common_forward((x + torch.tensor([[0.00, 0.00, -epsilon]], device=x.device)).clamp(-self.bound, self.bound)) normal = torch.stack([ 0.5 * (dx_pos - dx_neg) / epsilon, 0.5 * (dy_pos - dy_neg) / epsilon, 0.5 * (dz_pos - dz_neg) / epsilon ], dim=-1) return normal def normal(self, x): with torch.enable_grad(): x.requires_grad_(True) sigma, albedo = self.common_forward(x) # query gradient normal = - torch.autograd.grad(torch.sum(sigma), x, create_graph=True)[0] # [N, 3] # normalize...
class MLP(nn.Module): def __init__(self, dim_in, dim_out, dim_hidden, num_layers, bias=True): super().__init__() self.dim_in = dim_in self.dim_out = dim_out self.dim_hidden = dim_hidden self.num_layers = num_layers net = [] for l in range(num_layers): net.append(nn.Linear(self.dim_in if l == 0 else self.dim_hidden, self.dim_out if l == num_layers - 1 else self.dim_hidden, bias=bias)) self.net = nn.ModuleList(net) def forward(self, x): for l in range(self.num_layers): x = self.net[l](x) if l != self.num_layers - 1: x = F.relu(x, inplace=True) return x class NeRFNetwork(NeRFRenderer): def __init__(self, opt, num_layers=5, hidden_dim=128, num_layers_bg=2, hidden_dim_bg=64, ): super().__init__(opt) self.num_layers = num_layers self.hidden_dim = hidden_dim self.encoder, self.in_dim = get_encoder('frequency', input_dim=3) self.sigma_net = MLP(self.in_dim, 4, hidden_dim, num_layers, bias=True) # background network if self.bg_radius > 0: self.num_layers_bg = num_layers_bg self.hidden_dim_bg = hidden_dim_bg self.encoder_bg, self.in_dim_bg = get_encoder('frequency', input_dim=3) self.bg_net = MLP(self.in_dim_bg, 3, hidden_dim_bg, num_layers_bg, bias=True) else: self.bg_net = None def gaussian(self, x): # x: [B, N, 3] d = (x ** 2).sum(-1) g = 5 * torch.exp(-d / (2 * 0.2 ** 2)) return g def common_forward(self, x): # x: [N, 3], in [-bound, bound] # sigma h = self.encoder(x, bound=self.bound) h = self.sigma_net(h) sigma = trunc_exp(h[..., 0] + self.gaussian(x)) albedo = torch.sigmoid(h[..., 1:]) return sigma, albedo # ref: https://github.com/zhaofuq/Instant-NSR/blob/main/nerf/network_sdf.py#L192 def finite_difference_normal(self, x, epsilon=1e-2): # x: [N, 3] dx_pos, _ = self.common_forward((x + torch.tensor([[epsilon, 0.00, 0.00]], device=x.device)).clamp(-self.bound, self.bound)) dx_neg, _ = self.common_forward((x + torch.tensor([[-epsilon, 0.00, 0.00]], device=x.device)).clamp(-self.bound, self.bound)) dy_pos, _ = self.common_forward((x + torch.tensor([[0.00, epsilon, 0.00]], device=x.device)).clamp(-self.bound, self.bound)) dy_neg, _ = self.common_forward((x + torch.tensor([[0.00, -epsilon, 0.00]], device=x.device)).clamp(-self.bound, self.bound)) dz_pos, _ = self.common_forward((x + torch.tensor([[0.00, 0.00, epsilon]], device=x.device)).clamp(-self.bound, self.bound)) dz_neg, _ = self.common_forward((x + torch.tensor([[0.00, 0.00, -epsilon]], device=x.device)).clamp(-self.bound, self.bound)) normal = torch.stack([ 0.5 * (dx_pos - dx_neg) / epsilon, 0.5 * (dy_pos - dy_neg) / epsilon, 0.5 * (dz_pos - dz_neg) / epsilon ], dim=-1) return normal def normal(self, x): with torch.enable_grad(): x.requires_grad_(True) sigma, albedo = self.common_forward(x) # query gradient normal = - torch.autograd.grad(torch.sum(sigma), x, create_graph=True)[0] # [N, 3] # normalize...
normal = safe_normalize(normal)
3
2023-12-12 00:49:11+00:00
12k
modelscope/normal-depth-diffusion
scripts/t2i.py
[ { "identifier": "DDIMSampler", "path": "ldm/models/diffusion/ddim.py", "snippet": "class DDIMSampler(object):\n\n def __init__(self, model, schedule='linear', **kwargs):\n super().__init__()\n self.model = model\n self.ddpm_num_timesteps = model.num_timesteps\n self.schedu...
import argparse import glob import os import pdb import sys import time import cv2 import numpy as np import torch from contextlib import contextmanager, nullcontext from itertools import islice from diffusers.pipelines.stable_diffusion.safety_checker import \ StableDiffusionSafetyChecker from einops import rearrange, repeat from imwatermark import WatermarkEncoder from ldm.models.diffusion.ddim import DDIMSampler from ldm.models.diffusion.dpm_solver import DPMSolverSampler from ldm.models.diffusion.plms import PLMSSampler from ldm.util import instantiate_from_config from model_zoo import build_model from omegaconf import OmegaConf from PIL import Image from pytorch_lightning import seed_everything from torch import autocast from torchvision.utils import make_grid from tqdm import tqdm, trange from transformers import AutoFeatureExtractor from utils.color_transfer import (map_2_16bit, map_16bit_2_8, split_rgbd, split_rgbd_only_tensor, split_rgbd_tensor)
10,267
) parser.add_argument( '--laion400m', action='store_true', help='uses the LAION400M model', ) parser.add_argument( '--fixed_code', action='store_true', help='if enabled, uses the same starting code across 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=1, 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', ) parser.add_argument( '--n_samples', type=int, default=1, 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=7.5, 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', ) parser.add_argument( '--config', type=str, default='./configs/inference/nd/nd-1.5-inference.yaml', help='path to config which constructs model', ) parser.add_argument( '--ckpt', type=str, default='models/ldm/txt2depth/last.ckpt', 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') opt = parser.parse_args() seed_everything(opt.seed) ckpt_name = os.path.splitext(os.path.basename(opt.ckpt))[0] outdir = os.path.join(opt.save_dir, ckpt_name) os.makedirs(outdir, exist_ok=True) outpath = outdir # config = OmegaConf.load(f"{opt.config}") # model = load_model_from_config(config, f"{opt.ckpt}") model = build_model('nd', opt.ckpt, strict=False) device = torch.device( 'cuda') if torch.cuda.is_available() else torch.device('cpu') model = model.to(device) if opt.dpm_solver: sampler = DPMSolverSampler(model) elif opt.plms: sampler = PLMSSampler(model) else:
sys.path.append('./') # load safety model ''' safety_model_id = "CompVis/stable-diffusion-safety-checker" safety_feature_extractor = AutoFeatureExtractor.from_pretrained(safety_model_id) safety_checker = StableDiffusionSafetyChecker.from_pretrained(safety_model_id) ''' NEGATIVE_PROMPTS = 'ugly, tiling, poorly drawn hands, poorly drawn feet, poorly drawn face, out of frame, extra limbs, disfigured, deformed, body out of frame, blurry, bad anatomy, blurred, watermark, grainy, signature, cut off, draft.' def chunk(it, size): it = iter(it) return iter(lambda: tuple(islice(it, size)), ()) def numpy_to_pil(images): """ Convert a numpy image or a batch of images to a PIL image. """ if images.ndim == 3: images = images[None, ...] images = (images * 255).round().astype('uint8') pil_images = [Image.fromarray(image) for image in images] return pil_images def load_model_from_config(config, ckpt, 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) model.cuda() model.eval() return model 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 load_replacement(x): try: hwc = x.shape y = Image.open('assets/rick.jpeg').convert('RGB').resize( (hwc[1], hwc[0])) y = (np.array(y) / 255.0).astype(x.dtype) assert y.shape == x.shape return y except Exception: return x def check_safety(x_image): return x_image, False def main(): parser = argparse.ArgumentParser() parser.add_argument( '--prompt', type=str, nargs='?', default=None, help='the prompt to render') parser.add_argument( '--save_dir', type=str, nargs='?', help='dir to write results to', default='outputs/txt2img-samples') parser.add_argument( '--skip_grid', action='store_true', help= 'do not save a grid, only individual samples. Helpful when evaluating lots of samples', ) parser.add_argument( '--skip_save', action='store_true', help='do not save individual samples. For speed measurements.', ) parser.add_argument( '--ddim_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_solver', action='store_true', help='use dpm_solver sampling', ) parser.add_argument( '--laion400m', action='store_true', help='uses the LAION400M model', ) parser.add_argument( '--fixed_code', action='store_true', help='if enabled, uses the same starting code across 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=1, 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', ) parser.add_argument( '--n_samples', type=int, default=1, 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=7.5, 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', ) parser.add_argument( '--config', type=str, default='./configs/inference/nd/nd-1.5-inference.yaml', help='path to config which constructs model', ) parser.add_argument( '--ckpt', type=str, default='models/ldm/txt2depth/last.ckpt', 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') opt = parser.parse_args() seed_everything(opt.seed) ckpt_name = os.path.splitext(os.path.basename(opt.ckpt))[0] outdir = os.path.join(opt.save_dir, ckpt_name) os.makedirs(outdir, exist_ok=True) outpath = outdir # config = OmegaConf.load(f"{opt.config}") # model = load_model_from_config(config, f"{opt.ckpt}") model = build_model('nd', opt.ckpt, strict=False) device = torch.device( 'cuda') if torch.cuda.is_available() else torch.device('cpu') model = model.to(device) if opt.dpm_solver: sampler = DPMSolverSampler(model) elif opt.plms: sampler = PLMSSampler(model) else:
sampler = DDIMSampler(model)
0
2023-12-06 07:29:34+00:00
12k
FrozenBurning/PrimDiffusion
visualize.py
[ { "identifier": "RayMarcher", "path": "dva/ray_marcher.py", "snippet": "class RayMarcher(nn.Module):\n def __init__(\n self,\n image_height,\n image_width,\n volradius,\n fadescale=8.0,\n fadeexp=8.0,\n dt=1.0,\n ray_subsample_factor=1,\n ...
import os import sys import imageio import torch as th import numpy as np import random import logging from omegaconf import OmegaConf from dva.ray_marcher import RayMarcher, generate_colored_boxes from primdiffusion.dataset.renderpeople_crossid_dataset import RenderPeopleSViewDataset from dva.io import load_static_assets_crossid_smpl, load_from_config from dva.utils import to_device from dva.geom import make_postex, compute_tbn
7,701
) preds_boxes = rm( prim_rgba=boxes_rgba, prim_pos=preds["prim_pos"], prim_scale=preds["prim_scale"], prim_rot=preds["prim_rot"], RT=batch["Rt"], K=batch["K"], ) return preds_boxes["rgba_image"][:, :3].permute(0, 2, 3, 1) def set_random_seed(seed): r"""Set random seeds for everything. Args: seed (int): Random seed. by_rank (bool): """ print(f"Using random seed {seed}") random.seed(seed) np.random.seed(seed) th.manual_seed(seed) th.cuda.manual_seed(seed) th.cuda.manual_seed_all(seed) def to_video_out(input): ndarr = input[0].mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", th.uint8).numpy() return ndarr def main(config): use_ddim = config.ddim device = th.device("cuda:0") th.cuda.set_device(device) static_assets = load_static_assets_crossid_smpl(config) inference_output_dir = f"{config.output_dir}/primdiffusion_interm_visualization" checkpoint_path = config.checkpoint_path os.makedirs(inference_output_dir, exist_ok=True) video_path = os.path.join(inference_output_dir, 'videos') os.makedirs(video_path, exist_ok=True) OmegaConf.save(config, os.path.join(inference_output_dir, "config.yml")) logger.info(f"saving results to {inference_output_dir}") logger.info(f"starting inference with the config: {OmegaConf.to_yaml(config)}") model = load_from_config( config.model, assets=static_assets, ) print('loading checkpoint {}'.format(checkpoint_path)) state_dict = th.load(checkpoint_path, map_location='cpu') model.load_state_dict(state_dict['model_state_dict']) model = model.to(device) model.device = device model.eval() # computing values for the given viewpoints rm = RayMarcher( config.image_height, config.image_width, **config.rm, ).to(device) dataset = RenderPeopleSViewDataset( **config.data, cameras=config.cameras_train, cond_cameras=config.cameras_cond, sample_cameras=False, is_train=False, camera_id='00', ) sample_num = 1 seed_list = [1007,] dataset.gen_inf_cameras(num_views=5) for iter in range(1000): logger.info('Rendering iteration-{:04d}......'.format(iter)) set_random_seed(iter) batch = dataset.sample_cam_smpl() batch = to_device(batch, device) if use_ddim: log_every_t = 1 samples, z_denoise_row = model.sample_log(cond=None, batch_size = sample_num, ddim=True, ddim_steps=100, eta=0.0, log_every_t=log_every_t) z_denoise_row = z_denoise_row['x_inter'] else: log_every_t = 10 samples, z_denoise_row = model.sample_log(cond=None, batch_size = sample_num, ddim=False, ddim_steps=None, eta=0.0, log_every_t=log_every_t) samples = (samples / model.scaling_factor + 1) / 2. * 255. denoise_row = (th.stack(z_denoise_row) / model.scaling_factor + 1) / 2. * 255 prim_size = config.model.bodydecoder_config.prim_size n_prims_x = n_prims_y = int(config.model.bodydecoder_config.n_prims ** 0.5) # plot denoising row denoise_row = denoise_row.reshape(-1, sample_num, prim_size, 7, n_prims_y, prim_size, n_prims_x, prim_size).permute(0, 1, 4, 6, 3, 2, 5, 7).reshape(-1, sample_num, n_prims_y * n_prims_x, 7, prim_size, prim_size, prim_size) denoise_sample_deltascale = th.mean(denoise_row[:, :, :, 4:], dim=(-1, -2, -3)) / 255. * 20. denoise_sample_rgba = denoise_row[:, :, :, :4, :, :, :] num_steps = denoise_row.shape[0] for i in range(sample_num): batch = dataset.sample_cam_smpl() sam_cam = {} sam_cam.update(dataset.inf_cameras[dataset.subject_ids[0]]['camera0000']) for k, v in sam_cam.items(): if isinstance(v, np.ndarray): sam_cam[k] = v[None, ...] batch.update(sam_cam) batch = to_device(batch, device) B = 1 geom = model.bodydecoder.lbs_fn( poses = batch["poses"], shapes = batch["shapes"], Rh = batch["Rh"], Th = batch["Th"], v_template = model.bodydecoder.lbs_fn.v_template[np.newaxis], ) * 1000.0 prim_pos_mesh = (
device = th.device("cuda") logger = logging.getLogger("visualize.py") def render_mvp_boxes(rm, batch, preds): with th.no_grad(): boxes_rgba = generate_colored_boxes( preds["prim_rgba"], preds["prim_rot"], ) preds_boxes = rm( prim_rgba=boxes_rgba, prim_pos=preds["prim_pos"], prim_scale=preds["prim_scale"], prim_rot=preds["prim_rot"], RT=batch["Rt"], K=batch["K"], ) return preds_boxes["rgba_image"][:, :3].permute(0, 2, 3, 1) def set_random_seed(seed): r"""Set random seeds for everything. Args: seed (int): Random seed. by_rank (bool): """ print(f"Using random seed {seed}") random.seed(seed) np.random.seed(seed) th.manual_seed(seed) th.cuda.manual_seed(seed) th.cuda.manual_seed_all(seed) def to_video_out(input): ndarr = input[0].mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", th.uint8).numpy() return ndarr def main(config): use_ddim = config.ddim device = th.device("cuda:0") th.cuda.set_device(device) static_assets = load_static_assets_crossid_smpl(config) inference_output_dir = f"{config.output_dir}/primdiffusion_interm_visualization" checkpoint_path = config.checkpoint_path os.makedirs(inference_output_dir, exist_ok=True) video_path = os.path.join(inference_output_dir, 'videos') os.makedirs(video_path, exist_ok=True) OmegaConf.save(config, os.path.join(inference_output_dir, "config.yml")) logger.info(f"saving results to {inference_output_dir}") logger.info(f"starting inference with the config: {OmegaConf.to_yaml(config)}") model = load_from_config( config.model, assets=static_assets, ) print('loading checkpoint {}'.format(checkpoint_path)) state_dict = th.load(checkpoint_path, map_location='cpu') model.load_state_dict(state_dict['model_state_dict']) model = model.to(device) model.device = device model.eval() # computing values for the given viewpoints rm = RayMarcher( config.image_height, config.image_width, **config.rm, ).to(device) dataset = RenderPeopleSViewDataset( **config.data, cameras=config.cameras_train, cond_cameras=config.cameras_cond, sample_cameras=False, is_train=False, camera_id='00', ) sample_num = 1 seed_list = [1007,] dataset.gen_inf_cameras(num_views=5) for iter in range(1000): logger.info('Rendering iteration-{:04d}......'.format(iter)) set_random_seed(iter) batch = dataset.sample_cam_smpl() batch = to_device(batch, device) if use_ddim: log_every_t = 1 samples, z_denoise_row = model.sample_log(cond=None, batch_size = sample_num, ddim=True, ddim_steps=100, eta=0.0, log_every_t=log_every_t) z_denoise_row = z_denoise_row['x_inter'] else: log_every_t = 10 samples, z_denoise_row = model.sample_log(cond=None, batch_size = sample_num, ddim=False, ddim_steps=None, eta=0.0, log_every_t=log_every_t) samples = (samples / model.scaling_factor + 1) / 2. * 255. denoise_row = (th.stack(z_denoise_row) / model.scaling_factor + 1) / 2. * 255 prim_size = config.model.bodydecoder_config.prim_size n_prims_x = n_prims_y = int(config.model.bodydecoder_config.n_prims ** 0.5) # plot denoising row denoise_row = denoise_row.reshape(-1, sample_num, prim_size, 7, n_prims_y, prim_size, n_prims_x, prim_size).permute(0, 1, 4, 6, 3, 2, 5, 7).reshape(-1, sample_num, n_prims_y * n_prims_x, 7, prim_size, prim_size, prim_size) denoise_sample_deltascale = th.mean(denoise_row[:, :, :, 4:], dim=(-1, -2, -3)) / 255. * 20. denoise_sample_rgba = denoise_row[:, :, :, :4, :, :, :] num_steps = denoise_row.shape[0] for i in range(sample_num): batch = dataset.sample_cam_smpl() sam_cam = {} sam_cam.update(dataset.inf_cameras[dataset.subject_ids[0]]['camera0000']) for k, v in sam_cam.items(): if isinstance(v, np.ndarray): sam_cam[k] = v[None, ...] batch.update(sam_cam) batch = to_device(batch, device) B = 1 geom = model.bodydecoder.lbs_fn( poses = batch["poses"], shapes = batch["shapes"], Rh = batch["Rh"], Th = batch["Th"], v_template = model.bodydecoder.lbs_fn.v_template[np.newaxis], ) * 1000.0 prim_pos_mesh = (
make_postex(geom, model.bodydecoder.prim_vidx_img, model.bodydecoder.prim_bary_img)
6
2023-12-06 05:12:55+00:00
12k
ml-stat-Sustech/TorchCP
tests/test_conformal_training.py
[ { "identifier": "ConfTr", "path": "torchcp/classification/loss/conftr.py", "snippet": "class ConfTr(nn.Module):\n \"\"\"\n Conformal Training (Stutz et al., 2021).\n Paper: https://arxiv.org/abs/2110.09192\n\n :param weight: the weight of each loss function\n :param predictor: the CP pred...
import argparse import itertools import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from dataset import build_dataset from torchcp.classification.loss import ConfTr from torchcp.classification.predictors import SplitPredictor, ClusterPredictor, ClassWisePredictor from torchcp.classification.scores import THR, APS, SAPS, RAPS from torchcp.utils import fix_randomness
8,108
# Copyright (c) 2023-present, SUSTech-ML. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # # @Time : 13/12/2023 21:13 # Copyright (c) 2023-present, SUSTech-ML. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(28 * 28, 500) self.fc2 = nn.Linear(500, 10) def forward(self, x): x = x.view(-1, 28 * 28) x = F.relu(self.fc1(x)) x = self.fc2(x) return x def train(model, device, train_loader,criterion, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() def test_training(): alpha = 0.01 num_trials = 5 result = {} for loss in ["CE", "ConfTr"]: print(f"############################## {loss} #########################") result[loss] = {} if loss == "CE": criterion = nn.CrossEntropyLoss() elif loss == "ConfTr": predictor = SplitPredictor(score_function=THR(score_type="log_softmax"))
# Copyright (c) 2023-present, SUSTech-ML. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # # @Time : 13/12/2023 21:13 # Copyright (c) 2023-present, SUSTech-ML. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(28 * 28, 500) self.fc2 = nn.Linear(500, 10) def forward(self, x): x = x.view(-1, 28 * 28) x = F.relu(self.fc1(x)) x = self.fc2(x) return x def train(model, device, train_loader,criterion, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() def test_training(): alpha = 0.01 num_trials = 5 result = {} for loss in ["CE", "ConfTr"]: print(f"############################## {loss} #########################") result[loss] = {} if loss == "CE": criterion = nn.CrossEntropyLoss() elif loss == "ConfTr": predictor = SplitPredictor(score_function=THR(score_type="log_softmax"))
criterion = ConfTr(weight=0.01,
0
2023-12-06 09:08:41+00:00
12k
OpenDriveLab/LaneSegNet
projects/lanesegnet/models/modules/bevformer_constructer.py
[ { "identifier": "BEV_CONSTRUCTOR", "path": "projects/lanesegnet/utils/builder.py", "snippet": "BEV_CONSTRUCTOR = Registry('BEV Constructor')" }, { "identifier": "TemporalSelfAttention", "path": "projects/bevformer/modules/temporal_self_attention.py", "snippet": "class TemporalSelfAttenti...
import numpy as np import torch import torch.nn as nn from torch.nn.init import normal_ from torchvision.transforms.functional import rotate from mmcv.cnn import xavier_init from mmcv.cnn.bricks.transformer import build_transformer_layer_sequence, build_positional_encoding from mmcv.runner.base_module import BaseModule from ...utils.builder import BEV_CONSTRUCTOR from projects.bevformer.modules.temporal_self_attention import TemporalSelfAttention from projects.bevformer.modules.spatial_cross_attention import MSDeformableAttention3D from projects.bevformer.modules.decoder import CustomMSDeformableAttention
8,438
#---------------------------------------------------------------------------------------# # LaneSegNet: Map Learning with Lane Segment Perception for Autonomous Driving # # Source code: https://github.com/OpenDriveLab/LaneSegNet # # Copyright (c) OpenDriveLab. All rights reserved. # #---------------------------------------------------------------------------------------# @BEV_CONSTRUCTOR.register_module() class BEVFormerConstructer(BaseModule): """Implements the BEVFormer BEV Constructer. Args: as_two_stage (bool): Generate query from encoder features. Default: False. num_feature_levels (int): Number of feature maps from FPN: Default: 4. two_stage_num_proposals (int): Number of proposals when set `as_two_stage` as True. Default: 300. """ def __init__(self, num_feature_levels=4, num_cams=6, embed_dims=256, rotate_prev_bev=True, use_shift=True, use_can_bus=True, can_bus_norm=True, use_cams_embeds=True, pc_range=[-51.2, -51.2, -5.0, 51.2, 51.2, 3.0], bev_h=200, bev_w=200, rotate_center=[100, 100], encoder=None, positional_encoding=None, **kwargs): super(BEVFormerConstructer, self).__init__(**kwargs) self.embed_dims = embed_dims self.num_feature_levels = num_feature_levels self.num_cams = num_cams self.fp16_enabled = False self.rotate_prev_bev = rotate_prev_bev self.use_shift = use_shift self.use_can_bus = use_can_bus self.can_bus_norm = can_bus_norm self.use_cams_embeds = use_cams_embeds self.encoder = build_transformer_layer_sequence(encoder) self.positional_encoding = build_positional_encoding(positional_encoding) self.pc_range = pc_range self.real_w = self.pc_range[3] - self.pc_range[0] self.real_h = self.pc_range[4] - self.pc_range[1] self.bev_h = bev_h self.bev_w = bev_w self.rotate_center = rotate_center self.init_layers() def init_layers(self): self.bev_embedding = nn.Embedding( self.bev_h * self.bev_w, self.embed_dims) self.level_embeds = nn.Parameter(torch.Tensor( self.num_feature_levels, self.embed_dims)) self.cams_embeds = nn.Parameter( torch.Tensor(self.num_cams, self.embed_dims)) self.can_bus_mlp = nn.Sequential( nn.Linear(18, self.embed_dims // 2), nn.ReLU(inplace=True), nn.Linear(self.embed_dims // 2, self.embed_dims), nn.ReLU(inplace=True), ) if self.can_bus_norm: self.can_bus_mlp.add_module('norm', nn.LayerNorm(self.embed_dims)) def init_weights(self): """Initialize the transformer weights.""" for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) for m in self.modules():
#---------------------------------------------------------------------------------------# # LaneSegNet: Map Learning with Lane Segment Perception for Autonomous Driving # # Source code: https://github.com/OpenDriveLab/LaneSegNet # # Copyright (c) OpenDriveLab. All rights reserved. # #---------------------------------------------------------------------------------------# @BEV_CONSTRUCTOR.register_module() class BEVFormerConstructer(BaseModule): """Implements the BEVFormer BEV Constructer. Args: as_two_stage (bool): Generate query from encoder features. Default: False. num_feature_levels (int): Number of feature maps from FPN: Default: 4. two_stage_num_proposals (int): Number of proposals when set `as_two_stage` as True. Default: 300. """ def __init__(self, num_feature_levels=4, num_cams=6, embed_dims=256, rotate_prev_bev=True, use_shift=True, use_can_bus=True, can_bus_norm=True, use_cams_embeds=True, pc_range=[-51.2, -51.2, -5.0, 51.2, 51.2, 3.0], bev_h=200, bev_w=200, rotate_center=[100, 100], encoder=None, positional_encoding=None, **kwargs): super(BEVFormerConstructer, self).__init__(**kwargs) self.embed_dims = embed_dims self.num_feature_levels = num_feature_levels self.num_cams = num_cams self.fp16_enabled = False self.rotate_prev_bev = rotate_prev_bev self.use_shift = use_shift self.use_can_bus = use_can_bus self.can_bus_norm = can_bus_norm self.use_cams_embeds = use_cams_embeds self.encoder = build_transformer_layer_sequence(encoder) self.positional_encoding = build_positional_encoding(positional_encoding) self.pc_range = pc_range self.real_w = self.pc_range[3] - self.pc_range[0] self.real_h = self.pc_range[4] - self.pc_range[1] self.bev_h = bev_h self.bev_w = bev_w self.rotate_center = rotate_center self.init_layers() def init_layers(self): self.bev_embedding = nn.Embedding( self.bev_h * self.bev_w, self.embed_dims) self.level_embeds = nn.Parameter(torch.Tensor( self.num_feature_levels, self.embed_dims)) self.cams_embeds = nn.Parameter( torch.Tensor(self.num_cams, self.embed_dims)) self.can_bus_mlp = nn.Sequential( nn.Linear(18, self.embed_dims // 2), nn.ReLU(inplace=True), nn.Linear(self.embed_dims // 2, self.embed_dims), nn.ReLU(inplace=True), ) if self.can_bus_norm: self.can_bus_mlp.add_module('norm', nn.LayerNorm(self.embed_dims)) def init_weights(self): """Initialize the transformer weights.""" for p in self.parameters(): if p.dim() > 1: nn.init.xavier_uniform_(p) for m in self.modules():
if isinstance(m, MSDeformableAttention3D) or isinstance(m, TemporalSelfAttention) \
2
2023-12-06 07:13:48+00:00
12k
RobertCsordas/moe_attention
layers/transformer/moe_attention_relative_transformer.py
[ { "identifier": "AttentionMask", "path": "layers/transformer/multi_head_relative_pos_attention.py", "snippet": "def shift(posmat: torch.Tensor) -> torch.Tensor:\n def __init__(self, state_size: int, n_heads: int, dropout: float, projection_size: Optional[int] = None):\n def get_attention_scores(se...
from typing import Optional from .multi_head_relative_pos_attention import AttentionMask from .transformer import ActivationFunction from .transformer_preln import reset_prenorm_params from .full_moe_relative_attention import FullMoeRelativeAttention, FullMoeRopeAttention from .moa import MoA import torch import torch.nn import torch.nn.functional as F import math
7,348
class MoeAttentionRelativeTransformerEncoderLayer(torch.nn.Module): def __init__(self, d_model, nhead, moe_att_n_experts, dim_feedforward=2048, dropout=0.1, activation: ActivationFunction = F.relu, attention_dropout=0, drop_expand: bool = True, head_projection_size: Optional[int] = None, preln: bool = False, n_layers: Optional[int] = None, att_perplexity_reg: float = 0.0, expert_dropout: float = 0.0, att_selection_mode="sigmoid", attention_variant="moa", q_expert: bool = True, k_expert: bool = True, v_expert: bool = True, o_expert: bool = True, moe_k: int = 2, norm_qk_score: bool = False, v_projection_size: Optional[int] = None, same_sel: bool = False, qside_n_experts: Optional[int] = None, shared_experts: bool = False, kq_n_experts: Optional[int] = None, separate_kq_sel: bool = False, cvloss: float = 0.0, switchloss: float = 0.0, zloss: float = 0.0, moa_mode: str = "my", rotate_fraction: float = 0.5, rope_base: float = 10000, moeatt_norm_init: bool = False): super().__init__() self.is_preln = preln if attention_variant not in {"full", "full_rope"} and (not q_expert): raise ValueError("q_expert can be disabled only when using qside attention") if attention_variant == "moa":
class MoeAttentionRelativeTransformerEncoderLayer(torch.nn.Module): def __init__(self, d_model, nhead, moe_att_n_experts, dim_feedforward=2048, dropout=0.1, activation: ActivationFunction = F.relu, attention_dropout=0, drop_expand: bool = True, head_projection_size: Optional[int] = None, preln: bool = False, n_layers: Optional[int] = None, att_perplexity_reg: float = 0.0, expert_dropout: float = 0.0, att_selection_mode="sigmoid", attention_variant="moa", q_expert: bool = True, k_expert: bool = True, v_expert: bool = True, o_expert: bool = True, moe_k: int = 2, norm_qk_score: bool = False, v_projection_size: Optional[int] = None, same_sel: bool = False, qside_n_experts: Optional[int] = None, shared_experts: bool = False, kq_n_experts: Optional[int] = None, separate_kq_sel: bool = False, cvloss: float = 0.0, switchloss: float = 0.0, zloss: float = 0.0, moa_mode: str = "my", rotate_fraction: float = 0.5, rope_base: float = 10000, moeatt_norm_init: bool = False): super().__init__() self.is_preln = preln if attention_variant not in {"full", "full_rope"} and (not q_expert): raise ValueError("q_expert can be disabled only when using qside attention") if attention_variant == "moa":
self.self_attn = MoA(
5
2023-12-13 08:45:02+00:00
12k
Q-Future/Q-Align
q_align/model/convert_mplug_owl2_weight_to_hf.py
[ { "identifier": "MPLUGOwl2Config", "path": "q_align/model/configuration_mplug_owl2.py", "snippet": "class MPLUGOwl2Config(LlamaConfig):\n model_type = \"mplug_owl2\"\n def __init__(self, visual_config=None, **kwargs):\n if visual_config is None:\n self.visual_config = DEFAULT_VIS...
import argparse import gc import json import math import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer from .configuration_mplug_owl2 import MPLUGOwl2Config, MplugOwlVisionConfig, MplugOwlVisualAbstractorConfig from .modeling_mplug_owl2 import MPLUGOwl2LlamaForCausalLM from transformers import LlamaTokenizerFast
8,310
# dim=0, # ).reshape(n_hidden, n_hidden) # ) # state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat( # [ # wv.view(n_heads_per_shard, hidden_per_head, n_hidden) # for wv in range(wvs) # ], # dim=0, # ).reshape(n_hidden, n_hidden) # state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat( # [loaded[i]['encoder'][f"layers.{layer_i}.self_attention.o_proj.weight"] for i in range(num_shards)], dim=1 # ) # state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat( # [loaded[i]['encoder'][f"layers.{layer_i}.mlp.gate_proj.weight"] for i in range(num_shards)], dim=0 # ) # state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat( # [loaded[i]['encoder'][f"layers.{layer_i}.mlp.down_proj.weight"] for i in range(num_shards)], dim=1 # ) # state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat( # [loaded[i]['encoder'][f"layers.{layer_i}.mlp.up_proj.weight"] for i in range(num_shards)], dim=0 # ) state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq for k, v in state_dict.items(): index_dict["weight_map"][k] = filename param_count += v.numel() torch.save(state_dict, os.path.join(tmp_model_path, filename)) print(f'Sharded file saved to {filename}') filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if num_shards==1: # Unsharded state_dict = { "model.embed_tokens.weight": loaded['embedding']['word_embeddings']['weight'], "model.norm.weight": loaded['encoder']['norm.weight'], "lm_head.weight": loaded['encoder']['lm_head.weight'], } else: state_dict = { "model.embed_tokens.weight": loaded[0]['embedding']['word_embeddings']['weight'], "model.norm.weight": loaded[0]['encoder']['norm.weight'], "lm_head.weight": loaded[0]['encoder']['lm_head.weight'], } loaded_all = torch.load(original_filename, map_location="cpu")['model'] # Vision Part state_dict.update({ "model.vision_model.embeddings.cls_token": loaded_all['vision_model']['cls_token'], "model.vision_model.embeddings.patch_embed.weight": loaded_all['vision_model']['patch_embed']['weight'], "model.vision_model.embeddings.position_embedding": loaded_all['vision_model']['position_embeddings'], "model.vision_model.embeddings.pre_layernorm.bias": loaded_all['vision_model']['pre_layernorm']['bias'], "model.vision_model.embeddings.pre_layernorm.weight": loaded_all['vision_model']['pre_layernorm']['weight'], "model.vision_model.post_layernorm.bias": loaded_all['vision_model']['transformer']['final_layernorm.bias'], "model.vision_model.post_layernorm.weight": loaded_all['vision_model']['transformer']['final_layernorm.weight'], }) for v_layer_idx in range(24): state_dict.update({ f"model.vision_model.encoder.layers.{v_layer_idx}.input_layernorm.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.input_layernorm.bias'], f"model.vision_model.encoder.layers.{v_layer_idx}.input_layernorm.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.input_layernorm.weight'], f"model.vision_model.encoder.layers.{v_layer_idx}.mlp.fc1.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.mlp.dense_h_to_4h.bias'], f"model.vision_model.encoder.layers.{v_layer_idx}.mlp.fc1.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.mlp.dense_h_to_4h.weight'], f"model.vision_model.encoder.layers.{v_layer_idx}.mlp.fc2.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.mlp.dense_4h_to_h.bias'], f"model.vision_model.encoder.layers.{v_layer_idx}.mlp.fc2.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.mlp.dense_4h_to_h.weight'], f"model.vision_model.encoder.layers.{v_layer_idx}.post_attention_layernorm.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.post_attention_layernorm.bias'], f"model.vision_model.encoder.layers.{v_layer_idx}.post_attention_layernorm.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.post_attention_layernorm.weight'], f"model.vision_model.encoder.layers.{v_layer_idx}.self_attn.dense.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.self_attention.dense.bias'], f"model.vision_model.encoder.layers.{v_layer_idx}.self_attn.dense.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.self_attention.dense.weight'], f"model.vision_model.encoder.layers.{v_layer_idx}.self_attn.query_key_value.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.self_attention.query_key_value.bias'], f"model.vision_model.encoder.layers.{v_layer_idx}.self_attn.query_key_value.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.self_attention.query_key_value.weight'], }) # Abstractor Part state_dict.update({ "model.visual_abstractor.query_embeds": loaded_all['vision_abstractor']['learnable_queries'], "model.visual_abstractor.visual_fc.bias": loaded_all['vision_abstractor']['visual_fc']['bias'], "model.visual_abstractor.visual_fc.weight": loaded_all['vision_abstractor']['visual_fc']['weight'], "model.visual_abstractor.vit_eos": loaded_all['vision_abstractor']['vit_eos'], }) for v_layer_idx in range(6): state_dict.update({ # f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.k_pos_embed": f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.key.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.k_proj.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.key.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.k_proj.weight"], # f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.q_pos_embed": "pytorch_model-00004-of-00004.bin", f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.query.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.q_proj.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.query.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.q_proj.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.value.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.v_proj.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.value.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.v_proj.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.norm1.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.norm1.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.norm1.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.norm1.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.normk.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.normk.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.normk.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.normk.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.ffn_ln.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.ffn_ln.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.ffn_ln.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.ffn_ln.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w1.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w1.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w1.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w1.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w2.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w2.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w2.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w2.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w3.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w3.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w3.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w3.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.norm2.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.norm2.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.norm2.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.norm2.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.out_proj.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.o_proj.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.out_proj.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.o_proj.weight"], }) for k, v in state_dict.items(): index_dict["weight_map"][k] = filename param_count += v.numel() torch.save(state_dict, os.path.join(tmp_model_path, filename)) # Write configs index_dict["metadata"] = {"total_size": param_count * 2} write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json"))
# Copyright 2023 DAMO Academy and The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: except ImportError as e: warnings.warn(e) warnings.warn( "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion" ) LlamaTokenizerFast = None """ Sample usage: ``` python3 /pure-mlo-scratch/sfan/model-parallel-trainer/llama2megatron/convert_llama2hf.py \ --input_dir /pure-mlo-scratch/llama/ --model_size 7 --output_dir /pure-mlo-scratch/llama/converted_HF_7B ``` Thereafter, models can be loaded via: ```py from transformers import LlamaForCausalLM, LlamaTokenizer model = LlamaForCausalLM.from_pretrained("/output/path") tokenizer = LlamaTokenizer.from_pretrained("/output/path") ``` Important note: you need to be able to host the whole model in RAM to execute this script (even if the biggest versions come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM). """ llama_s2layer = {7: 32, 13: 40, 30: 60, 65: 80, 70: 80} llama_s2heads = {7: 32, 13: 40, 30: 52, 65: 64, 70: 64} llama_s2dense = {7: 11008, 13: 13824, 30: 17920, 65: 22016, 70: 28672} # should be (2/3)*4*d, but it isn't exaclty that llama_s2hidden = {7: 4096, 13: 5120, 32: 6656, 65: 8192, 70: 8192} def compute_intermediate_size(n): return int(math.ceil(n * 8 / 3) + 255) // 256 * 256 def read_json(path): with open(path, "r") as f: return json.load(f) def write_json(text, path): with open(path, "w") as f: json.dump(text, f) def write_model(model_path, input_base_path, model_size, num_input_shards=1, num_output_shards=2, skip_permute=True, norm_eps=1e-05): # if os.path.exists(model_path): # shutil.rmtree(model_path) os.makedirs(model_path, exist_ok=True) # tmp_model_path = os.path.join(model_path, "tmp") tmp_model_path = model_path os.makedirs(tmp_model_path, exist_ok=True) num_shards = num_input_shards n_layers = llama_s2layer[model_size] n_heads = llama_s2heads[model_size] n_heads_per_shard = n_heads // num_shards n_dense = llama_s2dense[model_size] n_hidden = llama_s2hidden[model_size] hidden_per_head = n_hidden // n_heads base = 10000.0 inv_freq = 1.0 / (base ** (torch.arange(0, hidden_per_head, 2).float() / hidden_per_head)) # permute for sliced rotary def permute(w, skip_permute=skip_permute): if skip_permute: return w return w.view(n_heads, n_hidden // n_heads // 2, 2, n_hidden).transpose(1, 2).reshape(n_hidden, n_hidden) print(f"Fetching all parameters from the checkpoint at {input_base_path}.") # Load weights if num_shards==1: # Not sharded # (The sharded implementation would also work, but this is simpler.) # /pure-mlo-scratch/alhernan/megatron-data/checkpoints/llama2-7b-tp4-pp1-optim/release/mp_rank_00/model_optim_rng.pt if os.path.exists(os.path.join(input_base_path, 'release')): filename = os.path.join(input_base_path, 'release', 'mp_rank_00', 'model_optim_rng.pt') elif input_base_path.split('/')[-1].startswith('iter_'): iteration = eval(input_base_path.split('/')[-1].replace('iter_', '').lstrip('0')) load_dir = '/'.join(input_base_path.split('/')[:-1]) filename = os.path.join(input_base_path, 'mp_rank_00', 'model_optim_rng.pt') if not os.path.exists(filename): filename = filename.replace('model_optim_rng.pt', 'model_rng.pt') else: tracker_filename = os.path.join(input_base_path, 'latest_checkpointed_iteration.txt') with open(tracker_filename, 'r') as f: metastring = f.read().strip() iteration = 'iter_{:07d}'.format(int(metastring)) filename = os.path.join(input_base_path, iteration, 'mp_rank_00', 'model_optim_rng.pt') if not os.path.exists(filename): filename = filename.replace('model_optim_rng.pt', 'model_rng.pt') original_filename = filename loaded = torch.load(filename, map_location="cpu")['model']['language_model'] else: # Sharded filenames = [] for i in range(num_shards): if os.path.exists(os.path.join(input_base_path, 'release')): filename = os.path.join(input_base_path, 'release', f'mp_rank_{i:02d}', 'model_optim_rng.pt') else: tracker_filename = os.path.join(input_base_path, 'latest_checkpointed_iteration.txt') with open(tracker_filename, 'r') as f: metastring = f.read().strip() iteration = 'iter_{:07d}'.format(int(metastring)) filename = os.path.join(input_base_path, iteration, f'mp_rank_{i:02d}', 'model_optim_rng.pt') if not os.path.exists(filename): filename = filename.replace('model_optim_rng.pt', 'model_rng.pt') filenames.append(filename) loaded = [ torch.load(filenames[i], map_location="cpu")['model']['language_model'] for i in range(num_shards) ] print('Llama-Megatron Loaded!') param_count = 0 index_dict = {"weight_map": {}} print(f'Weighted Converting for {n_layers} layers...') for layer_i in range(n_layers): print(layer_i) filename = f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin" if num_shards == 1: # Unsharded state_dict = { f"model.layers.{layer_i}.self_attn.q_proj.weight": loaded['encoder'][f"layers.{layer_i}.self_attention.q_proj.weight"], f"model.layers.{layer_i}.self_attn.k_proj.multiway.0.weight": loaded['encoder'][f"layers.{layer_i}.self_attention.k_proj.multiway.0.weight"], f"model.layers.{layer_i}.self_attn.v_proj.multiway.0.weight": loaded['encoder'][f"layers.{layer_i}.self_attention.v_proj.multiway.0.weight"], f"model.layers.{layer_i}.self_attn.k_proj.multiway.1.weight": loaded['encoder'][f"layers.{layer_i}.self_attention.k_proj.multiway.1.weight"], f"model.layers.{layer_i}.self_attn.v_proj.multiway.1.weight": loaded['encoder'][f"layers.{layer_i}.self_attention.v_proj.multiway.1.weight"], f"model.layers.{layer_i}.self_attn.o_proj.weight": loaded['encoder'][f"layers.{layer_i}.self_attention.o_proj.weight"], f"model.layers.{layer_i}.mlp.gate_proj.weight": loaded['encoder'][f"layers.{layer_i}.mlp.gate_proj.weight"], f"model.layers.{layer_i}.mlp.down_proj.weight": loaded['encoder'][f"layers.{layer_i}.mlp.down_proj.weight"], f"model.layers.{layer_i}.mlp.up_proj.weight": loaded['encoder'][f"layers.{layer_i}.mlp.up_proj.weight"], f"model.layers.{layer_i}.input_layernorm.multiway.0.weight": loaded['encoder'][f"layers.{layer_i}.input_layernorm.multiway.0.weight"], f"model.layers.{layer_i}.post_attention_layernorm.multiway.0.weight": loaded['encoder'][f"layers.{layer_i}.post_attention_layernorm.multiway.0.weight"], f"model.layers.{layer_i}.input_layernorm.multiway.1.weight": loaded['encoder'][f"layers.{layer_i}.input_layernorm.multiway.1.weight"], f"model.layers.{layer_i}.post_attention_layernorm.multiway.1.weight": loaded['encoder'][f"layers.{layer_i}.post_attention_layernorm.multiway.1.weight"], } else: raise NotImplemented # else: # # Sharded # # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. # state_dict = { # f"model.layers.{layer_i}.input_layernorm.weight": loaded[0]['encoder'][ # f"layers.{layer_i}.input_layernorm.multiway.0.weight" # ].clone(), # f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0]['encoder'][ # f"layers.{layer_i}.post_attention_layernorm.multiway.0.weight" # ].clone(), # } # wqs, wks, wvs, ffn_w1s, ffn_w3s = [], [], [], [], [] # for shard_idx in range(num_shards): # wqs.append(loaded[shard_idx]['encoder'][f"layers.{layer_i}.self_attention.q_proj.weight"]) # wks.append(loaded[shard_idx]['encoder'][f"layers.{layer_i}.self_attention.k_proj.multiway.0.weight"]) # wvs.append(loaded[shard_idx]['encoder'][f"layers.{layer_i}.self_attention.v_proj.multiway.0.weight"]) # state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute( # torch.cat( # [ # wq.view(n_heads_per_shard, hidden_per_head, n_hidden) # for wq in range(wqs) # ], # dim=0, # ).reshape(n_hidden, n_hidden) # ) # state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute( # torch.cat( # [ # wk.view(n_heads_per_shard, hidden_per_head, n_hidden) # for wk in range(wks) # ], # dim=0, # ).reshape(n_hidden, n_hidden) # ) # state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat( # [ # wv.view(n_heads_per_shard, hidden_per_head, n_hidden) # for wv in range(wvs) # ], # dim=0, # ).reshape(n_hidden, n_hidden) # state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat( # [loaded[i]['encoder'][f"layers.{layer_i}.self_attention.o_proj.weight"] for i in range(num_shards)], dim=1 # ) # state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat( # [loaded[i]['encoder'][f"layers.{layer_i}.mlp.gate_proj.weight"] for i in range(num_shards)], dim=0 # ) # state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat( # [loaded[i]['encoder'][f"layers.{layer_i}.mlp.down_proj.weight"] for i in range(num_shards)], dim=1 # ) # state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat( # [loaded[i]['encoder'][f"layers.{layer_i}.mlp.up_proj.weight"] for i in range(num_shards)], dim=0 # ) state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq for k, v in state_dict.items(): index_dict["weight_map"][k] = filename param_count += v.numel() torch.save(state_dict, os.path.join(tmp_model_path, filename)) print(f'Sharded file saved to {filename}') filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin" if num_shards==1: # Unsharded state_dict = { "model.embed_tokens.weight": loaded['embedding']['word_embeddings']['weight'], "model.norm.weight": loaded['encoder']['norm.weight'], "lm_head.weight": loaded['encoder']['lm_head.weight'], } else: state_dict = { "model.embed_tokens.weight": loaded[0]['embedding']['word_embeddings']['weight'], "model.norm.weight": loaded[0]['encoder']['norm.weight'], "lm_head.weight": loaded[0]['encoder']['lm_head.weight'], } loaded_all = torch.load(original_filename, map_location="cpu")['model'] # Vision Part state_dict.update({ "model.vision_model.embeddings.cls_token": loaded_all['vision_model']['cls_token'], "model.vision_model.embeddings.patch_embed.weight": loaded_all['vision_model']['patch_embed']['weight'], "model.vision_model.embeddings.position_embedding": loaded_all['vision_model']['position_embeddings'], "model.vision_model.embeddings.pre_layernorm.bias": loaded_all['vision_model']['pre_layernorm']['bias'], "model.vision_model.embeddings.pre_layernorm.weight": loaded_all['vision_model']['pre_layernorm']['weight'], "model.vision_model.post_layernorm.bias": loaded_all['vision_model']['transformer']['final_layernorm.bias'], "model.vision_model.post_layernorm.weight": loaded_all['vision_model']['transformer']['final_layernorm.weight'], }) for v_layer_idx in range(24): state_dict.update({ f"model.vision_model.encoder.layers.{v_layer_idx}.input_layernorm.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.input_layernorm.bias'], f"model.vision_model.encoder.layers.{v_layer_idx}.input_layernorm.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.input_layernorm.weight'], f"model.vision_model.encoder.layers.{v_layer_idx}.mlp.fc1.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.mlp.dense_h_to_4h.bias'], f"model.vision_model.encoder.layers.{v_layer_idx}.mlp.fc1.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.mlp.dense_h_to_4h.weight'], f"model.vision_model.encoder.layers.{v_layer_idx}.mlp.fc2.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.mlp.dense_4h_to_h.bias'], f"model.vision_model.encoder.layers.{v_layer_idx}.mlp.fc2.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.mlp.dense_4h_to_h.weight'], f"model.vision_model.encoder.layers.{v_layer_idx}.post_attention_layernorm.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.post_attention_layernorm.bias'], f"model.vision_model.encoder.layers.{v_layer_idx}.post_attention_layernorm.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.post_attention_layernorm.weight'], f"model.vision_model.encoder.layers.{v_layer_idx}.self_attn.dense.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.self_attention.dense.bias'], f"model.vision_model.encoder.layers.{v_layer_idx}.self_attn.dense.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.self_attention.dense.weight'], f"model.vision_model.encoder.layers.{v_layer_idx}.self_attn.query_key_value.bias": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.self_attention.query_key_value.bias'], f"model.vision_model.encoder.layers.{v_layer_idx}.self_attn.query_key_value.weight": loaded_all['vision_model']['transformer'][f'layers.{v_layer_idx}.self_attention.query_key_value.weight'], }) # Abstractor Part state_dict.update({ "model.visual_abstractor.query_embeds": loaded_all['vision_abstractor']['learnable_queries'], "model.visual_abstractor.visual_fc.bias": loaded_all['vision_abstractor']['visual_fc']['bias'], "model.visual_abstractor.visual_fc.weight": loaded_all['vision_abstractor']['visual_fc']['weight'], "model.visual_abstractor.vit_eos": loaded_all['vision_abstractor']['vit_eos'], }) for v_layer_idx in range(6): state_dict.update({ # f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.k_pos_embed": f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.key.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.k_proj.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.key.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.k_proj.weight"], # f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.q_pos_embed": "pytorch_model-00004-of-00004.bin", f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.query.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.q_proj.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.query.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.q_proj.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.value.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.v_proj.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.attention.value.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.v_proj.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.norm1.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.norm1.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.norm1.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.norm1.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.normk.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.normk.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.normk.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.normk.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.ffn_ln.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.ffn_ln.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.ffn_ln.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.ffn_ln.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w1.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w1.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w1.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w1.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w2.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w2.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w2.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w2.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w3.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w3.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.mlp.w3.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.mlp.w3.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.norm2.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.norm2.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.norm2.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.norm2.weight"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.out_proj.bias": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.o_proj.bias"], f"model.visual_abstractor.encoder.layers.{v_layer_idx}.crossattention.output.out_proj.weight": loaded_all['vision_abstractor']['transformer'][f"layers.{v_layer_idx}.self_attention.o_proj.weight"], }) for k, v in state_dict.items(): index_dict["weight_map"][k] = filename param_count += v.numel() torch.save(state_dict, os.path.join(tmp_model_path, filename)) # Write configs index_dict["metadata"] = {"total_size": param_count * 2} write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json"))
config = MPLUGOwl2Config()
0
2023-12-14 03:36:30+00:00
12k
nox-410/tvm.tl
python/tvm/target/detect_target.py
[ { "identifier": "Target", "path": "python/tvm/target/target.py", "snippet": "class Target(Object):\n \"\"\"Target device information, use through TVM API.\n\n Note\n ----\n You can create target using the constructor or the following functions\n\n - :py:func:`tvm.target.arm_cpu` create ar...
from typing import Union from . import Target from .._ffi import get_global_func from .._ffi.runtime_ctypes import Device from ..runtime.ndarray import device
7,225
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. """Detect target.""" def _detect_metal(dev: Device) -> Target: return Target( { "kind": "metal", "max_shared_memory_per_block": 32768, "max_threads_per_block": dev.max_threads_per_block, "thread_warp_size": dev.warp_size, } ) def _detect_cuda(dev: Device) -> Target: return Target( { "kind": "cuda", "max_shared_memory_per_block": dev.max_shared_memory_per_block, "max_threads_per_block": dev.max_threads_per_block, "thread_warp_size": dev.warp_size, "arch": "sm_" + dev.compute_version.replace(".", ""), } ) def _detect_rocm(dev: Device) -> Target: return Target( { "kind": "rocm", "mtriple": "amdgcn-and-amdhsa-hcc", "max_shared_memory_per_block": dev.max_shared_memory_per_block, "max_threads_per_block": dev.max_threads_per_block, "thread_warp_size": dev.warp_size, } ) def _detect_vulkan(dev: Device) -> Target:
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. """Detect target.""" def _detect_metal(dev: Device) -> Target: return Target( { "kind": "metal", "max_shared_memory_per_block": 32768, "max_threads_per_block": dev.max_threads_per_block, "thread_warp_size": dev.warp_size, } ) def _detect_cuda(dev: Device) -> Target: return Target( { "kind": "cuda", "max_shared_memory_per_block": dev.max_shared_memory_per_block, "max_threads_per_block": dev.max_threads_per_block, "thread_warp_size": dev.warp_size, "arch": "sm_" + dev.compute_version.replace(".", ""), } ) def _detect_rocm(dev: Device) -> Target: return Target( { "kind": "rocm", "mtriple": "amdgcn-and-amdhsa-hcc", "max_shared_memory_per_block": dev.max_shared_memory_per_block, "max_threads_per_block": dev.max_threads_per_block, "thread_warp_size": dev.warp_size, } ) def _detect_vulkan(dev: Device) -> Target:
f_get_target_property = get_global_func("device_api.vulkan.get_target_property")
1
2023-12-14 02:37:47+00:00
12k