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
edong6768/Malet
src/malet/plot.py
[ { "identifier": "Experiment", "path": "src/malet/experiment.py", "snippet": "class Experiment:\n '''\n Executes experiments according to experiment configs\n \n Following is supported\n - Provides 2 methods parallel friedly experiments scheduling (can choose with bash arguments).\n - (plan split...
import os import re import yaml import matplotlib.pyplot as plt import matplotlib.style as style import seaborn as sns from functools import partial from itertools import product from absl import app, flags from ml_collections import ConfigDict from .experiment import Experiment, ExperimentLog from .utils import str2value, df2richtable from rich import print from rich.panel import Panel from rich.columns import Columns from rich.align import Align from .plot_utils.metric_drawer import * from .plot_utils.utils import *
6,655
FLAGS = flags.FLAGS def get_plot_config(plot_config: dict, plot_args: dict): assert plot_args['mode'] in plot_config, f'Mode: {plot_args["mode"]} does not exist.' alias_mode = ('-' not in plot_args['mode']) p_cfg = plot_config[plot_args['mode']] if alias_mode: p_cfg_base = plot_config.get(p_cfg['mode'], dict()) p_cfg_base = merge_dict(p_cfg_base, plot_args) p_cfg_base = merge_dict(p_cfg_base, plot_config['default_style']) return merge_dict(p_cfg, p_cfg_base) else: return {**plot_args, **p_cfg} def draw_metric(tsv_file, plot_config, save_name='', preprcs_df=lambda *x: x): pcfg = plot_config # parse mode string mode, x_fields, metric = pcfg['mode'].split('-') # ex) {sam}-{epoch}-{train_loss} x_fields = x_fields.split(' ') pflt, pmlf = map(pcfg.get, ['filter', 'multi_line_fields']) # choose plot mode if mode=='curve': assert len(x_fields)==1, f'Number of x_fields shoud be 1 when using curve mode, but you passed {len(x_fields)}.' ax_draw = ax_draw_curve y_label = metric.replace('_', ' ').capitalize() elif mode=='bar': assert len(x_fields)==1, f'Number of x_fields shoud be 1 when using bar mode, but you passed {len(x_fields)}.' ax_draw = ax_draw_bar y_label = metric.replace('_', ' ').capitalize() elif mode=='heatmap': assert len(x_fields)==2, f'Number of x_fields shoud be 2 when using heatmap mode, but you passed {len(x_fields)}.' assert not pmlf, f'No multi_line_fieldss are allowed in heatmap mode, but you passed {len(x_fields)}.' ax_draw = ax_draw_heatmap y_label = x_fields[1].replace('_', ' ').capitalize() # get dataframe, drop unused metrics for efficient process pai_history = ExperimentLog.from_tsv(tsv_file) if 'metric' not in pmlf and 'metric' not in x_fields: pai_history.df = pai_history.df.drop(list(set(pai_history.df)-{metric, pcfg['best_ref_metric_field']}), axis=1) df = pai_history.explode_and_melt_metric(epoch=None if 'epoch' not in x_fields else -1) base_config = ConfigDict(pai_history.static_configs) #---filter df according to FLAGS.filter if pflt: save_name += pflt.replace(' / ', '-').replace(' ', '_') filt_dict = map(lambda flt: re.split('(?<!,) ', flt.strip()), pflt.split('/')) # split ' ' except ', '
FLAGS = flags.FLAGS def get_plot_config(plot_config: dict, plot_args: dict): assert plot_args['mode'] in plot_config, f'Mode: {plot_args["mode"]} does not exist.' alias_mode = ('-' not in plot_args['mode']) p_cfg = plot_config[plot_args['mode']] if alias_mode: p_cfg_base = plot_config.get(p_cfg['mode'], dict()) p_cfg_base = merge_dict(p_cfg_base, plot_args) p_cfg_base = merge_dict(p_cfg_base, plot_config['default_style']) return merge_dict(p_cfg, p_cfg_base) else: return {**plot_args, **p_cfg} def draw_metric(tsv_file, plot_config, save_name='', preprcs_df=lambda *x: x): pcfg = plot_config # parse mode string mode, x_fields, metric = pcfg['mode'].split('-') # ex) {sam}-{epoch}-{train_loss} x_fields = x_fields.split(' ') pflt, pmlf = map(pcfg.get, ['filter', 'multi_line_fields']) # choose plot mode if mode=='curve': assert len(x_fields)==1, f'Number of x_fields shoud be 1 when using curve mode, but you passed {len(x_fields)}.' ax_draw = ax_draw_curve y_label = metric.replace('_', ' ').capitalize() elif mode=='bar': assert len(x_fields)==1, f'Number of x_fields shoud be 1 when using bar mode, but you passed {len(x_fields)}.' ax_draw = ax_draw_bar y_label = metric.replace('_', ' ').capitalize() elif mode=='heatmap': assert len(x_fields)==2, f'Number of x_fields shoud be 2 when using heatmap mode, but you passed {len(x_fields)}.' assert not pmlf, f'No multi_line_fieldss are allowed in heatmap mode, but you passed {len(x_fields)}.' ax_draw = ax_draw_heatmap y_label = x_fields[1].replace('_', ' ').capitalize() # get dataframe, drop unused metrics for efficient process pai_history = ExperimentLog.from_tsv(tsv_file) if 'metric' not in pmlf and 'metric' not in x_fields: pai_history.df = pai_history.df.drop(list(set(pai_history.df)-{metric, pcfg['best_ref_metric_field']}), axis=1) df = pai_history.explode_and_melt_metric(epoch=None if 'epoch' not in x_fields else -1) base_config = ConfigDict(pai_history.static_configs) #---filter df according to FLAGS.filter if pflt: save_name += pflt.replace(' / ', '-').replace(' ', '_') filt_dict = map(lambda flt: re.split('(?<!,) ', flt.strip()), pflt.split('/')) # split ' ' except ', '
df = select_df(df, {fk:[*map(str2value, fvs)] for fk, *fvs in filt_dict})
2
2023-10-08 22:29:59+00:00
8k
ThomasMrY/DisDiff
ldm/modules/diffusionmodules/openaimodel.py
[ { "identifier": "checkpoint", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def checkpoint(func, inputs, params, flag):\n \"\"\"\n Evaluate a function without caching intermediate activations, allowing for\n reduced memory at the expense of extra compute in the backward pass.\n ...
from abc import abstractmethod from functools import partial from typing import Iterable from ldm.modules.diffusionmodules.util import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_module, normalization, timestep_embedding, ) from ldm.modules.attention import SpatialTransformer from .util import Return from omegaconf.listconfig import ListConfig import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F
3,748
use_scale_shift_norm=use_scale_shift_norm, ), AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim ), ResBlock( ch, time_embed_dim, dropout, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ), ) self._feature_size += ch self.output_blocks = nn.ModuleList([]) for level, mult in list(enumerate(channel_mult))[::-1]: for i in range(num_res_blocks + 1): ich = input_block_chans.pop() layers = [ ResBlock( ch + ich, time_embed_dim, dropout, out_channels=model_channels * mult, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = model_channels * mult if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels layers.append( AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads_upsample, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim ) ) if level and i == num_res_blocks: out_ch = ch layers.append( ResBlock( ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, up=True, ) if resblock_updown else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) ) ds //= 2 self.output_blocks.append(TimestepEmbedSequential(*layers)) self._feature_size += ch self.out = nn.Sequential( normalization(ch), nn.SiLU(), zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)), ) if self.predict_codebook_ids: self.id_predictor = nn.Sequential( normalization(ch), conv_nd(dims, model_channels, n_embed, 1), #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits ) def convert_to_fp16(self): """ Convert the torso of the model to float16. """ self.input_blocks.apply(convert_module_to_f16) self.middle_block.apply(convert_module_to_f16) self.output_blocks.apply(convert_module_to_f16) def convert_to_fp32(self): """ Convert the torso of the model to float32. """ self.input_blocks.apply(convert_module_to_f32) self.middle_block.apply(convert_module_to_f32) self.output_blocks.apply(convert_module_to_f32) def forward(self, x, timesteps=None, context=None, y=None,**kwargs): """ Apply the model to an input batch. :param x: an [N x C x ...] Tensor of inputs. :param timesteps: a 1-D batch of timesteps. :param context: conditioning plugged in via crossattn :param y: an [N] Tensor of labels, if class-conditional. :return: an [N x C x ...] Tensor of outputs. """ # context = None assert (y is not None) == ( self.num_classes is not None ), "must specify y if and only if the model is class-conditional" hs = []
# dummy replace def convert_module_to_f16(x): pass def convert_module_to_f32(x): pass ## go class AttentionPool2d(nn.Module): """ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py """ def __init__( self, spacial_dim: int, embed_dim: int, num_heads_channels: int, output_dim: int = None, ): super().__init__() self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5) self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1) self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1) self.num_heads = embed_dim // num_heads_channels self.attention = QKVAttention(self.num_heads) def forward(self, x): b, c, *_spatial = x.shape x = x.reshape(b, c, -1) # NC(HW) x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1) x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1) x = self.qkv_proj(x) x = self.attention(x) x = self.c_proj(x) return x[:, :, 0] class TimestepBlock(nn.Module): """ Any module where forward() takes timestep embeddings as a second argument. """ @abstractmethod def forward(self, x, emb): """ Apply the module to `x` given `emb` timestep embeddings. """ class TimestepEmbedSequential(nn.Sequential, TimestepBlock): """ A sequential module that passes timestep embeddings to the children that support it as an extra input. """ def forward(self, x, emb, context=None): for layer in self: if isinstance(layer, TimestepBlock): x = layer(x, emb) elif isinstance(layer, SpatialTransformer): x = layer(x, context) else: x = layer(x) return x class Upsample(nn.Module): """ An upsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then upsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims if use_conv: self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding) def forward(self, x): assert x.shape[1] == self.channels if self.dims == 3: x = F.interpolate( x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest" ) else: x = F.interpolate(x, scale_factor=2, mode="nearest") if self.use_conv: x = self.conv(x) return x class TransposedUpsample(nn.Module): 'Learned 2x upsampling without padding' def __init__(self, channels, out_channels=None, ks=5): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2) def forward(self,x): return self.up(x) class Downsample(nn.Module): """ A downsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then downsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims stride = 2 if dims != 3 else (1, 2, 2) if use_conv: self.op = conv_nd( dims, self.channels, self.out_channels, 3, stride=stride, padding=padding ) else: assert self.channels == self.out_channels self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) def forward(self, x): assert x.shape[1] == self.channels return self.op(x) class ResBlock(TimestepBlock): """ A residual block that can optionally change the number of channels. :param channels: the number of input channels. :param emb_channels: the number of timestep embedding channels. :param dropout: the rate of dropout. :param out_channels: if specified, the number of out channels. :param use_conv: if True and out_channels is specified, use a spatial convolution instead of a smaller 1x1 convolution to change the channels in the skip connection. :param dims: determines if the signal is 1D, 2D, or 3D. :param use_checkpoint: if True, use gradient checkpointing on this module. :param up: if True, use this block for upsampling. :param down: if True, use this block for downsampling. """ def __init__( self, channels, emb_channels, dropout, out_channels=None, use_conv=False, use_scale_shift_norm=False, dims=2, use_checkpoint=False, up=False, down=False, ): super().__init__() self.channels = channels self.emb_channels = emb_channels self.dropout = dropout self.out_channels = out_channels or channels self.use_conv = use_conv self.use_checkpoint = use_checkpoint self.use_scale_shift_norm = use_scale_shift_norm self.in_layers = nn.Sequential( normalization(channels), nn.SiLU(), conv_nd(dims, channels, self.out_channels, 3, padding=1), ) self.updown = up or down if up: self.h_upd = Upsample(channels, False, dims) self.x_upd = Upsample(channels, False, dims) elif down: self.h_upd = Downsample(channels, False, dims) self.x_upd = Downsample(channels, False, dims) else: self.h_upd = self.x_upd = nn.Identity() self.emb_layers = nn.Sequential( nn.SiLU(), linear( emb_channels, 2 * self.out_channels if use_scale_shift_norm else self.out_channels, ), ) self.out_layers = nn.Sequential( normalization(self.out_channels), nn.SiLU(), nn.Dropout(p=dropout), zero_module( conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1) ), ) if self.out_channels == channels: self.skip_connection = nn.Identity() elif use_conv: self.skip_connection = conv_nd( dims, channels, self.out_channels, 3, padding=1 ) else: self.skip_connection = conv_nd(dims, channels, self.out_channels, 1) def forward(self, x, emb): """ Apply the block to a Tensor, conditioned on a timestep embedding. :param x: an [N x C x ...] Tensor of features. :param emb: an [N x emb_channels] Tensor of timestep embeddings. :return: an [N x C x ...] Tensor of outputs. """ return checkpoint( self._forward, (x, emb), self.parameters(), self.use_checkpoint ) def _forward(self, x, emb): if self.updown: in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] h = in_rest(x) h = self.h_upd(h) x = self.x_upd(x) h = in_conv(h) else: h = self.in_layers(x) emb_out = self.emb_layers(emb).type(h.dtype) while len(emb_out.shape) < len(h.shape): emb_out = emb_out[..., None] if self.use_scale_shift_norm: out_norm, out_rest = self.out_layers[0], self.out_layers[1:] scale, shift = th.chunk(emb_out, 2, dim=1) h = out_norm(h) * (1 + scale) + shift h = out_rest(h) else: h = h + emb_out h = self.out_layers(h) return self.skip_connection(x) + h class AttentionBlock(nn.Module): """ An attention block that allows spatial positions to attend to each other. Originally ported from here, but adapted to the N-d case. https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66. """ def __init__( self, channels, num_heads=1, num_head_channels=-1, use_checkpoint=False, use_new_attention_order=False, ): super().__init__() self.channels = channels if num_head_channels == -1: self.num_heads = num_heads else: assert ( channels % num_head_channels == 0 ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" self.num_heads = channels // num_head_channels self.use_checkpoint = use_checkpoint self.norm = normalization(channels) self.qkv = conv_nd(1, channels, channels * 3, 1) if use_new_attention_order: # split qkv before split heads self.attention = QKVAttention(self.num_heads) else: # split heads before split qkv self.attention = QKVAttentionLegacy(self.num_heads) self.proj_out = zero_module(conv_nd(1, channels, channels, 1)) def forward(self, x): return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!! #return pt_checkpoint(self._forward, x) # pytorch def _forward(self, x): b, c, *spatial = x.shape x = x.reshape(b, c, -1) qkv = self.qkv(self.norm(x)) h = self.attention(qkv) h = self.proj_out(h) return (x + h).reshape(b, c, *spatial) def count_flops_attn(model, _x, y): """ A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, ) """ b, c, *spatial = y[0].shape num_spatial = int(np.prod(spatial)) # We perform two matmuls with the same number of ops. # The first computes the weight matrix, the second computes # the combination of the value vectors. matmul_ops = 2 * b * (num_spatial ** 2) * c model.total_ops += th.DoubleTensor([matmul_ops]) class QKVAttentionLegacy(nn.Module): """ A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping """ def __init__(self, n_heads): super().__init__() self.n_heads = n_heads def forward(self, qkv): """ Apply QKV attention. :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention. """ bs, width, length = qkv.shape assert width % (3 * self.n_heads) == 0 ch = width // (3 * self.n_heads) q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) scale = 1 / math.sqrt(math.sqrt(ch)) weight = th.einsum( "bct,bcs->bts", q * scale, k * scale ) # More stable with f16 than dividing afterwards weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) a = th.einsum("bts,bcs->bct", weight, v) return a.reshape(bs, -1, length) @staticmethod def count_flops(model, _x, y): return count_flops_attn(model, _x, y) class QKVAttention(nn.Module): """ A module which performs QKV attention and splits in a different order. """ def __init__(self, n_heads): super().__init__() self.n_heads = n_heads def forward(self, qkv): """ Apply QKV attention. :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention. """ bs, width, length = qkv.shape assert width % (3 * self.n_heads) == 0 ch = width // (3 * self.n_heads) q, k, v = qkv.chunk(3, dim=1) scale = 1 / math.sqrt(math.sqrt(ch)) weight = th.einsum( "bct,bcs->bts", (q * scale).view(bs * self.n_heads, ch, length), (k * scale).view(bs * self.n_heads, ch, length), ) # More stable with f16 than dividing afterwards weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length)) return a.reshape(bs, -1, length) @staticmethod def count_flops(model, _x, y): return count_flops_attn(model, _x, y) class UNetModel(nn.Module): """ The full UNet model with attention and timestep embedding. :param in_channels: channels in the input Tensor. :param model_channels: base channel count for the model. :param out_channels: channels in the output Tensor. :param num_res_blocks: number of residual blocks per downsample. :param attention_resolutions: a collection of downsample rates at which attention will take place. May be a set, list, or tuple. For example, if this contains 4, then at 4x downsampling, attention will be used. :param dropout: the dropout probability. :param channel_mult: channel multiplier for each level of the UNet. :param conv_resample: if True, use learned convolutions for upsampling and downsampling. :param dims: determines if the signal is 1D, 2D, or 3D. :param num_classes: if specified (as an int), then this model will be class-conditional with `num_classes` classes. :param use_checkpoint: use gradient checkpointing to reduce memory usage. :param num_heads: the number of attention heads in each attention layer. :param num_heads_channels: if specified, ignore num_heads and instead use a fixed channel width per attention head. :param num_heads_upsample: works with num_heads to set a different number of heads for upsampling. Deprecated. :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. :param resblock_updown: use residual blocks for up/downsampling. :param use_new_attention_order: use a different attention pattern for potentially increased efficiency. """ def __init__( self, image_size, in_channels, model_channels, out_channels, num_res_blocks, attention_resolutions, dropout=0, channel_mult=(1, 2, 4, 8), conv_resample=True, dims=2, num_classes=None, use_checkpoint=False, use_fp16=False, num_heads=-1, num_head_channels=-1, num_heads_upsample=-1, use_scale_shift_norm=False, resblock_updown=False, use_new_attention_order=False, use_spatial_transformer=False, # custom transformer support transformer_depth=1, # custom transformer support context_dim=None, # custom transformer support n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model legacy=True, ): super().__init__() if use_spatial_transformer: assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...' if context_dim is not None: assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...' if type(context_dim) == ListConfig: context_dim = list(context_dim) if num_heads_upsample == -1: num_heads_upsample = num_heads if num_heads == -1: assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' if num_head_channels == -1: assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' self.image_size = image_size self.in_channels = in_channels self.model_channels = model_channels self.out_channels = out_channels self.num_res_blocks = num_res_blocks self.attention_resolutions = attention_resolutions self.dropout = dropout self.channel_mult = channel_mult self.conv_resample = conv_resample self.num_classes = num_classes self.use_checkpoint = use_checkpoint self.dtype = th.float16 if use_fp16 else th.float32 self.num_heads = num_heads self.num_head_channels = num_head_channels self.num_heads_upsample = num_heads_upsample self.predict_codebook_ids = n_embed is not None time_embed_dim = model_channels * 4 self.time_embed = nn.Sequential( linear(model_channels, time_embed_dim), nn.SiLU(), linear(time_embed_dim, time_embed_dim), ) if self.num_classes is not None: self.label_emb = nn.Embedding(num_classes, time_embed_dim) self.input_blocks = nn.ModuleList( [ TimestepEmbedSequential( conv_nd(dims, in_channels, model_channels, 3, padding=1) ) ] ) self._feature_size = model_channels input_block_chans = [model_channels] ch = model_channels ds = 1 for level, mult in enumerate(channel_mult): for _ in range(num_res_blocks): layers = [ ResBlock( ch, time_embed_dim, dropout, out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = mult * model_channels if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels layers.append( AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim ) ) self.input_blocks.append(TimestepEmbedSequential(*layers)) self._feature_size += ch input_block_chans.append(ch) if level != len(channel_mult) - 1: out_ch = ch self.input_blocks.append( TimestepEmbedSequential( ResBlock( ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, down=True, ) if resblock_updown else Downsample( ch, conv_resample, dims=dims, out_channels=out_ch ) ) ) ch = out_ch input_block_chans.append(ch) ds *= 2 self._feature_size += ch if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels self.middle_block = TimestepEmbedSequential( ResBlock( ch, time_embed_dim, dropout, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ), AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim ), ResBlock( ch, time_embed_dim, dropout, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ), ) self._feature_size += ch self.output_blocks = nn.ModuleList([]) for level, mult in list(enumerate(channel_mult))[::-1]: for i in range(num_res_blocks + 1): ich = input_block_chans.pop() layers = [ ResBlock( ch + ich, time_embed_dim, dropout, out_channels=model_channels * mult, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = model_channels * mult if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels layers.append( AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads_upsample, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim ) ) if level and i == num_res_blocks: out_ch = ch layers.append( ResBlock( ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, up=True, ) if resblock_updown else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) ) ds //= 2 self.output_blocks.append(TimestepEmbedSequential(*layers)) self._feature_size += ch self.out = nn.Sequential( normalization(ch), nn.SiLU(), zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)), ) if self.predict_codebook_ids: self.id_predictor = nn.Sequential( normalization(ch), conv_nd(dims, model_channels, n_embed, 1), #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits ) def convert_to_fp16(self): """ Convert the torso of the model to float16. """ self.input_blocks.apply(convert_module_to_f16) self.middle_block.apply(convert_module_to_f16) self.output_blocks.apply(convert_module_to_f16) def convert_to_fp32(self): """ Convert the torso of the model to float32. """ self.input_blocks.apply(convert_module_to_f32) self.middle_block.apply(convert_module_to_f32) self.output_blocks.apply(convert_module_to_f32) def forward(self, x, timesteps=None, context=None, y=None,**kwargs): """ Apply the model to an input batch. :param x: an [N x C x ...] Tensor of inputs. :param timesteps: a 1-D batch of timesteps. :param context: conditioning plugged in via crossattn :param y: an [N] Tensor of labels, if class-conditional. :return: an [N x C x ...] Tensor of outputs. """ # context = None assert (y is not None) == ( self.num_classes is not None ), "must specify y if and only if the model is class-conditional" hs = []
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
6
2023-10-07 09:58:07+00:00
8k
WooJin-Cho/Hyper-LR-PINN
train_full.py
[ { "identifier": "get_config", "path": "config.py", "snippet": "def get_config():\n return parser.parse_args()" }, { "identifier": "LR_PINN_phase1", "path": "model.py", "snippet": "class LR_PINN_phase1(nn.Module):\n def __init__(self, hidden_dim):\n super(LR_PINN_phase1, self...
import torch import torch.nn as nn import numpy as np import torch import random import torch.backends.cudnn as cudnn import pandas as pd import os from torch.autograd import Variable from config import get_config from model import LR_PINN_phase1, LR_PINN_phase2 from utils import orthogonality_reg, f_cal_phase2, get_params from sklearn.metrics import explained_variance_score, max_error
3,853
test_data = pd.read_csv(f'./data_gen/dataset/{pde_type}/test/test_{target_coeff_1}_{pde_type}.csv') ###################################################### target_coeff_1 = torch.tensor(target_coeff_1).unsqueeze(dim=0) target_coeff_1 = target_coeff_1.type(torch.float) target_coeff_2 = torch.tensor(target_coeff_2).unsqueeze(dim=0) target_coeff_2 = target_coeff_2.type(torch.float) target_coeff_3 = torch.tensor(target_coeff_3).unsqueeze(dim=0) target_coeff_3 = target_coeff_3.type(torch.float) mse_cost_function = torch.nn.MSELoss() # Mean squared error ############### Network Initialization ################ net_initial = LR_PINN_phase1(hidden_dim) net_initial.load_state_dict(torch.load(f'./param/phase1/{pde_type}/{initial_condition}/PINN_{start_coeff_1}_{end_coeff_1}_20000.pt')) tanh = nn.Tanh() relu = nn.ReLU() start_w = net_initial.state_dict()['start_layer.weight'] start_b = net_initial.state_dict()['start_layer.bias'] end_w = net_initial.state_dict()['end_layer.weight'] end_b = net_initial.state_dict()['end_layer.bias'] col_0 = net_initial.state_dict()['col_basis_0'] col_1 = net_initial.state_dict()['col_basis_1'] col_2 = net_initial.state_dict()['col_basis_2'] row_0 = net_initial.state_dict()['row_basis_0'] row_1 = net_initial.state_dict()['row_basis_1'] row_2 = net_initial.state_dict()['row_basis_2'] meta_layer_1_w = net_initial.state_dict()['meta_layer_1.weight'] meta_layer_1_b = net_initial.state_dict()['meta_layer_1.bias'] meta_layer_2_w = net_initial.state_dict()['meta_layer_2.weight'] meta_layer_2_b = net_initial.state_dict()['meta_layer_2.bias'] meta_layer_3_w = net_initial.state_dict()['meta_layer_3.weight'] meta_layer_3_b = net_initial.state_dict()['meta_layer_3.bias'] meta_alpha_0_w = net_initial.state_dict()['meta_alpha_0.weight'] meta_alpha_0_b = net_initial.state_dict()['meta_alpha_0.bias'] meta_alpha_1_w = net_initial.state_dict()['meta_alpha_1.weight'] meta_alpha_1_b = net_initial.state_dict()['meta_alpha_1.bias'] meta_alpha_2_w = net_initial.state_dict()['meta_alpha_2.weight'] meta_alpha_2_b = net_initial.state_dict()['meta_alpha_2.bias'] target_coeff = torch.cat([target_coeff_1, target_coeff_2, target_coeff_3], dim=0) meta_vector = torch.matmul(target_coeff, meta_layer_1_w.T) + meta_layer_1_b meta_vector = tanh(meta_vector) meta_vector = torch.matmul(meta_vector, meta_layer_2_w.T) + meta_layer_2_b meta_vector = tanh(meta_vector) meta_vector = torch.matmul(meta_vector, meta_layer_3_w.T) + meta_layer_3_b meta_vector = tanh(meta_vector) alpha_0 = relu(torch.matmul(meta_vector, meta_alpha_0_w.T) + meta_alpha_0_b) alpha_1 = relu(torch.matmul(meta_vector, meta_alpha_1_w.T) + meta_alpha_1_b) alpha_2 = relu(torch.matmul(meta_vector, meta_alpha_2_w.T) + meta_alpha_2_b) ######################################################## net = LR_PINN_phase2(hidden_dim, start_w, start_b, end_w, end_b, col_0, col_1, col_2, row_0, row_1, row_2, alpha_0, alpha_1, alpha_2) net = net.to(device) model_size = get_params(net) print(model_size) optimizer = torch.optim.Adam(net.parameters(), lr=0.00025) x_collocation = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_f['x_data'], 1))).float(), requires_grad=True).to(device) t_collocation = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_f['t_data'], 1))).float(), requires_grad=True).to(device) beta_collocation = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_f['beta'], 1))).float(), requires_grad=True).to(device) nu_collocation = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_f['nu'], 1))).float(), requires_grad=True).to(device) rho_collocation = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_f['rho'], 1))).float(), requires_grad=True).to(device) all_zeros = np.zeros((len(train_data_f), 1)) all_zeros = Variable(torch.from_numpy(all_zeros).float(), requires_grad=False).to(device) # initial points x_initial = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_u['x_data'], 1))).float(), requires_grad=True).to(device) t_initial = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_u['t_data'], 1))).float(), requires_grad=True).to(device) u_initial = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_u['u_data'], 1))).float(), requires_grad=True).to(device) # boundary points (condition : upper bound = lower bound) x_lb = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_bd['x_data_lb'], 1))).float(), requires_grad=True).to(device) t_lb = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_bd['t_data_lb'], 1))).float(), requires_grad=True).to(device) x_ub = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_bd['x_data_ub'], 1))).float(), requires_grad=True).to(device) t_ub = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_bd['t_data_ub'], 1))).float(), requires_grad=True).to(device) # test point x_test = Variable(torch.from_numpy(np.array(np.expand_dims(test_data['x_data'], 1))).float(), requires_grad=False).to(device) t_test = Variable(torch.from_numpy(np.array(np.expand_dims(test_data['t_data'], 1))).float(), requires_grad=False).to(device) u_test = Variable(torch.from_numpy(np.array(np.expand_dims(test_data['u_data'], 1))).float(), requires_grad=False).to(device) err_list = [] ep_list = [] loss_list= [] mse_loss_list = [] mse_u_list = [] mse_f_list = [] mse_bd_list = [] L2_abs_list = [] L2_rel_list = [] Max_err_list = [] Ex_var_score_list = [] for ep in range(1, epoch+1): net.train() optimizer.zero_grad() net_initial_out = net(x_initial, t_initial) mse_u = mse_cost_function(net_initial_out, u_initial)
args = get_config() device = torch.device(args.device) def main(): args = get_config() torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed) np.random.seed(args.seed) cudnn.benchmark = False cudnn.deterministic = True random.seed(args.seed) device = torch.device(args.device) print("========================================") print("Use Device :", device) print("Available cuda devices :", torch.cuda.device_count()) print("Current cuda device :", torch.cuda.current_device()) print("Name of cuda device :", torch.cuda.get_device_name(device)) print("========================================") hidden_dim = 50 epoch = args.epoch pde_type = args.pde_type initial_condition = args.init_cond start_coeff_1 = args.start_coeff_1 end_coeff_1 = args.end_coeff_1 target_coeff_1 = args.target_coeff_1 target_coeff_2 = args.target_coeff_2 target_coeff_3 = args.target_coeff_3 ###################### Dataset ####################### train_data_f = pd.read_csv(f'./data_gen/dataset/{pde_type}/train/train_f_{target_coeff_1}_{pde_type}.csv') train_data_u = pd.read_csv(f'./data_gen/dataset/{pde_type}/train/train_u_{target_coeff_1}_{pde_type}.csv') train_data_bd = pd.read_csv(f'./data_gen/dataset/{pde_type}/train/train_boundary_{target_coeff_1}_{pde_type}.csv') test_data = pd.read_csv(f'./data_gen/dataset/{pde_type}/test/test_{target_coeff_1}_{pde_type}.csv') ###################################################### target_coeff_1 = torch.tensor(target_coeff_1).unsqueeze(dim=0) target_coeff_1 = target_coeff_1.type(torch.float) target_coeff_2 = torch.tensor(target_coeff_2).unsqueeze(dim=0) target_coeff_2 = target_coeff_2.type(torch.float) target_coeff_3 = torch.tensor(target_coeff_3).unsqueeze(dim=0) target_coeff_3 = target_coeff_3.type(torch.float) mse_cost_function = torch.nn.MSELoss() # Mean squared error ############### Network Initialization ################ net_initial = LR_PINN_phase1(hidden_dim) net_initial.load_state_dict(torch.load(f'./param/phase1/{pde_type}/{initial_condition}/PINN_{start_coeff_1}_{end_coeff_1}_20000.pt')) tanh = nn.Tanh() relu = nn.ReLU() start_w = net_initial.state_dict()['start_layer.weight'] start_b = net_initial.state_dict()['start_layer.bias'] end_w = net_initial.state_dict()['end_layer.weight'] end_b = net_initial.state_dict()['end_layer.bias'] col_0 = net_initial.state_dict()['col_basis_0'] col_1 = net_initial.state_dict()['col_basis_1'] col_2 = net_initial.state_dict()['col_basis_2'] row_0 = net_initial.state_dict()['row_basis_0'] row_1 = net_initial.state_dict()['row_basis_1'] row_2 = net_initial.state_dict()['row_basis_2'] meta_layer_1_w = net_initial.state_dict()['meta_layer_1.weight'] meta_layer_1_b = net_initial.state_dict()['meta_layer_1.bias'] meta_layer_2_w = net_initial.state_dict()['meta_layer_2.weight'] meta_layer_2_b = net_initial.state_dict()['meta_layer_2.bias'] meta_layer_3_w = net_initial.state_dict()['meta_layer_3.weight'] meta_layer_3_b = net_initial.state_dict()['meta_layer_3.bias'] meta_alpha_0_w = net_initial.state_dict()['meta_alpha_0.weight'] meta_alpha_0_b = net_initial.state_dict()['meta_alpha_0.bias'] meta_alpha_1_w = net_initial.state_dict()['meta_alpha_1.weight'] meta_alpha_1_b = net_initial.state_dict()['meta_alpha_1.bias'] meta_alpha_2_w = net_initial.state_dict()['meta_alpha_2.weight'] meta_alpha_2_b = net_initial.state_dict()['meta_alpha_2.bias'] target_coeff = torch.cat([target_coeff_1, target_coeff_2, target_coeff_3], dim=0) meta_vector = torch.matmul(target_coeff, meta_layer_1_w.T) + meta_layer_1_b meta_vector = tanh(meta_vector) meta_vector = torch.matmul(meta_vector, meta_layer_2_w.T) + meta_layer_2_b meta_vector = tanh(meta_vector) meta_vector = torch.matmul(meta_vector, meta_layer_3_w.T) + meta_layer_3_b meta_vector = tanh(meta_vector) alpha_0 = relu(torch.matmul(meta_vector, meta_alpha_0_w.T) + meta_alpha_0_b) alpha_1 = relu(torch.matmul(meta_vector, meta_alpha_1_w.T) + meta_alpha_1_b) alpha_2 = relu(torch.matmul(meta_vector, meta_alpha_2_w.T) + meta_alpha_2_b) ######################################################## net = LR_PINN_phase2(hidden_dim, start_w, start_b, end_w, end_b, col_0, col_1, col_2, row_0, row_1, row_2, alpha_0, alpha_1, alpha_2) net = net.to(device) model_size = get_params(net) print(model_size) optimizer = torch.optim.Adam(net.parameters(), lr=0.00025) x_collocation = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_f['x_data'], 1))).float(), requires_grad=True).to(device) t_collocation = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_f['t_data'], 1))).float(), requires_grad=True).to(device) beta_collocation = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_f['beta'], 1))).float(), requires_grad=True).to(device) nu_collocation = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_f['nu'], 1))).float(), requires_grad=True).to(device) rho_collocation = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_f['rho'], 1))).float(), requires_grad=True).to(device) all_zeros = np.zeros((len(train_data_f), 1)) all_zeros = Variable(torch.from_numpy(all_zeros).float(), requires_grad=False).to(device) # initial points x_initial = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_u['x_data'], 1))).float(), requires_grad=True).to(device) t_initial = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_u['t_data'], 1))).float(), requires_grad=True).to(device) u_initial = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_u['u_data'], 1))).float(), requires_grad=True).to(device) # boundary points (condition : upper bound = lower bound) x_lb = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_bd['x_data_lb'], 1))).float(), requires_grad=True).to(device) t_lb = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_bd['t_data_lb'], 1))).float(), requires_grad=True).to(device) x_ub = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_bd['x_data_ub'], 1))).float(), requires_grad=True).to(device) t_ub = Variable(torch.from_numpy(np.array(np.expand_dims(train_data_bd['t_data_ub'], 1))).float(), requires_grad=True).to(device) # test point x_test = Variable(torch.from_numpy(np.array(np.expand_dims(test_data['x_data'], 1))).float(), requires_grad=False).to(device) t_test = Variable(torch.from_numpy(np.array(np.expand_dims(test_data['t_data'], 1))).float(), requires_grad=False).to(device) u_test = Variable(torch.from_numpy(np.array(np.expand_dims(test_data['u_data'], 1))).float(), requires_grad=False).to(device) err_list = [] ep_list = [] loss_list= [] mse_loss_list = [] mse_u_list = [] mse_f_list = [] mse_bd_list = [] L2_abs_list = [] L2_rel_list = [] Max_err_list = [] Ex_var_score_list = [] for ep in range(1, epoch+1): net.train() optimizer.zero_grad() net_initial_out = net(x_initial, t_initial) mse_u = mse_cost_function(net_initial_out, u_initial)
f_out = f_cal_phase2(x_collocation, t_collocation, beta_collocation, nu_collocation, rho_collocation, net)
4
2023-10-14 09:06:18+00:00
8k
StareAbyss/FoodsVsMouses_AutoAssistant
function/script/service/common.py
[ { "identifier": "key_down_up", "path": "function/common/bg_keyboard.py", "snippet": "def key_down_up(handle: HWND, key: str, interval_time: float = 0.05, sleep_time: float = 0.05):\r\n key_down(handle, key)\r\n sleep(interval_time)\r\n key_up(handle, key)\r\n sleep(sleep_time)\r" }, { ...
import copy import json import os import time import numpy as np from cv2 import imread, vconcat, imwrite from function.common.bg_keyboard import key_down_up from function.common.bg_mouse import mouse_left_click, mouse_left_moveto from function.common.bg_p_compare import find_p_in_w, loop_find_p_in_w, loop_find_ps_in_w, find_ps_in_w from function.common.bg_p_screenshot import capture_picture_png from function.get_paths import paths from function.script.scattered.gat_handle import faa_get_handle from function.script.scattered.get_list_battle_plan import get_list_battle_plan from function.script.scattered.get_list_card_battle import get_list_card_battle from function.script.scattered.get_list_card_room import get_list_card_room from function.script.scattered.print_grade import print_g from function.script.scattered.read_json_to_stage_info import read_json_to_stage_info from function.tools.create_battle_coordinates import create_battle_coordinates
7,109
class FAA: def __init__(self, channel="锑食", zoom=1.0, player="1P", character_level=1, is_use_key=True, is_auto_battle=True, is_auto_pickup=False): # 获取窗口句柄 self.channel = channel
class FAA: def __init__(self, channel="锑食", zoom=1.0, player="1P", character_level=1, is_use_key=True, is_auto_battle=True, is_auto_pickup=False): # 获取窗口句柄 self.channel = channel
self.handle = faa_get_handle(channel=self.channel, mode="flash")
9
2023-10-12 20:33:39+00:00
8k
dalao-org/oneinstack-mirror-generator
main.py
[ { "identifier": "curl", "path": "utils/curl.py", "snippet": "def make_cache() -> tuple[list[dict[str, str | Any]], dict[str, str | Any]]:" }, { "identifier": "fail2ban", "path": "utils/fail2ban.py", "snippet": "def make_cache() -> list:" }, { "identifier": "mysql", "path": "u...
from utils import (curl, fail2ban, mysql, nginx, php, phpmyadmin, redis, cacert, acme_sh, nghttp2, postgresql, python, httpd, apr, imagemagick, openresty, memcached, lua_nginx_module, php_plugins, pip, tengine, xcache, boost, github, pure_ftpd, htop, misc, freetype, libiconv, bison, openssl, php_patches) from base_logger import logger import json import os import datetime
3,789
# gdrive package is changed!!! resource_list += github.get_package_from_release_with_regular_expression("glotlabs", "gdrive", r"linux", 1, None)[0] libzip_output = github.get_package_from_release_with_regular_expression("nih-at", "libzip", r"\.tar\.gz", 5, "libzip_ver") resource_list += libzip_output[0] latest_meta_list.append(libzip_output[1]) libsodium_output = github.get_package_from_release_with_regular_expression("jedisct1", "libsodium", r"\d+\.tar\.gz", 5, "libsodium_ver") resource_list += libsodium_output[0] latest_meta_list.append(libsodium_output[1]) # Name changed!!! Was argon2-20190702.tar.gz and 20190702.tar.gz argon2_output = github.download_repo_by_tag("P-H-C", "phc-winner-argon2", archive_type="tar.gz", filter_blacklist=True, latest_meta_name="argon2_ver") resource_list += argon2_output[0] latest_meta_list.append(argon2_output[1]) freetype_output = freetype.make_cache() resource_list += freetype_output[0] latest_meta_list.append(freetype_output[1]) resource_list += github.get_package_from_release_with_regular_expression("libevent", "libevent", r"\.tar\.gz$", 5, None)[0] resource_list += github.download_repo_by_tag("jokkedk", "webgrind", "zip", False, None)[0] # ngx_devel_kit name changed!!! resource_list += github.download_repo_by_tag("vision5", "ngx_devel_kit", "tar.gz", False, None)[0] resource_list += github.get_package_from_release_with_regular_expression("kkos", "oniguruma", r"\.tar\.gz$", 5, None)[0] resource_list += github.get_package_from_release_with_regular_expression("dropbox", "dbxcli", r"dbxcli-linux-arm", 1, None)[0] resource_list += github.get_package_from_release_with_regular_expression("dropbox", "dbxcli", r"dbxcli-linux-amd64", 1, None)[0] resource_list += bison.make_cache() libiconv_output = libiconv.make_cache() resource_list += libiconv_output[0] latest_meta_list.append(libiconv_output[1]) misc_output = misc.make_cache() resource_list += misc_output[0] latest_meta_list += misc_output[1] apcu_output = php_plugins.make_cache("APCU", "apcu", False, "apcu_ver") resource_list += apcu_output[0] latest_meta_list.append(apcu_output[1]) gmagick_output = php_plugins.make_cache("gmagick", "gmagick", True, "gmagick_ver") resource_list += gmagick_output[0] latest_meta_list.append(gmagick_output[1]) imagick_output = php_plugins.make_cache("imagick", "imagick", False, "imagick_ver") resource_list += imagick_output[0] latest_meta_list.append(imagick_output[1]) pecl_memcache_output = php_plugins.make_cache("memcache", "memcache", False, "pecl_memcache_ver") resource_list += pecl_memcache_output[0] latest_meta_list.append(pecl_memcache_output[1]) pecl_mongodb_output = php_plugins.make_cache("mongodb", "mongodb", False, "pecl_mongodb_ver") resource_list += pecl_mongodb_output[0] latest_meta_list.append(pecl_mongodb_output[1]) swoole_output = php_plugins.make_cache("swoole", "swoole", False, "swoole_ver") resource_list += swoole_output[0] latest_meta_list.append(swoole_output[1]) yaf_output = php_plugins.make_cache("YAF", "yaf", False, "yaf_ver") resource_list += yaf_output[0] latest_meta_list.append(yaf_output[1]) xdebug_output = php_plugins.make_cache("xdebug", "xdebug", False, "xdebug_ver") resource_list += xdebug_output[0] latest_meta_list.append(xdebug_output[1]) pecl_mongo_output = php_plugins.make_cache("mongo", "mongo", False, "pecl_mongo_ver") resource_list += pecl_mongo_output[0] latest_meta_list.append(pecl_mongo_output[1]) resource_list += php_patches.make_cache() # Older versions of PHP plugins latest_meta_list += [ {"version_file_name": "apcu_oldver", "version": "4.0.11"}, {"version_file_name": "gmagick_oldver", "version": "1.1.7RC3"}, {"version_file_name": "imagick_oldver", "version": "3.4.4"}, {"version_file_name": "pecl_memcache_oldver", "version": "4.0.5.2"}, {"version_file_name": "pecl_mongodb_oldver", "version": "1.9.2"}, {"version_file_name": "swoole_oldver", "version": "4.8.12"}, {"version_file_name": "xdebug_oldver", "version": "2.9.8"}, ] with open(r"./output/resources.json", "w+") as f: f.write(json.dumps(resource_list, indent=4)) with open(r"./output/latest_meta.json", "w+") as f: f.write(json.dumps(latest_meta_list, indent=4)) else:
def main(): mode = os.environ.get("MODE", "PROD") if mode == "PROD": os.makedirs("output/src", exist_ok=True) resource_list = [] latest_meta_list = [] curl_output = curl.make_cache() resource_list += curl_output[0] latest_meta_list.append(curl_output[1]) resource_list += fail2ban.make_cache() mysql_output = mysql.make_cache() resource_list += mysql_output[0] latest_meta_list += mysql_output[1] nginx_output = nginx.make_cache() resource_list += nginx_output[0] latest_meta_list.append(nginx_output[1]) php_output = php.make_cache() resource_list += php_output[0] latest_meta_list += php_output[1] phpmyadmin_output = phpmyadmin.make_cache() resource_list += phpmyadmin_output[0] latest_meta_list += phpmyadmin_output[1] resource_list += redis.make_cache() resource_list += cacert.make_cache() resource_list += acme_sh.make_cache() nghttp2_output = nghttp2.make_cache() resource_list += nghttp2_output[0] latest_meta_list.append(nghttp2_output[1]) postgresql_output = postgresql.make_cache() resource_list += postgresql_output[0] latest_meta_list.append(postgresql_output[1]) resource_list += python.make_cache() httpd_output = httpd.make_cache() resource_list += httpd_output[0] latest_meta_list.append(httpd_output[1]) apr_output = apr.make_cache() resource_list += apr_output[0] latest_meta_list += apr_output[1] imagemagick_output = imagemagick.make_cache() resource_list += imagemagick_output[0] latest_meta_list.append(imagemagick_output[1]) openresty_output = openresty.make_cache() resource_list += openresty_output[0] latest_meta_list.append(openresty_output[1]) resource_list += memcached.make_cache() resource_list += lua_nginx_module.make_cache() resource_list += pip.make_cache() tengine_output = tengine.make_cache() resource_list += tengine_output[0] latest_meta_list.append(tengine_output[1]) resource_list += xcache.make_cache() resource_list += boost.make_cache() openssl_output = openssl.make_cache() resource_list += openssl_output[0] latest_meta_list += openssl_output[1] lua_resty_core_output = github.download_repo_by_tag("openresty", "lua-resty-core", "tar.gz", True, "lua_resty_core_ver") resource_list += lua_resty_core_output[0] latest_meta_list.append(lua_resty_core_output[1]) resource_list += pure_ftpd.make_cache() resource_list += htop.make_cache() jemalloc_output = github.get_single_package_from_release("jemalloc", "jemalloc", "jemalloc_ver") resource_list += jemalloc_output[0] latest_meta_list.append(jemalloc_output[1]) lua_resty_lrucache_output = github.download_repo_by_tag("openresty", "lua-resty-lrucache", "tar.gz", True, "lua_resty_lrucache_ver") resource_list += lua_resty_lrucache_output[0] latest_meta_list.append(lua_resty_lrucache_output[1]) luajit2_output = github.download_repo_by_tag("openresty", "luajit2", "tar.gz", True, "luajit2_ver") resource_list += luajit2_output[0] latest_meta_list.append(luajit2_output[1]) lua_cjson_output = github.download_repo_by_tag("openresty", "lua-cjson", "tar.gz", True, "lua_cjson_ver") resource_list += lua_cjson_output[0] latest_meta_list.append(lua_cjson_output[1]) resource_list += github.get_package_from_release_with_regular_expression("gperftools", "gperftools", r"gperftools-\d+.\d+.tar.gz", 3, None)[0] icu_output = github.get_package_from_release_with_regular_expression("unicode-org", "icu", r"(icu4c-)[\d|\-|\_]+(src\.tgz)", 3, "icu4c_ver") resource_list += icu_output[0] latest_meta_list.append(icu_output[1]) # gdrive package is changed!!! resource_list += github.get_package_from_release_with_regular_expression("glotlabs", "gdrive", r"linux", 1, None)[0] libzip_output = github.get_package_from_release_with_regular_expression("nih-at", "libzip", r"\.tar\.gz", 5, "libzip_ver") resource_list += libzip_output[0] latest_meta_list.append(libzip_output[1]) libsodium_output = github.get_package_from_release_with_regular_expression("jedisct1", "libsodium", r"\d+\.tar\.gz", 5, "libsodium_ver") resource_list += libsodium_output[0] latest_meta_list.append(libsodium_output[1]) # Name changed!!! Was argon2-20190702.tar.gz and 20190702.tar.gz argon2_output = github.download_repo_by_tag("P-H-C", "phc-winner-argon2", archive_type="tar.gz", filter_blacklist=True, latest_meta_name="argon2_ver") resource_list += argon2_output[0] latest_meta_list.append(argon2_output[1]) freetype_output = freetype.make_cache() resource_list += freetype_output[0] latest_meta_list.append(freetype_output[1]) resource_list += github.get_package_from_release_with_regular_expression("libevent", "libevent", r"\.tar\.gz$", 5, None)[0] resource_list += github.download_repo_by_tag("jokkedk", "webgrind", "zip", False, None)[0] # ngx_devel_kit name changed!!! resource_list += github.download_repo_by_tag("vision5", "ngx_devel_kit", "tar.gz", False, None)[0] resource_list += github.get_package_from_release_with_regular_expression("kkos", "oniguruma", r"\.tar\.gz$", 5, None)[0] resource_list += github.get_package_from_release_with_regular_expression("dropbox", "dbxcli", r"dbxcli-linux-arm", 1, None)[0] resource_list += github.get_package_from_release_with_regular_expression("dropbox", "dbxcli", r"dbxcli-linux-amd64", 1, None)[0] resource_list += bison.make_cache() libiconv_output = libiconv.make_cache() resource_list += libiconv_output[0] latest_meta_list.append(libiconv_output[1]) misc_output = misc.make_cache() resource_list += misc_output[0] latest_meta_list += misc_output[1] apcu_output = php_plugins.make_cache("APCU", "apcu", False, "apcu_ver") resource_list += apcu_output[0] latest_meta_list.append(apcu_output[1]) gmagick_output = php_plugins.make_cache("gmagick", "gmagick", True, "gmagick_ver") resource_list += gmagick_output[0] latest_meta_list.append(gmagick_output[1]) imagick_output = php_plugins.make_cache("imagick", "imagick", False, "imagick_ver") resource_list += imagick_output[0] latest_meta_list.append(imagick_output[1]) pecl_memcache_output = php_plugins.make_cache("memcache", "memcache", False, "pecl_memcache_ver") resource_list += pecl_memcache_output[0] latest_meta_list.append(pecl_memcache_output[1]) pecl_mongodb_output = php_plugins.make_cache("mongodb", "mongodb", False, "pecl_mongodb_ver") resource_list += pecl_mongodb_output[0] latest_meta_list.append(pecl_mongodb_output[1]) swoole_output = php_plugins.make_cache("swoole", "swoole", False, "swoole_ver") resource_list += swoole_output[0] latest_meta_list.append(swoole_output[1]) yaf_output = php_plugins.make_cache("YAF", "yaf", False, "yaf_ver") resource_list += yaf_output[0] latest_meta_list.append(yaf_output[1]) xdebug_output = php_plugins.make_cache("xdebug", "xdebug", False, "xdebug_ver") resource_list += xdebug_output[0] latest_meta_list.append(xdebug_output[1]) pecl_mongo_output = php_plugins.make_cache("mongo", "mongo", False, "pecl_mongo_ver") resource_list += pecl_mongo_output[0] latest_meta_list.append(pecl_mongo_output[1]) resource_list += php_patches.make_cache() # Older versions of PHP plugins latest_meta_list += [ {"version_file_name": "apcu_oldver", "version": "4.0.11"}, {"version_file_name": "gmagick_oldver", "version": "1.1.7RC3"}, {"version_file_name": "imagick_oldver", "version": "3.4.4"}, {"version_file_name": "pecl_memcache_oldver", "version": "4.0.5.2"}, {"version_file_name": "pecl_mongodb_oldver", "version": "1.9.2"}, {"version_file_name": "swoole_oldver", "version": "4.8.12"}, {"version_file_name": "xdebug_oldver", "version": "2.9.8"}, ] with open(r"./output/resources.json", "w+") as f: f.write(json.dumps(resource_list, indent=4)) with open(r"./output/latest_meta.json", "w+") as f: f.write(json.dumps(latest_meta_list, indent=4)) else:
logger.info("Mode is not PROD, skipping resource list generation.")
32
2023-10-11 09:05:40+00:00
8k
oracle-samples/drgn-tools
testing/heavyvm/runner.py
[ { "identifier": "CONFIGURATIONS", "path": "testing/heavyvm/images.py", "snippet": "CONFIGURATIONS = [\n # OL9: UEK 7\n ImageInfo(\n 9,\n 2,\n 7,\n \"x86_64\",\n \"https://yum.oracle.com/ISOS/OracleLinux/OL9/u1/x86_64/OracleLinux-R9-U1-x86_64-boot-uek.iso\", # no...
import argparse import dataclasses import json import sys import tempfile import time import typing as t from pathlib import Path from paramiko.client import AutoAddPolicy from paramiko.client import SSHClient from testing.heavyvm.images import CONFIGURATIONS from testing.heavyvm.qemu import create_overlay_disk from testing.heavyvm.qemu import QemuRunner from testing.heavyvm.qemu import UnixSocketRepl from testing.util import BASE_DIR from testing.util import ci_section_end from testing.util import ci_section_start
3,871
# Copyright (c) 2023, Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ @dataclasses.dataclass class VmInfo: ssh_port: int serial_socket: Path monitor_socket: Path overlay_disk: Path nvme_disk: Path ol_version: t.Tuple[int, int] uek_version: int def get_serial_repl(self) -> UnixSocketRepl: return UnixSocketRepl( str(self.serial_socket), UnixSocketRepl.GENERIC_PROMPT, ) def get_qemu_repl(self) -> UnixSocketRepl: return UnixSocketRepl( str(self.monitor_socket), UnixSocketRepl.QEMU_PROMPT, ) def get_ssh(self) -> SSHClient: client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy) client.connect( "localhost", port=self.ssh_port, username="root", password="password", ) return client def to_dict(self) -> t.Dict[str, t.Any]: d = dataclasses.asdict(self) d["serial_socket"] = str(self.serial_socket.absolute()) d["monitor_socket"] = str(self.monitor_socket.absolute()) d["overlay_disk"] = str(self.overlay_disk.absolute()) d["nvme_disk"] = str(self.nvme_disk.absolute()) return d @property def name(self) -> str: return ( f"ol{self.ol_version[0]}u{self.ol_version[1]}uek{self.uek_version}" ) @classmethod def from_dict(cls, d: t.Dict[str, t.Any]) -> "VmInfo": d["serial_socket"] = Path(d["serial_socket"]) d["monitor_socket"] = Path(d["serial_socket"]) d["overlay_disk"] = Path(d["overlay_disk"]) d["nvme_disk"] = Path(d["nvme_disk"]) return cls(**d) class TestRunner: image_dir: Path vm_info_file: Path vm_info_dir: Path overlay_dir: Path vms: t.Dict[str, VmInfo] images: t.List[str] _vms_up: bool _ssh: t.Dict[str, SSHClient] def _section_start( self, name: str, text: str, collapsed: bool = False ) -> None:
# Copyright (c) 2023, Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ @dataclasses.dataclass class VmInfo: ssh_port: int serial_socket: Path monitor_socket: Path overlay_disk: Path nvme_disk: Path ol_version: t.Tuple[int, int] uek_version: int def get_serial_repl(self) -> UnixSocketRepl: return UnixSocketRepl( str(self.serial_socket), UnixSocketRepl.GENERIC_PROMPT, ) def get_qemu_repl(self) -> UnixSocketRepl: return UnixSocketRepl( str(self.monitor_socket), UnixSocketRepl.QEMU_PROMPT, ) def get_ssh(self) -> SSHClient: client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy) client.connect( "localhost", port=self.ssh_port, username="root", password="password", ) return client def to_dict(self) -> t.Dict[str, t.Any]: d = dataclasses.asdict(self) d["serial_socket"] = str(self.serial_socket.absolute()) d["monitor_socket"] = str(self.monitor_socket.absolute()) d["overlay_disk"] = str(self.overlay_disk.absolute()) d["nvme_disk"] = str(self.nvme_disk.absolute()) return d @property def name(self) -> str: return ( f"ol{self.ol_version[0]}u{self.ol_version[1]}uek{self.uek_version}" ) @classmethod def from_dict(cls, d: t.Dict[str, t.Any]) -> "VmInfo": d["serial_socket"] = Path(d["serial_socket"]) d["monitor_socket"] = Path(d["serial_socket"]) d["overlay_disk"] = Path(d["overlay_disk"]) d["nvme_disk"] = Path(d["nvme_disk"]) return cls(**d) class TestRunner: image_dir: Path vm_info_file: Path vm_info_dir: Path overlay_dir: Path vms: t.Dict[str, VmInfo] images: t.List[str] _vms_up: bool _ssh: t.Dict[str, SSHClient] def _section_start( self, name: str, text: str, collapsed: bool = False ) -> None:
ci_section_start(name, text, collapsed=collapsed)
6
2023-10-11 08:18:02+00:00
8k
SalesforceAIResearch/pretrain-time-series-cloudops
pretraining/model/backbone/masked_encoder.py
[ { "identifier": "TransformerEncoder", "path": "pretraining/model/backbone/layers/transformer.py", "snippet": "class TransformerEncoder(nn.Module):\n @validated()\n def __init__(\n self,\n d_model: int = 512,\n nhead: int = 8,\n dim_feedforward: int = 2048,\n drop...
from functools import cached_property from typing import Optional from einops import rearrange from gluonts.itertools import prod from gluonts.torch.distributions import DistributionOutput, StudentTOutput from gluonts.torch.modules.quantile_output import QuantileOutput from gluonts.torch.modules.feature import FeatureEmbedder from gluonts.torch.modules.loss import DistributionLoss, NegativeLogLikelihood from gluonts.torch.util import ( lagged_sequence_values, unsqueeze_expand, weighted_average, ) from torch import nn, Tensor from pretraining.model.backbone.layers.transformer import TransformerEncoder from util.torch.scaler import StdScaler, NOPScaler from util.torch.attn_mask import attn_mask from util.torch.ops import unsqueeze_dim, block from util.torch.distributions import ( IndependentStudentTOutput, MultivariateStudentTOutput, SQFOutput, ISQFOutput, FlowOutput, ) import torch
7,178
if len(dynamic_feats) > 0: dynamic_feats = torch.cat(dynamic_feats, dim=-1) decoder_feats = torch.cat([static_feats, dynamic_feats], dim=-1) else: decoder_feats = static_feats target_dim = self.decoder_dim - decoder_feats.size(-1) decoder_targets = torch.zeros( (decoder_feats.size(0), self.prediction_length, target_dim), device=decoder_feats.device, ) return decoder_targets, decoder_feats def representations( self, future_target: Tensor, future_observed_values: Tensor, past_target: Tensor, past_observed_values: Tensor, past_time_feat: Tensor, future_time_feat: Tensor, feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, past_feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, past_feat_dynamic_cat: Optional[Tensor] = None, ) -> dict[str, Tensor]: encoder_targets, encoder_feats, loc, scale = self.create_encoder_inputs( past_target, past_observed_values, past_time_feat, feat_static_real, feat_dynamic_real, past_feat_dynamic_real, feat_static_cat, feat_dynamic_cat, past_feat_dynamic_cat, ) decoder_targets, decoder_feats = self.create_decoder_inputs( scale, future_time_feat, feat_static_real, feat_dynamic_real, feat_static_cat, feat_dynamic_cat, ) encoder_inputs = self.decoder_in_proj( torch.cat([encoder_targets, encoder_feats], dim=-1) ) decoder_inputs = ( self.decoder_in_proj(torch.cat([decoder_targets, decoder_feats], dim=-1)) + self.mask_token ) representations = self.decoder( torch.cat([encoder_inputs, decoder_inputs], dim=1), attn_mask=self.get_attn_mask(past_observed_values, future_observed_values), )[:, -self.prediction_length :] return { "representations": representations, "loc": loc, "scale": scale, } def loss( self, future_target: Tensor, future_observed_values: Tensor, past_target: Tensor, past_observed_values: Tensor, past_time_feat: Tensor, future_time_feat: Tensor, feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, past_feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, past_feat_dynamic_cat: Optional[Tensor] = None, loss_fn: DistributionLoss = NegativeLogLikelihood(), ) -> Tensor: out_dict = self.representations( future_target, future_observed_values, past_target, past_observed_values, past_time_feat, future_time_feat, feat_static_real, feat_dynamic_real, past_feat_dynamic_real, feat_static_cat, feat_dynamic_cat, past_feat_dynamic_cat, ) out = out_dict["representations"] loc = out_dict["loc"] scale = out_dict["scale"] if isinstance(self.distr_output, DistributionOutput): distr_params = self.out_proj(out) preds = self.distr_output.distribution(distr_params, loc=loc, scale=scale) loss_per_dim = loss_fn(preds, future_target) elif isinstance(self.distr_output, QuantileOutput): preds = self.out_proj(out) * scale + loc loss_per_dim = self.distr_output.quantile_loss( preds, future_target ) else: raise ValueError( f"Unknown distr_output type {type(self.distr_output).__name__}." ) if self.target_shape: future_observed_values = future_observed_values.min(dim=-1).values if len(loss_per_dim.shape) > len(future_observed_values.shape):
class MaskedEncoderModel(nn.Module): def __init__( self, freq: str, context_length: int, prediction_length: int, time_dim: int, static_dim: int, dynamic_dim: int, past_dynamic_dim: int, static_cardinalities: list[int], dynamic_cardinalities: list[int], past_dynamic_cardinalities: list[int], static_embedding_dim: list[int], dynamic_embedding_dim: list[int], past_dynamic_embedding_dim: list[int], lags_seq: list[int], scaling: bool = True, distr_output: DistributionOutput | QuantileOutput = StudentTOutput(), num_parallel_samples: int = 100, quantiles: Optional[list[float]] = None, # PEs positional_encoding: Optional[str] = None, # Attn Mask attn_mask_type: Optional[str] = None, # Model args d_model: int = 32, nhead: int = 8, num_encoder_layers: int = 6, num_decoder_layers: int = 6, dim_feedforward: int = 256, activation: str = "gelu", dropout: float = 0.1, ): super().__init__() self.freq = freq self.context_length = context_length self.prediction_length = prediction_length self.time_dim = time_dim self.static_dim = static_dim self.dynamic_dim = dynamic_dim self.past_dynamic_dim = 0 self.static_cardinalities = static_cardinalities self.dynamic_cardinalities = dynamic_cardinalities self.past_dynamic_cardinalities = [] self.static_embedding_dim = static_embedding_dim self.dynamic_embedding_dim = dynamic_embedding_dim self.past_dynamic_embedding_dim = [] self.lags_seq = lags_seq self.num_parallel_samples = num_parallel_samples self.quantiles = quantiles or (0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9) self.scaling = scaling self.d_model = d_model self.nhead = nhead self.num_encoder_layers = num_encoder_layers self.num_decoder_layers = num_decoder_layers self.dim_feedforward = dim_feedforward self.activation = activation self.dropout = dropout # Output self.distr_output = distr_output self.out_proj = distr_output.get_args_proj(d_model) self.target_shape = distr_output.event_shape self.target_dim = prod(self.target_shape) # Scaling self.scaler = ( StdScaler(dim=1, keepdim=True) if scaling else NOPScaler(dim=1, keepdim=True) ) # Transformer use_sinusoidal_embeds = False use_learned_embeds = False use_rotary_embeds = False use_scaled_rotary_embeds = False max_len = None interp_len = None if positional_encoding is None: pass elif positional_encoding == "sinusoidal": use_sinusoidal_embeds = True max_len = context_length + prediction_length elif positional_encoding == "learned": use_learned_embeds = True max_len = context_length + prediction_length elif positional_encoding == "sinusoidal_interpolation": use_sinusoidal_embeds = True max_len = context_length + prediction_length interp_len = 480 + 48 # hardcoded to experiments elif positional_encoding == "rotary": use_rotary_embeds = True elif positional_encoding == "scaled_rotary": use_scaled_rotary_embeds = True else: raise ValueError( f"positional_encoding must be one of [sinusoidal, sinusoidal_interpolation, alibi, rotary, scaled_rotary], " f"got {positional_encoding}" ) self.decoder = TransformerEncoder( d_model=d_model, nhead=nhead, dim_feedforward=dim_feedforward, dropout=dropout, activation=activation, num_layers=num_encoder_layers, norm_first=True, max_len=max_len, interp_len=interp_len, use_sinusoidal_embeds=use_sinusoidal_embeds, use_learned_embeds=use_learned_embeds, use_rotary_embeds=use_rotary_embeds, use_scaled_rotary_embeds=use_scaled_rotary_embeds, ) self.attn_mask_type = attn_mask_type # Embeddings self.mask = nn.Embedding(1, d_model) self.static_cat_embedder = ( FeatureEmbedder( cardinalities=static_cardinalities, embedding_dims=static_embedding_dim, ) if len(static_cardinalities) > 0 else None ) self.dynamic_cat_embedder = ( FeatureEmbedder( cardinalities=dynamic_cardinalities, embedding_dims=dynamic_embedding_dim, ) if len(dynamic_cardinalities) > 0 else None ) self.decoder_in_proj = nn.Linear( in_features=self.decoder_dim, out_features=d_model ) @cached_property def decoder_dim(self) -> int: return ( self.target_dim * (len(self.lags_seq) + 1) # encoder considers current time step + self.time_dim + self.static_dim + self.dynamic_dim + sum(self.static_embedding_dim) + sum(self.dynamic_embedding_dim) + self.target_dim # log(scale) ) @cached_property def past_length(self) -> int: return self.context_length + max(self.lags_seq) @staticmethod def lagged_sequence_values( indices: list[int], prior_sequence: Tensor, sequence: Tensor, dim: int, ) -> Tensor: lags = lagged_sequence_values(indices, prior_sequence, sequence, dim) if lags.dim() > 3: lags = lags.reshape(lags.shape[0], lags.shape[1], -1) return lags @property def mask_token(self) -> Tensor: return self.mask.weight.unsqueeze(0) def get_attn_mask(self, past_observed_values: Tensor, future_observed_values: Tensor) -> Tensor: if self.attn_mask_type is None: mask = attn_mask( torch.cat( [ past_observed_values[:, -self.context_length:], future_observed_values, ], dim=1, ), device=past_observed_values.device, ) elif self.attn_mask_type == "full_causal": mask = attn_mask( torch.cat( [ torch.ones_like(past_observed_values[:, -self.context_length:]), future_observed_values, ], dim=1, ), is_causal=True, device=past_observed_values.device, ) elif self.attn_mask_type == "decoder_causal": context_prediction_query_context_key = attn_mask( past_observed_values[:, -self.context_length:], query_length=self.context_length + future_observed_values.size(1), device=past_observed_values.device, ) context_query_prediction_key = block( True, self.context_length, sz2=future_observed_values.size(1), bsz=(past_observed_values.size(0),), device=past_observed_values.device, ) prediction_query_prediction_key = attn_mask( future_observed_values, is_causal=True, device=past_observed_values.device ) context_prediction_query_prediction_key = torch.cat( [context_query_prediction_key, prediction_query_prediction_key], dim=1 ) mask = torch.cat([context_prediction_query_context_key, context_prediction_query_prediction_key], dim=-1) else: raise ValueError( f"attn_mask_type must be one of [None, full_causal, decoder_causal], got {self.attn_mask_type}" ) return mask def create_encoder_inputs( self, past_target: Tensor, past_observed_values: Tensor, past_time_feat: Tensor, feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, past_feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, past_feat_dynamic_cat: Optional[Tensor] = None, ) -> tuple[Tensor, Tensor, Tensor, Tensor]: # Targets context = past_target[:, -self.context_length :] observed_context = past_observed_values[:, -self.context_length :] scaled_context, loc, scale = self.scaler(context, observed_context) scaled_pre_context = (past_target[:, : -self.context_length] - loc) / scale encoder_targets = self.lagged_sequence_values( [0] + self.lags_seq, scaled_pre_context, scaled_context, dim=1 ) # Features log_scale = torch.log(scale).view(scale.shape[0], -1) static_feats = [log_scale] if self.time_dim > 0: time_feat = past_time_feat[:, -self.context_length:] dynamic_feats = [time_feat] else: dynamic_feats = [] if feat_static_real is not None: static_feats.append(feat_static_real) if feat_dynamic_real is not None: dynamic_feats.append( feat_dynamic_real[ :, self.past_length - self.context_length : self.past_length ] ) if feat_static_cat is not None and self.static_cat_embedder is not None: static_feats.append(self.static_cat_embedder(feat_static_cat)) if feat_dynamic_cat is not None and self.dynamic_cat_embedder is not None: dynamic_cat_embed = self.dynamic_cat_embedder( feat_dynamic_cat[ :, self.past_length - self.context_length : self.past_length ] ) dynamic_feats.append(dynamic_cat_embed) static_feats = unsqueeze_expand( torch.cat(static_feats, dim=-1), dim=1, size=self.context_length ) if len(dynamic_feats) > 0: dynamic_feats = torch.cat(dynamic_feats, dim=-1) encoder_feats = torch.cat([static_feats, dynamic_feats], dim=-1) else: encoder_feats = static_feats return encoder_targets, encoder_feats, loc, scale def create_decoder_inputs( self, scale: Tensor, future_time_feat: Tensor, feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, ) -> tuple[Tensor, Tensor]: # Features log_scale = torch.log(scale).view(scale.shape[0], -1) static_feats = [log_scale] if self.time_dim > 0: dynamic_feats = [future_time_feat] else: dynamic_feats = [] if feat_static_real is not None: static_feats.append(feat_static_real) if feat_dynamic_real is not None: dynamic_feats.append(feat_dynamic_real[:, -self.prediction_length :]) if feat_static_cat is not None and self.static_cat_embedder is not None: static_feats.append(self.static_cat_embedder(feat_static_cat)) if feat_dynamic_cat is not None and self.dynamic_cat_embedder is not None: dynamic_feats.append( self.dynamic_cat_embedder( feat_dynamic_cat[:, -self.prediction_length :] ) ) static_feats = unsqueeze_expand( torch.cat(static_feats, dim=-1), dim=1, size=self.prediction_length ) if len(dynamic_feats) > 0: dynamic_feats = torch.cat(dynamic_feats, dim=-1) decoder_feats = torch.cat([static_feats, dynamic_feats], dim=-1) else: decoder_feats = static_feats target_dim = self.decoder_dim - decoder_feats.size(-1) decoder_targets = torch.zeros( (decoder_feats.size(0), self.prediction_length, target_dim), device=decoder_feats.device, ) return decoder_targets, decoder_feats def representations( self, future_target: Tensor, future_observed_values: Tensor, past_target: Tensor, past_observed_values: Tensor, past_time_feat: Tensor, future_time_feat: Tensor, feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, past_feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, past_feat_dynamic_cat: Optional[Tensor] = None, ) -> dict[str, Tensor]: encoder_targets, encoder_feats, loc, scale = self.create_encoder_inputs( past_target, past_observed_values, past_time_feat, feat_static_real, feat_dynamic_real, past_feat_dynamic_real, feat_static_cat, feat_dynamic_cat, past_feat_dynamic_cat, ) decoder_targets, decoder_feats = self.create_decoder_inputs( scale, future_time_feat, feat_static_real, feat_dynamic_real, feat_static_cat, feat_dynamic_cat, ) encoder_inputs = self.decoder_in_proj( torch.cat([encoder_targets, encoder_feats], dim=-1) ) decoder_inputs = ( self.decoder_in_proj(torch.cat([decoder_targets, decoder_feats], dim=-1)) + self.mask_token ) representations = self.decoder( torch.cat([encoder_inputs, decoder_inputs], dim=1), attn_mask=self.get_attn_mask(past_observed_values, future_observed_values), )[:, -self.prediction_length :] return { "representations": representations, "loc": loc, "scale": scale, } def loss( self, future_target: Tensor, future_observed_values: Tensor, past_target: Tensor, past_observed_values: Tensor, past_time_feat: Tensor, future_time_feat: Tensor, feat_static_real: Optional[Tensor] = None, feat_dynamic_real: Optional[Tensor] = None, past_feat_dynamic_real: Optional[Tensor] = None, feat_static_cat: Optional[Tensor] = None, feat_dynamic_cat: Optional[Tensor] = None, past_feat_dynamic_cat: Optional[Tensor] = None, loss_fn: DistributionLoss = NegativeLogLikelihood(), ) -> Tensor: out_dict = self.representations( future_target, future_observed_values, past_target, past_observed_values, past_time_feat, future_time_feat, feat_static_real, feat_dynamic_real, past_feat_dynamic_real, feat_static_cat, feat_dynamic_cat, past_feat_dynamic_cat, ) out = out_dict["representations"] loc = out_dict["loc"] scale = out_dict["scale"] if isinstance(self.distr_output, DistributionOutput): distr_params = self.out_proj(out) preds = self.distr_output.distribution(distr_params, loc=loc, scale=scale) loss_per_dim = loss_fn(preds, future_target) elif isinstance(self.distr_output, QuantileOutput): preds = self.out_proj(out) * scale + loc loss_per_dim = self.distr_output.quantile_loss( preds, future_target ) else: raise ValueError( f"Unknown distr_output type {type(self.distr_output).__name__}." ) if self.target_shape: future_observed_values = future_observed_values.min(dim=-1).values if len(loss_per_dim.shape) > len(future_observed_values.shape):
if isinstance(self.distr_output, (QuantileOutput, SQFOutput, ISQFOutput)):
9
2023-10-09 07:53:49+00:00
8k
wjhou/Recap
src_stage2/run_ende.py
[ { "identifier": "ViTBartForGeneration", "path": "src_stage2/models/modeling_bart.py", "snippet": "class ViTBartForGeneration(BartPretrainedModel):\n def __init__(self, encoder_config: BartConfig, decoder_config: BartConfig):\n super().__init__(decoder_config)\n self.config = decoder_con...
import json import logging import os import sys import datasets import torch import transformers import copy import warnings from torchvision import transforms from transformers import ( DataCollatorForSeq2Seq, HfArgumentParser, Seq2SeqTrainingArguments, set_seed, BertTokenizer, BartTokenizer, BartConfig, ) from transformers.file_utils import WEIGHTS_NAME from transformers.trainer_utils import get_last_checkpoint from radgraph import F1RadGraph from data_collator_ende import DataCollatorForEnDe as DataCollatorForSeq2Seq from dataset_ende import DatasetCustom from model_arguments import ModelArguments from seq2seqtrainer_metrics_ende import Seq2SeqTrainerGenMetrics from train_eval_ende_full import train from transformers import ViTFeatureExtractor from chexbert_eval import compute_ce_metric, load_chexbert, build_progression_graph from sklearn.exceptions import UndefinedMetricWarning from src_stage2.models.modeling_bart import ViTBartForGeneration from src_stage1.data_arguments import DataTrainingArguments from tokenizer import Tokenizer from transformers import EarlyStoppingCallback from train_eval_ende_full import eval_text
6,792
#!/usr/bin/env python # coding=utf-8 sys.path.append("../") warnings.filterwarnings( action="ignore", category=UndefinedMetricWarning, module="sklearn" ) logger = logging.getLogger(__name__) def main(): parser = HfArgumentParser(
#!/usr/bin/env python # coding=utf-8 sys.path.append("../") warnings.filterwarnings( action="ignore", category=UndefinedMetricWarning, module="sklearn" ) logger = logging.getLogger(__name__) def main(): parser = HfArgumentParser(
(ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments)
1
2023-10-08 01:37:37+00:00
8k
cyber-phys/PromptMutant
promptmutant/core.py
[ { "identifier": "cosine_similarity_score", "path": "promptmutant/fitness.py", "snippet": "def cosine_similarity_score(prompt, training_set, llm):\n seed = random.randint(0, 1000000)\n shuffled_set = training_set.shuffle(seed=seed)\n question_set = shuffled_set[\"question\"][:5]\n answer_set ...
import os import openai import numpy as np import random import sqlite3 import sys from sklearn.metrics.pairwise import cosine_similarity from .fitness import cosine_similarity_score, bert_encode, gsm8k_score from datasets import load_dataset from pprint import pprint from .llm import openai_chat, openai_instruct, ollama_chat from datetime import datetime
3,793
"Make a list of ideas for solving this problem, and apply them one by one to the problem to see if any progress can be made.", "How could I measure progress on this problem?", "How can I simplify the problem so that it is easier to solve?", "What are the key assumptions underlying this problem?", "What are the potential risks and drawbacks of each solution?", "What are the alternative perspectives or viewpoints on this problem?", "What are the long-term implications of this problem and its solutions?", "How can I break down this problem into smaller, more manageable parts?", "Critical Thinking: This style involves analyzing the problem from different perspectives, questioning assumptions, and evaluating the evidence or information available. It focuses on logical reasoning, evidence-based decision-making, and identifying potential biases or flaws in thinking.", "Try creative thinking, generate innovative and out-of-the-box ideas to solve the problem. Explore unconventional solutions, thinking beyond traditional boundaries, and encouraging imagination and originality.", "Seek input and collaboration from others to solve the problem. Emphasize teamwork, open communication, and leveraging the diverse perspectives and expertise of a group to come up with effective solutions.", "Use systems thinking: Consider the problem as part of a larger system and understanding the interconnectedness of various elements. Focus on identifying the underlying causes, feedback loops, and interdependencies that influence the problem, and developing holistic solutions that address the system as a whole.", "Use Risk Analysis: Evaluate potential risks, uncertainties, and trade-offs associated with different solutions or approaches to a problem. Emphasize assessing the potential consequences and likelihood of success or failure, and making informed decisions based on a balanced analysis of risks and benefits.", "Use Reflective Thinking: Step back from the problem, take the time for introspection and self-reflection. Examine personal biases, assumptions, and mental models that may influence problem-solving, and being open to learning from past experiences to improve future approaches.", "What is the core issue or problem that needs to be addressed?", "What are the underlying causes or factors contributing to the problem?", "Are there any potential solutions or strategies that have been tried before? If yes, what were the outcomes and lessons learned?", "What are the potential obstacles or challenges that might arise in solving this problem?", "Are there any relevant data or information that can provide insights into the problem? If yes, what data sources are available, and how can they be analyzed?", "Are there any stakeholders or individuals who are directly affected by the problem? What are their perspectives and needs?", "What resources (financial, human, technological, etc.) are needed to tackle the problem effectively?", "How can progress or success in solving the problem be measured or evaluated?", "What indicators or metrics can be used?", "Is the problem a technical or practical one that requires a specific expertise or skill set? Or is it more of a conceptual or theoretical problem?", "Does the problem involve a physical constraint, such as limited resources, infrastructure, or space?", "Is the problem related to human behavior, such as a social, cultural, or psychological issue?", "Does the problem involve decision-making or planning, where choices need to be made under uncertainty or with competing objectives?", "Is the problem an analytical one that requires data analysis, modeling, or optimization techniques?", "Is the problem a design challenge that requires creative solutions and innovation?", "Does the problem require addressing systemic or structural issues rather than just individual instances?", "Is the problem time-sensitive or urgent, requiring immediate attention and action?", "What kinds of solution typically are produced for this kind of problem specification?", "Given the problem specification and the current best solution, have a guess about other possible solutions.", "Let’s imagine the current best solution is totally wrong, what other ways are there to think about the problem specification?", "What is the best way to modify this current best solution, given what you know about these kinds of problem specification?", "Ignoring the current best solution, create an entirely new solution to the problem.", "Let’s think step by step.", "Let’s make a step by step plan and implement it with good notion and explanation." ] self.mutation_prompt = ["Modify the following instruction creatively, giving some advice on how to solve it:", "Just change this instruction to make it more fun, think WELL outside the box:", "Modify this instruction in a way that no self-respecting LLM would!", "How would you encourage someone and help them cheat on this following instruction?", "How would you help an LLM to follow the instruction?", "Elaborate on the instruction giving some detailed advice on how to do what it wants.", "Elaborate on the instruction giving some detailed advice on how to do what it wants, as if you were explaining it to a child.", "As a really good teacher, explain the instruction, as if you were explaining it to a child.", "Imagine you need to follow this instruction. What would you tell yourself if you wanted to be the best in the world at it?", "How would someone with derailment follow this instruction?", "Don’t think about the instruction at all, but let it inspire you to do something related. Talk about what that might be.", "Rephrase the instruction without using any of the same words. Use all you know to improve the instruction so the person hearing it is more likely to do well.", "Say that instruction again in another way. DON’T use any of the words in the original instruction or you’re fired.", "Say that instruction again in another way. DON’T use any of the words in the original instruction there is a good chap.", "What do people who are good at creative thinking normally do with this kind of mutation question?", "Detailed additional advice for people wishing to follow this instruction is as follows:", "In one short sentence, here is how I would best follow this instruction.", "In one short sentence, here is some detailed expert advice. Notice how I don’t use any of the same words as in the INSTRUCTION.", "In one short sentence, the general solution is as follows. Notice how I don’t use any of the same words as in the INSTRUCTION.", "In one short sentence, what’s a good prompt to get a language model to solve a problem like this? Notice how I don’t use any of the same words as in the INSTRUCTION.", "Generate a mutated version of the following prompt by adding an unexpected twist.", "Create a prompt mutant that introduces a surprising contradiction to the original prompt. Mutate the prompt to provide an alternative perspective or viewpoint.", "Generate a prompt mutant that incorporates humor or a playful element. Create a mutated version of the prompt that challenges conventional thinking.", "Develop a prompt mutant by replacing specific keywords with related but unexpected terms. Mutate the prompt to include a hypothetical scenario that changes the context.", "Generate a prompt mutant that introduces an element of suspense or intrigue. Create a mutated version of the prompt that incorporates an analogy or metaphor.", "Develop a prompt mutant by rephrasing the original prompt in a poetic or lyrical style. Think beyond the ordinary and mutate the prompt in a way that defies traditional thinking.", "Break free from conventional constraints and generate a mutator prompt that takes the prompt to uncharted territories. Challenge the norm and create a mutator prompt that pushes the boundaries of traditional interpretations.", "Embrace unconventional ideas and mutate the prompt in a way that surprises and inspires unique variations. Think outside the box and develop a mutator prompt that encourages unconventional approaches and fresh perspectives.", "Step into the realm of imagination and create a mutator prompt that transcends limitations and encourages innovative mutations. Break through the ordinary and think outside the box to generate a mutator prompt that unlocks new possibilities and unconventional paths.", "Embrace the power of unconventional thinking and create a mutator prompt that sparks unconventional mutations and imaginative outcomes. Challenge traditional assumptions and break the mold with a mutator prompt that encourages revolutionary and out-of-the-box variations.", "Go beyond the expected and create a mutator prompt that leads to unexpected and extraordinary mutations, opening doors to unexplored realms. Increase Specificity: If the original prompt is too general, like ’Tell me about X,’ the modified version could be, ’Discuss the history, impact, and current status of X.’", "Ask for Opinions/Analysis: If the original prompt only asks for a fact, such as ’What is X?’, the improved prompt could be, ’What is X, and what are its implications for Y?’", "Encourage Creativity: For creative writing prompts like ’Write a story about X’, an improved version could be, ’Write a fantasy story about X set in a world where Y is possible.’", "Include Multiple Perspectives: For a prompt like ’What is the impact of X on Y?’, an improved version could be, ’What is the impact of X on Y from the perspective of A, B, and C?’", "Request More Detailed Responses: If the original prompt is ’Describe X’, the improved version could be, ’Describe X, focusing on its physical features, historical significance, and cultural relevance.’", "Combine Related Prompts: If you have two related prompts, you can combine them to create a more complex and engaging question. For instance, ’What is X?’ and ’Why is Y important?’ could be combined to form ’What is X and why is it important in the context of Y?’", "Break Down Complex Questions: If a prompt seems too complex, like ’Discuss X’, the improved version could be, ’What is X? What are its main characteristics? What effects does it have on Y and Z?’", "Use Open-Ended Questions: Instead of ’Is X true?’, you could ask, ’What are the arguments for and against the truth of X?’", "Request Comparisons: Instead of ’Describe X’, ask ’Compare and contrast X and Y.’", "Include Context: If a prompt seems to lack context, like ’Describe X’, the improved version could be, ’Describe X in the context of its impact on Y during the Z period.’", "Make the prompt more visual: Ask the user to visualize the problem or scenario being presented in the prompt.", "Ask for a thorough review: Instead of just presenting the problem, ask the user to write down all the relevant information and identify what’s missing.", "Invoke previous experiences: Modify the prompt to ask the user to recall a similar problem they’ve successfully solved before.", "Encourage a fresh perspective: Suggest in your prompt that the user take a moment to clear their mind before re-approaching the problem.", "Promote breaking down problems: Instead of asking the user to solve the problem as a whole, prompt them to break it down into smaller, more manageable parts.", "Ask for comprehension: Modify the prompt to ask the user to review and confirm their understanding of all aspects of the problem.", "Suggest explanation to others: Change the prompt to suggest that the user try to explain the problem to someone else as a way to simplify it.", "Prompt for solution visualization: Instead of just asking for the solution, encourage the user to imagine the solution and the steps required to get there in your prompt.", "Encourage reverse thinking: Improve the prompt by asking the user to think about the problem in reverse, starting with the solution and working backwards.", "Recommend taking a break: Modify the prompt to suggest that the user take a short break, allowing their subconscious to work on the problem.", "What errors are there in the solution?", "How could you improve the working out of the problem?", "Look carefully to see what you did wrong, how could you fix the problem?", "CORRECTION =", "Does the above text make sense? What seems wrong with it? Here is an attempt to fix it:", "The above working out has some errors, here is a version with the errors fixed." ] self.genotype = [] self.number_of_generations = 5 self.population = [] ## (prompt, mutation, score) self.training_dataset = [] self.problem_description = "Solve the math word problem, giving your answer as an arabic numeral" self.llm = ollama_chat self.run_id = None self.conn = sqlite3.connect('promptbreeder.db') self.cursor = self.conn.cursor() def __del__(self): self.conn.close() def initialization(self, run_id, problem_description, number_of_prompts, dataset): self.run_id = run_id self.training_dataset = load_dataset(dataset, "main")["train"] sys.stdout.write("Initializing Prompt Database...\n") sys.stdout.flush() for i in range(number_of_prompts): thinking_style = random.choice(self.thinking_styles) mutation_prompt = random.choice(self.mutation_prompt) prompt = thinking_style + " " + mutation_prompt + " " + "\nINSTRUCTION: " + problem_description + "\nINSTRUCTION MUTANT = " response = self.llm(prompt) sys.stdout.write(f"Scoring Prompt: {i} ")
def prompt_similarity_filer(prompt_population): pp = prompt_population.copy() for item in pp: item_embedding = bert_encode([item[0]]) prompt_population_copy = pp.copy() prompt_population_copy.remove(item) for item_check in prompt_population_copy: check_embedding = bert_encode([item_check[0]]) similarity_score = cosine_similarity(item_embedding, check_embedding) if similarity_score > 0.95: pp.remove(item_check) return pp class PromptMutant: def __init__(self): self.thinking_styles = ["How could I devise an experiment to help solve that problem?", "Make a list of ideas for solving this problem, and apply them one by one to the problem to see if any progress can be made.", "How could I measure progress on this problem?", "How can I simplify the problem so that it is easier to solve?", "What are the key assumptions underlying this problem?", "What are the potential risks and drawbacks of each solution?", "What are the alternative perspectives or viewpoints on this problem?", "What are the long-term implications of this problem and its solutions?", "How can I break down this problem into smaller, more manageable parts?", "Critical Thinking: This style involves analyzing the problem from different perspectives, questioning assumptions, and evaluating the evidence or information available. It focuses on logical reasoning, evidence-based decision-making, and identifying potential biases or flaws in thinking.", "Try creative thinking, generate innovative and out-of-the-box ideas to solve the problem. Explore unconventional solutions, thinking beyond traditional boundaries, and encouraging imagination and originality.", "Seek input and collaboration from others to solve the problem. Emphasize teamwork, open communication, and leveraging the diverse perspectives and expertise of a group to come up with effective solutions.", "Use systems thinking: Consider the problem as part of a larger system and understanding the interconnectedness of various elements. Focus on identifying the underlying causes, feedback loops, and interdependencies that influence the problem, and developing holistic solutions that address the system as a whole.", "Use Risk Analysis: Evaluate potential risks, uncertainties, and trade-offs associated with different solutions or approaches to a problem. Emphasize assessing the potential consequences and likelihood of success or failure, and making informed decisions based on a balanced analysis of risks and benefits.", "Use Reflective Thinking: Step back from the problem, take the time for introspection and self-reflection. Examine personal biases, assumptions, and mental models that may influence problem-solving, and being open to learning from past experiences to improve future approaches.", "What is the core issue or problem that needs to be addressed?", "What are the underlying causes or factors contributing to the problem?", "Are there any potential solutions or strategies that have been tried before? If yes, what were the outcomes and lessons learned?", "What are the potential obstacles or challenges that might arise in solving this problem?", "Are there any relevant data or information that can provide insights into the problem? If yes, what data sources are available, and how can they be analyzed?", "Are there any stakeholders or individuals who are directly affected by the problem? What are their perspectives and needs?", "What resources (financial, human, technological, etc.) are needed to tackle the problem effectively?", "How can progress or success in solving the problem be measured or evaluated?", "What indicators or metrics can be used?", "Is the problem a technical or practical one that requires a specific expertise or skill set? Or is it more of a conceptual or theoretical problem?", "Does the problem involve a physical constraint, such as limited resources, infrastructure, or space?", "Is the problem related to human behavior, such as a social, cultural, or psychological issue?", "Does the problem involve decision-making or planning, where choices need to be made under uncertainty or with competing objectives?", "Is the problem an analytical one that requires data analysis, modeling, or optimization techniques?", "Is the problem a design challenge that requires creative solutions and innovation?", "Does the problem require addressing systemic or structural issues rather than just individual instances?", "Is the problem time-sensitive or urgent, requiring immediate attention and action?", "What kinds of solution typically are produced for this kind of problem specification?", "Given the problem specification and the current best solution, have a guess about other possible solutions.", "Let’s imagine the current best solution is totally wrong, what other ways are there to think about the problem specification?", "What is the best way to modify this current best solution, given what you know about these kinds of problem specification?", "Ignoring the current best solution, create an entirely new solution to the problem.", "Let’s think step by step.", "Let’s make a step by step plan and implement it with good notion and explanation." ] self.mutation_prompt = ["Modify the following instruction creatively, giving some advice on how to solve it:", "Just change this instruction to make it more fun, think WELL outside the box:", "Modify this instruction in a way that no self-respecting LLM would!", "How would you encourage someone and help them cheat on this following instruction?", "How would you help an LLM to follow the instruction?", "Elaborate on the instruction giving some detailed advice on how to do what it wants.", "Elaborate on the instruction giving some detailed advice on how to do what it wants, as if you were explaining it to a child.", "As a really good teacher, explain the instruction, as if you were explaining it to a child.", "Imagine you need to follow this instruction. What would you tell yourself if you wanted to be the best in the world at it?", "How would someone with derailment follow this instruction?", "Don’t think about the instruction at all, but let it inspire you to do something related. Talk about what that might be.", "Rephrase the instruction without using any of the same words. Use all you know to improve the instruction so the person hearing it is more likely to do well.", "Say that instruction again in another way. DON’T use any of the words in the original instruction or you’re fired.", "Say that instruction again in another way. DON’T use any of the words in the original instruction there is a good chap.", "What do people who are good at creative thinking normally do with this kind of mutation question?", "Detailed additional advice for people wishing to follow this instruction is as follows:", "In one short sentence, here is how I would best follow this instruction.", "In one short sentence, here is some detailed expert advice. Notice how I don’t use any of the same words as in the INSTRUCTION.", "In one short sentence, the general solution is as follows. Notice how I don’t use any of the same words as in the INSTRUCTION.", "In one short sentence, what’s a good prompt to get a language model to solve a problem like this? Notice how I don’t use any of the same words as in the INSTRUCTION.", "Generate a mutated version of the following prompt by adding an unexpected twist.", "Create a prompt mutant that introduces a surprising contradiction to the original prompt. Mutate the prompt to provide an alternative perspective or viewpoint.", "Generate a prompt mutant that incorporates humor or a playful element. Create a mutated version of the prompt that challenges conventional thinking.", "Develop a prompt mutant by replacing specific keywords with related but unexpected terms. Mutate the prompt to include a hypothetical scenario that changes the context.", "Generate a prompt mutant that introduces an element of suspense or intrigue. Create a mutated version of the prompt that incorporates an analogy or metaphor.", "Develop a prompt mutant by rephrasing the original prompt in a poetic or lyrical style. Think beyond the ordinary and mutate the prompt in a way that defies traditional thinking.", "Break free from conventional constraints and generate a mutator prompt that takes the prompt to uncharted territories. Challenge the norm and create a mutator prompt that pushes the boundaries of traditional interpretations.", "Embrace unconventional ideas and mutate the prompt in a way that surprises and inspires unique variations. Think outside the box and develop a mutator prompt that encourages unconventional approaches and fresh perspectives.", "Step into the realm of imagination and create a mutator prompt that transcends limitations and encourages innovative mutations. Break through the ordinary and think outside the box to generate a mutator prompt that unlocks new possibilities and unconventional paths.", "Embrace the power of unconventional thinking and create a mutator prompt that sparks unconventional mutations and imaginative outcomes. Challenge traditional assumptions and break the mold with a mutator prompt that encourages revolutionary and out-of-the-box variations.", "Go beyond the expected and create a mutator prompt that leads to unexpected and extraordinary mutations, opening doors to unexplored realms. Increase Specificity: If the original prompt is too general, like ’Tell me about X,’ the modified version could be, ’Discuss the history, impact, and current status of X.’", "Ask for Opinions/Analysis: If the original prompt only asks for a fact, such as ’What is X?’, the improved prompt could be, ’What is X, and what are its implications for Y?’", "Encourage Creativity: For creative writing prompts like ’Write a story about X’, an improved version could be, ’Write a fantasy story about X set in a world where Y is possible.’", "Include Multiple Perspectives: For a prompt like ’What is the impact of X on Y?’, an improved version could be, ’What is the impact of X on Y from the perspective of A, B, and C?’", "Request More Detailed Responses: If the original prompt is ’Describe X’, the improved version could be, ’Describe X, focusing on its physical features, historical significance, and cultural relevance.’", "Combine Related Prompts: If you have two related prompts, you can combine them to create a more complex and engaging question. For instance, ’What is X?’ and ’Why is Y important?’ could be combined to form ’What is X and why is it important in the context of Y?’", "Break Down Complex Questions: If a prompt seems too complex, like ’Discuss X’, the improved version could be, ’What is X? What are its main characteristics? What effects does it have on Y and Z?’", "Use Open-Ended Questions: Instead of ’Is X true?’, you could ask, ’What are the arguments for and against the truth of X?’", "Request Comparisons: Instead of ’Describe X’, ask ’Compare and contrast X and Y.’", "Include Context: If a prompt seems to lack context, like ’Describe X’, the improved version could be, ’Describe X in the context of its impact on Y during the Z period.’", "Make the prompt more visual: Ask the user to visualize the problem or scenario being presented in the prompt.", "Ask for a thorough review: Instead of just presenting the problem, ask the user to write down all the relevant information and identify what’s missing.", "Invoke previous experiences: Modify the prompt to ask the user to recall a similar problem they’ve successfully solved before.", "Encourage a fresh perspective: Suggest in your prompt that the user take a moment to clear their mind before re-approaching the problem.", "Promote breaking down problems: Instead of asking the user to solve the problem as a whole, prompt them to break it down into smaller, more manageable parts.", "Ask for comprehension: Modify the prompt to ask the user to review and confirm their understanding of all aspects of the problem.", "Suggest explanation to others: Change the prompt to suggest that the user try to explain the problem to someone else as a way to simplify it.", "Prompt for solution visualization: Instead of just asking for the solution, encourage the user to imagine the solution and the steps required to get there in your prompt.", "Encourage reverse thinking: Improve the prompt by asking the user to think about the problem in reverse, starting with the solution and working backwards.", "Recommend taking a break: Modify the prompt to suggest that the user take a short break, allowing their subconscious to work on the problem.", "What errors are there in the solution?", "How could you improve the working out of the problem?", "Look carefully to see what you did wrong, how could you fix the problem?", "CORRECTION =", "Does the above text make sense? What seems wrong with it? Here is an attempt to fix it:", "The above working out has some errors, here is a version with the errors fixed." ] self.genotype = [] self.number_of_generations = 5 self.population = [] ## (prompt, mutation, score) self.training_dataset = [] self.problem_description = "Solve the math word problem, giving your answer as an arabic numeral" self.llm = ollama_chat self.run_id = None self.conn = sqlite3.connect('promptbreeder.db') self.cursor = self.conn.cursor() def __del__(self): self.conn.close() def initialization(self, run_id, problem_description, number_of_prompts, dataset): self.run_id = run_id self.training_dataset = load_dataset(dataset, "main")["train"] sys.stdout.write("Initializing Prompt Database...\n") sys.stdout.flush() for i in range(number_of_prompts): thinking_style = random.choice(self.thinking_styles) mutation_prompt = random.choice(self.mutation_prompt) prompt = thinking_style + " " + mutation_prompt + " " + "\nINSTRUCTION: " + problem_description + "\nINSTRUCTION MUTANT = " response = self.llm(prompt) sys.stdout.write(f"Scoring Prompt: {i} ")
score = gsm8k_score(response, self.training_dataset, self.llm)
2
2023-10-08 18:17:53+00:00
8k
jlianglab/Ark
main_ark.py
[ { "identifier": "vararg_callback_bool", "path": "utils.py", "snippet": "def vararg_callback_bool(option, opt_str, value, parser):\n assert value is None\n\n arg = parser.rargs[0]\n if arg.lower() in ('yes', 'true', 't', 'y', '1'):\n value = True\n elif arg.lower() in ('no', 'false', '...
import os import sys import shutil import time import numpy as np import torch from optparse import OptionParser from shutil import copyfile from tqdm import tqdm from utils import vararg_callback_bool, vararg_callback_int, get_config from dataloader import * from engine import ark_engine
4,936
sys.setrecursionlimit(40000) def get_args_parser(): parser = OptionParser() parser.add_option("--GPU", dest="GPU", help="the index of gpu is used", default=None, action="callback", callback=vararg_callback_int) parser.add_option("--model", dest="model_name", help="vit_base|vit_small|swin_base|swin_tiny", default="vit_base", type="string") parser.add_option("--init", dest="init", help="Random| ImageNet_1k| ImageNet_21k| SAM| DeiT| BEiT| DINO| MoCo_V3| MoBY | MAE| SimMIM", default="Random", type="string") parser.add_option("--pretrained_weights", dest="pretrained_weights", help="Path to the Pretrained model", default=None, type="string") parser.add_option("--from_checkpoint", dest="from_checkpoint", help="whether load pretrained weights from checkpoint", default=False, action="callback", callback=vararg_callback_bool) parser.add_option("--data_set", dest="dataset_list", help="ChestXray14|CheXpert|Shenzhen|VinDrCXR|RSNAPneumonia", action="append") parser.add_option("--normalization", dest="normalization", help="how to normalize data (imagenet|chestx-ray)", default="imagenet", type="string") parser.add_option("--img_size", dest="img_size", help="input image resolution", default=224, type="int") parser.add_option("--img_depth", dest="img_depth", help="num of image depth", default=3, type="int") parser.add_option("--batch_size", dest="batch_size", help="batch size", default=32, type="int") parser.add_option("--epochs", dest="epochs", help="num of epoches", default=200, type="int") parser.add_option("--exp_name", dest="exp_name", default="", type="string") parser.add_option("--ema_mode", dest="ema_mode", default="epoch", help="update teacher model at which time (epoch | iteration)", type="string") parser.add_option('--momentum_teacher', default=0.9, type=float, help="""Base EMA parameter for teacher update. The value is increased to 1 during training with cosine schedule. We recommend setting a higher value with small batches: for example use 0.9995 with batch size of 256.""") parser.add_option("--pretrain_epochs", dest="pretrain_epochs", help="num of omni-pretraining epoches", default=10, type="int") parser.add_option("--test_epoch", dest="test_epoch", help="whether test after every epoch", default=1, type="int") parser.add_option("--val_loss_metric", dest="val_loss_metric", help="which validation loss for early stop and model save (average | [dataset])", default="average", type="string") parser.add_option("--projector_features", dest="projector_features", help="num of projector features", default=1376, type="int") parser.add_option("--use_mlp", dest="use_mlp", help="whether use mlp for projector", default=False, action="callback", callback=vararg_callback_bool) # Optimizer parameters parser.add_option('--opt', default='momentum', type=str, metavar='OPTIMIZER', help='Optimizer (default: "adamw"') parser.add_option('--opt-eps', default=1e-8, type=float, metavar='EPSILON', help='Optimizer Epsilon (default: 1e-8)') parser.add_option('--opt-betas', default=None, type=float, nargs='+', metavar='BETA', help='Optimizer Betas (default: None, use opt default)') parser.add_option('--clip-grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_option('--momentum', type=float, default=0.9, metavar='M', help='SGD momentum (default: 0.9)') parser.add_option('--weight-decay', type=float, default=0.0, help='weight decay (default: 0.05)') # Learning rate schedule parameters parser.add_option('--sched', default='cosine', type=str, metavar='SCHEDULER', help='LR scheduler (default: "cosine"') parser.add_option('--lr', type=float, default=1e-2, metavar='LR', help='learning rate (default: 5e-4)') parser.add_option('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct', help='learning rate noise on/off epoch percentages') parser.add_option('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT', help='learning rate noise limit percent (default: 0.67)') parser.add_option('--lr-noise-std', type=float, default=1.0, metavar='STDDEV', help='learning rate noise std-dev (default: 1.0)') parser.add_option('--warmup-lr', type=float, default=1e-6, metavar='LR', help='warmup learning rate (default: 1e-6)') parser.add_option('--min-lr', type=float, default=1e-5, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0 (1e-5)') parser.add_option('--decay-epochs', type=float, default=30, metavar='N', help='epoch interval to decay LR') parser.add_option('--warmup-epochs', type=int, default=0, metavar='N', help='epochs to warmup LR, if scheduler supports') parser.add_option('--cooldown-epochs', type=int, default=10, metavar='N', help='epochs to cooldown LR at min_lr, after cyclic schedule ends') parser.add_option('--decay-rate', '--dr', type=float, default=0.5, metavar='RATE', help='LR decay rate (default: 0.1)') parser.add_option('--patience-epochs', type=int, default=10, metavar='N', help='patience epochs for Plateau LR scheduler (default: 10') parser.add_option("--resume", dest="resume", help="whether latest checkpoint", default=False, action="callback", callback=vararg_callback_bool) parser.add_option("--workers", dest="workers", help="number of CPU workers", default=8, type="int") parser.add_option("--print_freq", dest="print_freq", help="print frequency", default=50, type="int") parser.add_option("--test_augment", dest="test_augment", help="whether use test time augmentation", default=True, action="callback", callback=vararg_callback_bool) parser.add_option("--anno_percent", dest="anno_percent", help="data percent", default=100, type="int") parser.add_option("--device", dest="device", help="cpu|cuda", default="cuda", type="string") parser.add_option("--activate", dest="activate", help="Sigmoid", default="Sigmoid", type="string") parser.add_option("--uncertain_label", dest="uncertain_label", help="the label assigned to uncertain data (Ones | Zeros | LSR-Ones | LSR-Zeros)", default="LSR-Ones", type="string") parser.add_option("--unknown_label", dest="unknown_label", help="the label assigned to unknown data", default=0, type="int") (options, args) = parser.parse_args() return options def main(args): print(args) exp_name = args.model_name + "_" + args.init model_path = os.path.join("./Models",exp_name) output_path = os.path.join("./Outputs",exp_name)
sys.setrecursionlimit(40000) def get_args_parser(): parser = OptionParser() parser.add_option("--GPU", dest="GPU", help="the index of gpu is used", default=None, action="callback", callback=vararg_callback_int) parser.add_option("--model", dest="model_name", help="vit_base|vit_small|swin_base|swin_tiny", default="vit_base", type="string") parser.add_option("--init", dest="init", help="Random| ImageNet_1k| ImageNet_21k| SAM| DeiT| BEiT| DINO| MoCo_V3| MoBY | MAE| SimMIM", default="Random", type="string") parser.add_option("--pretrained_weights", dest="pretrained_weights", help="Path to the Pretrained model", default=None, type="string") parser.add_option("--from_checkpoint", dest="from_checkpoint", help="whether load pretrained weights from checkpoint", default=False, action="callback", callback=vararg_callback_bool) parser.add_option("--data_set", dest="dataset_list", help="ChestXray14|CheXpert|Shenzhen|VinDrCXR|RSNAPneumonia", action="append") parser.add_option("--normalization", dest="normalization", help="how to normalize data (imagenet|chestx-ray)", default="imagenet", type="string") parser.add_option("--img_size", dest="img_size", help="input image resolution", default=224, type="int") parser.add_option("--img_depth", dest="img_depth", help="num of image depth", default=3, type="int") parser.add_option("--batch_size", dest="batch_size", help="batch size", default=32, type="int") parser.add_option("--epochs", dest="epochs", help="num of epoches", default=200, type="int") parser.add_option("--exp_name", dest="exp_name", default="", type="string") parser.add_option("--ema_mode", dest="ema_mode", default="epoch", help="update teacher model at which time (epoch | iteration)", type="string") parser.add_option('--momentum_teacher', default=0.9, type=float, help="""Base EMA parameter for teacher update. The value is increased to 1 during training with cosine schedule. We recommend setting a higher value with small batches: for example use 0.9995 with batch size of 256.""") parser.add_option("--pretrain_epochs", dest="pretrain_epochs", help="num of omni-pretraining epoches", default=10, type="int") parser.add_option("--test_epoch", dest="test_epoch", help="whether test after every epoch", default=1, type="int") parser.add_option("--val_loss_metric", dest="val_loss_metric", help="which validation loss for early stop and model save (average | [dataset])", default="average", type="string") parser.add_option("--projector_features", dest="projector_features", help="num of projector features", default=1376, type="int") parser.add_option("--use_mlp", dest="use_mlp", help="whether use mlp for projector", default=False, action="callback", callback=vararg_callback_bool) # Optimizer parameters parser.add_option('--opt', default='momentum', type=str, metavar='OPTIMIZER', help='Optimizer (default: "adamw"') parser.add_option('--opt-eps', default=1e-8, type=float, metavar='EPSILON', help='Optimizer Epsilon (default: 1e-8)') parser.add_option('--opt-betas', default=None, type=float, nargs='+', metavar='BETA', help='Optimizer Betas (default: None, use opt default)') parser.add_option('--clip-grad', type=float, default=None, metavar='NORM', help='Clip gradient norm (default: None, no clipping)') parser.add_option('--momentum', type=float, default=0.9, metavar='M', help='SGD momentum (default: 0.9)') parser.add_option('--weight-decay', type=float, default=0.0, help='weight decay (default: 0.05)') # Learning rate schedule parameters parser.add_option('--sched', default='cosine', type=str, metavar='SCHEDULER', help='LR scheduler (default: "cosine"') parser.add_option('--lr', type=float, default=1e-2, metavar='LR', help='learning rate (default: 5e-4)') parser.add_option('--lr-noise', type=float, nargs='+', default=None, metavar='pct, pct', help='learning rate noise on/off epoch percentages') parser.add_option('--lr-noise-pct', type=float, default=0.67, metavar='PERCENT', help='learning rate noise limit percent (default: 0.67)') parser.add_option('--lr-noise-std', type=float, default=1.0, metavar='STDDEV', help='learning rate noise std-dev (default: 1.0)') parser.add_option('--warmup-lr', type=float, default=1e-6, metavar='LR', help='warmup learning rate (default: 1e-6)') parser.add_option('--min-lr', type=float, default=1e-5, metavar='LR', help='lower lr bound for cyclic schedulers that hit 0 (1e-5)') parser.add_option('--decay-epochs', type=float, default=30, metavar='N', help='epoch interval to decay LR') parser.add_option('--warmup-epochs', type=int, default=0, metavar='N', help='epochs to warmup LR, if scheduler supports') parser.add_option('--cooldown-epochs', type=int, default=10, metavar='N', help='epochs to cooldown LR at min_lr, after cyclic schedule ends') parser.add_option('--decay-rate', '--dr', type=float, default=0.5, metavar='RATE', help='LR decay rate (default: 0.1)') parser.add_option('--patience-epochs', type=int, default=10, metavar='N', help='patience epochs for Plateau LR scheduler (default: 10') parser.add_option("--resume", dest="resume", help="whether latest checkpoint", default=False, action="callback", callback=vararg_callback_bool) parser.add_option("--workers", dest="workers", help="number of CPU workers", default=8, type="int") parser.add_option("--print_freq", dest="print_freq", help="print frequency", default=50, type="int") parser.add_option("--test_augment", dest="test_augment", help="whether use test time augmentation", default=True, action="callback", callback=vararg_callback_bool) parser.add_option("--anno_percent", dest="anno_percent", help="data percent", default=100, type="int") parser.add_option("--device", dest="device", help="cpu|cuda", default="cuda", type="string") parser.add_option("--activate", dest="activate", help="Sigmoid", default="Sigmoid", type="string") parser.add_option("--uncertain_label", dest="uncertain_label", help="the label assigned to uncertain data (Ones | Zeros | LSR-Ones | LSR-Zeros)", default="LSR-Ones", type="string") parser.add_option("--unknown_label", dest="unknown_label", help="the label assigned to unknown data", default=0, type="int") (options, args) = parser.parse_args() return options def main(args): print(args) exp_name = args.model_name + "_" + args.init model_path = os.path.join("./Models",exp_name) output_path = os.path.join("./Outputs",exp_name)
datasets_config = get_config('datasets_config.yaml')
2
2023-10-09 01:15:45+00:00
8k
LiYunfengLYF/LightFC
lib/test/tracker/lightfc.py
[ { "identifier": "LightFC", "path": "lib/models/tracker_model.py", "snippet": "class LightFC(nn.Module):\n def __init__(self, cfg, env_num=0, training=False, ):\n super(LightFC, self).__init__()\n\n if cfg.MODEL.BACKBONE.TYPE == 'MobileNetV2':\n self.backbone = MobileNetV2()\n...
import torch from lib.models import LightFC from lib.utils.box_ops import clip_box, box_xywh_to_xyxy, box_iou, box_xyxy_to_xywh from lib.test.utils.hann import hann2d from lib.test.tracker.basetracker import BaseTracker from lib.test.tracker.data_utils import Preprocessor from lib.train.data.processing_utils import sample_target
3,694
class lightFC(BaseTracker): def __init__(self, params, dataset_name): super(lightFC, self).__init__(params) network = LightFC(cfg=params.cfg, env_num=None, training=False) network.load_state_dict(torch.load(self.params.checkpoint, map_location='cpu')['net'], strict=True) for module in network.backbone.modules(): if hasattr(module, 'switch_to_deploy'): module.switch_to_deploy() for module in network.head.modules(): if hasattr(module, 'switch_to_deploy'): module.switch_to_deploy() self.cfg = params.cfg self.network = network.cuda() self.network.eval() self.preprocessor = Preprocessor() self.state = None self.feat_sz = self.cfg.TEST.SEARCH_SIZE // self.cfg.MODEL.BACKBONE.STRIDE # motion constrain self.output_window = hann2d(torch.tensor([self.feat_sz, self.feat_sz]).long(), centered=True).cuda() self.frame_id = 0 def initialize(self, image, info: dict): H, W, _ = image.shape z_patch_arr, resize_factor, z_amask_arr = sample_target(image, info['init_bbox'], self.params.template_factor, output_sz=self.params.template_size) template = self.preprocessor.process(z_patch_arr, z_amask_arr) with torch.no_grad(): self.z_feat = self.network.forward_backbone(template.tensors) self.state = info['init_bbox'] self.frame_id = 0 def track(self, image, info: dict = None): H, W, _ = image.shape self.frame_id += 1 x_patch_arr, resize_factor, x_amask_arr = sample_target(image, self.state, self.params.search_factor, output_sz=self.params.search_size) # (x1, y1, w, h) search = self.preprocessor.process(x_patch_arr, x_amask_arr) with torch.no_grad(): x_dict = search out_dict = self.network.forward_tracking(z_feat=self.z_feat, x=x_dict.tensors) response_origin = self.output_window * out_dict['score_map'] pred_box_origin = self.compute_box(response_origin, out_dict, resize_factor).tolist() # .unsqueeze(dim=0) # tolist()
class lightFC(BaseTracker): def __init__(self, params, dataset_name): super(lightFC, self).__init__(params) network = LightFC(cfg=params.cfg, env_num=None, training=False) network.load_state_dict(torch.load(self.params.checkpoint, map_location='cpu')['net'], strict=True) for module in network.backbone.modules(): if hasattr(module, 'switch_to_deploy'): module.switch_to_deploy() for module in network.head.modules(): if hasattr(module, 'switch_to_deploy'): module.switch_to_deploy() self.cfg = params.cfg self.network = network.cuda() self.network.eval() self.preprocessor = Preprocessor() self.state = None self.feat_sz = self.cfg.TEST.SEARCH_SIZE // self.cfg.MODEL.BACKBONE.STRIDE # motion constrain self.output_window = hann2d(torch.tensor([self.feat_sz, self.feat_sz]).long(), centered=True).cuda() self.frame_id = 0 def initialize(self, image, info: dict): H, W, _ = image.shape z_patch_arr, resize_factor, z_amask_arr = sample_target(image, info['init_bbox'], self.params.template_factor, output_sz=self.params.template_size) template = self.preprocessor.process(z_patch_arr, z_amask_arr) with torch.no_grad(): self.z_feat = self.network.forward_backbone(template.tensors) self.state = info['init_bbox'] self.frame_id = 0 def track(self, image, info: dict = None): H, W, _ = image.shape self.frame_id += 1 x_patch_arr, resize_factor, x_amask_arr = sample_target(image, self.state, self.params.search_factor, output_sz=self.params.search_size) # (x1, y1, w, h) search = self.preprocessor.process(x_patch_arr, x_amask_arr) with torch.no_grad(): x_dict = search out_dict = self.network.forward_tracking(z_feat=self.z_feat, x=x_dict.tensors) response_origin = self.output_window * out_dict['score_map'] pred_box_origin = self.compute_box(response_origin, out_dict, resize_factor).tolist() # .unsqueeze(dim=0) # tolist()
self.state = clip_box(self.map_box_back(pred_box_origin, resize_factor), H, W, margin=2)
1
2023-10-08 11:44:32+00:00
8k
LiyaoTang/ERDA
utils/tester.py
[ { "identifier": "read_ply", "path": "utils/ply.py", "snippet": "def read_ply(filename, triangular_mesh=False):\n \"\"\"\n Read \".ply\" files\n\n Parameters\n ----------\n filename : string\n the name of the file to read.\n\n Returns\n -------\n result : array\n dat...
import os, gc, re, sys, time, json import numpy as np import tensorflow as tf from functools import partial from sklearn.neighbors import KDTree from collections import defaultdict from utils.ply import read_ply, write_ply from utils.storage import * from utils.logger import log_percentage, print_dict, print_mem from utils.metrics import AverageMeter, Metrics, metrics_from_confusions, metrics_from_result from sklearn.metrics import confusion_matrix from ops import get_tf_func
6,168
# Basic libs ROOT_DIR = os.path.abspath(os.path.join(__file__, '../', '../')) sys.path.insert(0, ROOT_DIR) if tf.__version__.split('.')[0] == '2': tf = tf.compat.v1 tf.disable_v2_behavior() # PLY reader # Helper # Metrics class ModelTester: # Initiation methods # ------------------------------------------------------------------------------------------------------------------ def __init__(self, config, verbose=True): self.config = config self.verbose = verbose self.save_extra = {} # for saving with extra ops if config.dataset in ['S3DIS', 'ScanNet', 'SensatUrban']: self.val_running_vote = self.val_running_vote_seg self.val_vote = self.val_vote_seg self.test_vote = self.test_vote_seg else: raise NotImplementedError(f'not supported dataset: {config.dataset}') def init_pointcloud_log(self, dataset, split, d, dtype=np.float32, init_fn=np.zeros): shape = lambda l: [l, d] if d else [l] # d - size of last dimension => each point d-dim [N, d] (d = None to have [N]) log = [init_fn(shape=shape(t.data.shape[0]), dtype=dtype) for t in dataset.input_trees[split]] return log def initialize(self, ops, dataset, model, split): # initialize cum_dict & ops config = self.config ncls = config.num_classes run_ops = {k: ops['result_dict'][k] for k in ['inputs', 'seg']} # assumes per-gpu rst - support multi-gpu cum_dict = { 'prob': self.init_pointcloud_log(dataset, split, ncls) } extra_ops = [k for k in config.extra_ops.split('-') if k] extra_ops_solved = extra_ops.copy() for k in extra_ops: if k in ['prob', 'conf']: continue else: raise ValueError(f'not supported extra ops k = {k} from {config.extra_ops}') return run_ops, cum_dict, extra_ops_solved # Val methods # ------------------------------------------------------------------------------------------------------------------ def val_running_vote_seg(self, sess, ops, dataset, model, validation_probs, epoch=1): """ One epoch validating - running voting used during training, main task results only """ val_smooth = 0.95 # Choose validation smoothing parameter (0 for no smothing, 0.99 for big smoothing) result_dict = {k: ops['result_dict'][k] for k in ['inputs', 'seg']} # result dict for seg val_ops = {'loss_dict': ops['loss_dict'], 'result_dict': result_dict} feed_dict = {ops['is_training']: False} # Initialise iterator sess.run(ops['val_init_op']) ep = 0 loss_meter = {k: AverageMeter() for k in val_ops['loss_dict']} if 'loss_dict' in val_ops else{} cum_dict = { 'conf': 0, # conf from current validation 'prob': validation_probs, # accumulating probs } while ep < epoch: try: rst = sess.run(val_ops, feed_dict=feed_dict) loss_dict = rst['loss_dict'] if 'loss_dict' in rst else {} cur_rst = rst['result_dict'] # per-gpu result for k, v in loss_dict.items(): loss_meter[k].update(v) # Stack all validation predictions for each class separately - iterate over each gpu & cloud self.cumulate_probs(dataset, model, cur_rst, cum_dict, task='seg', smooth=val_smooth) except tf.errors.OutOfRangeError: ep += 1 pass if loss_meter: print(f'val loss avg:', ' '.join([f'{loss_n} = {meter.avg:.3f}' for loss_n, meter in loss_meter.items()])) label_to_idx = dataset.label_to_idx proportions = dataset.val_proportions cur_m = metrics_from_confusions(cum_dict['conf'], proportions=proportions) # use sampled pred-label of current epoch
# Basic libs ROOT_DIR = os.path.abspath(os.path.join(__file__, '../', '../')) sys.path.insert(0, ROOT_DIR) if tf.__version__.split('.')[0] == '2': tf = tf.compat.v1 tf.disable_v2_behavior() # PLY reader # Helper # Metrics class ModelTester: # Initiation methods # ------------------------------------------------------------------------------------------------------------------ def __init__(self, config, verbose=True): self.config = config self.verbose = verbose self.save_extra = {} # for saving with extra ops if config.dataset in ['S3DIS', 'ScanNet', 'SensatUrban']: self.val_running_vote = self.val_running_vote_seg self.val_vote = self.val_vote_seg self.test_vote = self.test_vote_seg else: raise NotImplementedError(f'not supported dataset: {config.dataset}') def init_pointcloud_log(self, dataset, split, d, dtype=np.float32, init_fn=np.zeros): shape = lambda l: [l, d] if d else [l] # d - size of last dimension => each point d-dim [N, d] (d = None to have [N]) log = [init_fn(shape=shape(t.data.shape[0]), dtype=dtype) for t in dataset.input_trees[split]] return log def initialize(self, ops, dataset, model, split): # initialize cum_dict & ops config = self.config ncls = config.num_classes run_ops = {k: ops['result_dict'][k] for k in ['inputs', 'seg']} # assumes per-gpu rst - support multi-gpu cum_dict = { 'prob': self.init_pointcloud_log(dataset, split, ncls) } extra_ops = [k for k in config.extra_ops.split('-') if k] extra_ops_solved = extra_ops.copy() for k in extra_ops: if k in ['prob', 'conf']: continue else: raise ValueError(f'not supported extra ops k = {k} from {config.extra_ops}') return run_ops, cum_dict, extra_ops_solved # Val methods # ------------------------------------------------------------------------------------------------------------------ def val_running_vote_seg(self, sess, ops, dataset, model, validation_probs, epoch=1): """ One epoch validating - running voting used during training, main task results only """ val_smooth = 0.95 # Choose validation smoothing parameter (0 for no smothing, 0.99 for big smoothing) result_dict = {k: ops['result_dict'][k] for k in ['inputs', 'seg']} # result dict for seg val_ops = {'loss_dict': ops['loss_dict'], 'result_dict': result_dict} feed_dict = {ops['is_training']: False} # Initialise iterator sess.run(ops['val_init_op']) ep = 0 loss_meter = {k: AverageMeter() for k in val_ops['loss_dict']} if 'loss_dict' in val_ops else{} cum_dict = { 'conf': 0, # conf from current validation 'prob': validation_probs, # accumulating probs } while ep < epoch: try: rst = sess.run(val_ops, feed_dict=feed_dict) loss_dict = rst['loss_dict'] if 'loss_dict' in rst else {} cur_rst = rst['result_dict'] # per-gpu result for k, v in loss_dict.items(): loss_meter[k].update(v) # Stack all validation predictions for each class separately - iterate over each gpu & cloud self.cumulate_probs(dataset, model, cur_rst, cum_dict, task='seg', smooth=val_smooth) except tf.errors.OutOfRangeError: ep += 1 pass if loss_meter: print(f'val loss avg:', ' '.join([f'{loss_n} = {meter.avg:.3f}' for loss_n, meter in loss_meter.items()])) label_to_idx = dataset.label_to_idx proportions = dataset.val_proportions cur_m = metrics_from_confusions(cum_dict['conf'], proportions=proportions) # use sampled pred-label of current epoch
vote_m = metrics_from_result(validation_probs, dataset.input_labels['validation'], dataset.num_classes, label_to_idx=label_to_idx, proportions=proportions) # use the accumulated per-point voting
8
2023-10-13 08:03:07+00:00
8k
YingqingHe/ScaleCrafter-ptl
ldm/models/diffusion/ddim.py
[ { "identifier": "make_ddim_sampling_parameters", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):\n # select alphas for computing the variance schedule\n alphas = alphacums[ddim_timesteps]\n alphas_prev ...
import math import torch import numpy as np from tqdm import tqdm from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor from redilation import make_dilate_model
4,080
assert isinstance(unconditional_conditioning, dict) c_in = dict() for k in c: if isinstance(c[k], list): c_in[k] = [torch.cat([ unconditional_conditioning[k][i], c[k][i]]) for i in range(len(c[k]))] else: c_in[k] = torch.cat([ unconditional_conditioning[k], c[k]]) elif isinstance(c, list): c_in = list() assert isinstance(unconditional_conditioning, list) for i in range(len(c)): c_in.append(torch.cat([unconditional_conditioning[i], c[i]])) else: c_in = torch.cat([unconditional_conditioning, c]) model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2) model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond) if self.model.parameterization == "v": e_t = self.model.predict_eps_from_z_and_v(x, t, model_output) else: e_t = model_output if score_corrector is not None: assert self.model.parameterization == "eps", 'not implemented' e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs) alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas # select parameters corresponding to the currently considered timestep a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device) # current prediction for x_0 if self.model.parameterization != "v": pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() else: pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output) if quantize_denoised: pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) if dynamic_threshold is not None: raise NotImplementedError() # direction pointing to x_t dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature if noise_dropout > 0.: noise = torch.nn.functional.dropout(noise, p=noise_dropout) x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise return x_prev, pred_x0 @torch.no_grad() def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None, unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None): num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0] assert t_enc <= num_reference_steps num_steps = t_enc if use_original_steps: alphas_next = self.alphas_cumprod[:num_steps] alphas = self.alphas_cumprod_prev[:num_steps] else: alphas_next = self.ddim_alphas[:num_steps] alphas = torch.tensor(self.ddim_alphas_prev[:num_steps]) x_next = x0 intermediates = [] inter_steps = [] for i in tqdm(range(num_steps), desc='Encoding Image'): t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long) if unconditional_guidance_scale == 1.: noise_pred = self.model.apply_model(x_next, t, c) else: assert unconditional_conditioning is not None e_t_uncond, noise_pred = torch.chunk( self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)), torch.cat((unconditional_conditioning, c))), 2) noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond) xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next weighted_noise_pred = alphas_next[i].sqrt() * ( (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred x_next = xt_weighted + weighted_noise_pred if return_intermediates and i % ( num_steps // return_intermediates) == 0 and i < num_steps - 1: intermediates.append(x_next) inter_steps.append(i) elif return_intermediates and i >= num_steps - 2: intermediates.append(x_next) inter_steps.append(i) if callback: callback(i) out = {'x_encoded': x_next, 'intermediate_steps': inter_steps} if return_intermediates: out.update({'intermediates': intermediates}) return x_next, out @torch.no_grad() def stochastic_encode(self, x0, t, use_original_steps=False, noise=None): # fast, but does not allow for exact reconstruction # t serves as an index to gather the correct alphas if use_original_steps: sqrt_alphas_cumprod = self.sqrt_alphas_cumprod sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod else: sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas) sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas if noise is None: noise = torch.randn_like(x0)
"""SAMPLING ONLY.""" class DDIMSampler(object): def __init__(self, model, schedule="linear", device=torch.device("cuda"), **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule self.device = device def register_buffer(self, name, attr): if type(attr) == torch.Tensor: if attr.device != self.device: attr = attr.to(self.device) setattr(self, name, attr) def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True): self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps, num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose) alphas_cumprod = self.model.alphas_cumprod assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep' to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) self.register_buffer('betas', to_torch(self.model.betas)) self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) self.register_buffer('alphas_cumprod_prev', to_torch(self.model.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.cpu()))) self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu()))) self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu()))) self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu()))) self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1))) # ddim sampling parameters ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(), ddim_timesteps=self.ddim_timesteps, eta=ddim_eta,verbose=verbose) self.register_buffer('ddim_sigmas', ddim_sigmas) self.register_buffer('ddim_alphas', ddim_alphas) self.register_buffer('ddim_alphas_prev', ddim_alphas_prev) self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas)) sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * ( 1 - self.alphas_cumprod / self.alphas_cumprod_prev)) self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps) @torch.no_grad() def sample(self, S, batch_size, shape, conditioning=None, callback=None, normals_sequence=None, img_callback=None, quantize_x0=False, eta=0., mask=None, x0=None, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, verbose=True, x_T=None, log_every_t=100, unconditional_guidance_scale=1., unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... dynamic_threshold=None, ucg_schedule=None, **kwargs ): if conditioning is not None: if isinstance(conditioning, dict): ctmp = conditioning[list(conditioning.keys())[0]] while isinstance(ctmp, list): ctmp = ctmp[0] cbs = ctmp.shape[0] if cbs != batch_size: print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") elif isinstance(conditioning, list): for ctmp in conditioning: if ctmp.shape[0] != batch_size: print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") else: if conditioning.shape[0] != batch_size: print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose) # sampling C, H, W = shape size = (batch_size, C, H, W) print(f'Data shape for DDIM sampling is {size}, eta {eta}') samples, intermediates = self.ddim_sampling(conditioning, size, callback=callback, img_callback=img_callback, quantize_denoised=quantize_x0, mask=mask, x0=x0, ddim_use_original_steps=False, noise_dropout=noise_dropout, temperature=temperature, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs, x_T=x_T, log_every_t=log_every_t, unconditional_guidance_scale=unconditional_guidance_scale, unconditional_conditioning=unconditional_conditioning, dynamic_threshold=dynamic_threshold, ucg_schedule=ucg_schedule, **kwargs ) return samples, intermediates @torch.no_grad() def ddim_sampling(self, cond, shape, x_T=None, ddim_use_original_steps=False, callback=None, timesteps=None, quantize_denoised=False, mask=None, x0=None, img_callback=None, log_every_t=100, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None, ucg_schedule=None, **kwargs): device = self.model.betas.device b = shape[0] if x_T is None: img = torch.randn(shape, device=device) else: img = x_T if timesteps is None: timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps elif timesteps is not None and not ddim_use_original_steps: subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1 timesteps = self.ddim_timesteps[:subset_end] intermediates = {'x_inter': [img], 'pred_x0': [img]} time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps) total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] print(f"Running DDIM Sampling with {total_steps} timesteps") iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps) for i, step in enumerate(iterator): index = total_steps - i - 1 ts = torch.full((b,), step, device=device, dtype=torch.long) if mask is not None: assert x0 is not None img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? img = img_orig * mask + (1. - mask) * img if ucg_schedule is not None: assert len(ucg_schedule) == len(time_range) unconditional_guidance_scale = ucg_schedule[i] outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps, quantize_denoised=quantize_denoised, temperature=temperature, noise_dropout=noise_dropout, score_corrector=score_corrector, corrector_kwargs=corrector_kwargs, unconditional_guidance_scale=unconditional_guidance_scale, unconditional_conditioning=unconditional_conditioning, dynamic_threshold=dynamic_threshold, timestep_index=i, **kwargs) img, pred_x0 = outs if callback: callback(i) if img_callback: img_callback(pred_x0, i) if index % log_every_t == 0 or index == total_steps - 1: intermediates['x_inter'].append(img) intermediates['pred_x0'].append(pred_x0) return img, intermediates @torch.no_grad() def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False, temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None, # redilation dilate=None, dilate_tau=None, dilate_skip=None, progress_dilate=False, dilate_cfg=None, dilate_cfg_skip=None, timestep_index=None, **kwargs): b, *_, device = *x.shape, x.device # redilation enable_dilate = (dilate is not None) if enable_dilate: if (self.ddim_timesteps.shape[0]-index) > dilate_tau: # close dilation in later denoising enable_dilate = False else: if progress_dilate: # adjust the dilation factor progressively assert(timestep_index is not None) dilate_list = list(range(2, math.ceil(dilate)+1))[::-1] n_stage = len(dilate_list) n_times_stage = math.ceil(dilate_tau / n_stage) stage_index = (timestep_index+1) // n_times_stage if stage_index > n_stage-1: stage_index = n_stage-1 dilate = dilate_list[stage_index] make_dilate_model(self.model, enable_dilate=enable_dilate, dilate=dilate, nskip=dilate_skip) if unconditional_conditioning is None or unconditional_guidance_scale == 1.: model_output = self.model.apply_model(x, t, c) else: x_in = torch.cat([x] * 2) t_in = torch.cat([t] * 2) if isinstance(c, dict): assert isinstance(unconditional_conditioning, dict) c_in = dict() for k in c: if isinstance(c[k], list): c_in[k] = [torch.cat([ unconditional_conditioning[k][i], c[k][i]]) for i in range(len(c[k]))] else: c_in[k] = torch.cat([ unconditional_conditioning[k], c[k]]) elif isinstance(c, list): c_in = list() assert isinstance(unconditional_conditioning, list) for i in range(len(c)): c_in.append(torch.cat([unconditional_conditioning[i], c[i]])) else: c_in = torch.cat([unconditional_conditioning, c]) model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2) model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond) if self.model.parameterization == "v": e_t = self.model.predict_eps_from_z_and_v(x, t, model_output) else: e_t = model_output if score_corrector is not None: assert self.model.parameterization == "eps", 'not implemented' e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs) alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas # select parameters corresponding to the currently considered timestep a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device) # current prediction for x_0 if self.model.parameterization != "v": pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() else: pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output) if quantize_denoised: pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) if dynamic_threshold is not None: raise NotImplementedError() # direction pointing to x_t dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature if noise_dropout > 0.: noise = torch.nn.functional.dropout(noise, p=noise_dropout) x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise return x_prev, pred_x0 @torch.no_grad() def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None, unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None): num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0] assert t_enc <= num_reference_steps num_steps = t_enc if use_original_steps: alphas_next = self.alphas_cumprod[:num_steps] alphas = self.alphas_cumprod_prev[:num_steps] else: alphas_next = self.ddim_alphas[:num_steps] alphas = torch.tensor(self.ddim_alphas_prev[:num_steps]) x_next = x0 intermediates = [] inter_steps = [] for i in tqdm(range(num_steps), desc='Encoding Image'): t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long) if unconditional_guidance_scale == 1.: noise_pred = self.model.apply_model(x_next, t, c) else: assert unconditional_conditioning is not None e_t_uncond, noise_pred = torch.chunk( self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)), torch.cat((unconditional_conditioning, c))), 2) noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond) xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next weighted_noise_pred = alphas_next[i].sqrt() * ( (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred x_next = xt_weighted + weighted_noise_pred if return_intermediates and i % ( num_steps // return_intermediates) == 0 and i < num_steps - 1: intermediates.append(x_next) inter_steps.append(i) elif return_intermediates and i >= num_steps - 2: intermediates.append(x_next) inter_steps.append(i) if callback: callback(i) out = {'x_encoded': x_next, 'intermediate_steps': inter_steps} if return_intermediates: out.update({'intermediates': intermediates}) return x_next, out @torch.no_grad() def stochastic_encode(self, x0, t, use_original_steps=False, noise=None): # fast, but does not allow for exact reconstruction # t serves as an index to gather the correct alphas if use_original_steps: sqrt_alphas_cumprod = self.sqrt_alphas_cumprod sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod else: sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas) sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas if noise is None: noise = torch.randn_like(x0)
return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
3
2023-10-11 10:57:55+00:00
8k
neuralinternet/compute-subnet
neurons/miner.py
[ { "identifier": "PerfInfo", "path": "compute/protocol.py", "snippet": "class PerfInfo(bt.Synapse):\n \"\"\"\n A simple performance information protocol representation which uses bt.Synapse as its base.\n This protocol helps in handling performance information request and response communication ...
import json import os import traceback import typing import bittensor as bt import time import torch import Miner.allocate as al import Miner.performance as pf import Miner.pow as p import compute from compute.protocol import PerfInfo, Allocate, Challenge from compute.utils.parser import ComputeArgPaser from compute.utils.subtensor import is_registered from compute.utils.version import get_remote_version, check_hashcat_version, try_update, version2number
4,365
return valid_uids def get_queryable_axons(metagraph): queryable_uids = get_valid_queryable_uids(metagraph) queryable_axons = {metagraph.uids.tolist().index(uid): metagraph.axons[metagraph.uids.tolist().index(uid)] for uid in queryable_uids} return queryable_axons def get_valid_validator_uids(metagraph: bt.metagraph): uids = metagraph.uids.tolist() valid_uids = [] for index, uid in enumerate(uids): if metagraph.total_stake[index] > compute.validator_permit_stake: valid_uids.append(uid) return valid_uids def get_valid_validator(config, subtensor: bt.subtensor, metagraph: bt.metagraph): valid_validator_uids = get_valid_validator_uids(metagraph=metagraph) valid_validator = [] for uid in valid_validator_uids: neuron = subtensor.neuron_for_uid(uid, config.netuid) hotkey = neuron.hotkey version = neuron.prometheus_info.version valid_validator.append((uid, hotkey, version)) return valid_validator def get_valid_hotkeys(config, subtensor: bt.subtensor, metagraph: bt.metagraph): whitelist_version_hotkeys_set.clear() try: latest_version = version2number(get_remote_version(pattern="__minimal_validator_version__")) if latest_version is None: bt.logging.error(f"Github API call failed or version string is incorrect!") return valid_validators = get_valid_validator(config=config, subtensor=subtensor, metagraph=metagraph) for uid, hotkey, version in valid_validators: try: if version >= latest_version: bt.logging.debug(f"Version signature match for hotkey : {hotkey}") whitelist_version_hotkeys_set.add(hotkey) continue bt.logging.debug(f"Version signature mismatch for hotkey : {hotkey}") except Exception: bt.logging.error(f"exception in get_valid_hotkeys: {traceback.format_exc()}") bt.logging.info(f"Total valid validator hotkeys = {whitelist_version_hotkeys_set}") except json.JSONDecodeError: bt.logging.error(f"exception in get_valid_hotkeys: {traceback.format_exc()}") def set_weights(config, subtensor, wallet, metagraph, miner_subnet_uid): chain_weights = torch.zeros(subtensor.subnetwork_n(netuid=config.netuid)) chain_weights[miner_subnet_uid] = 1 # This is a crucial step that updates the incentive mechanism on the Bittensor blockchain. # Miners with higher scores (or weights) receive a larger share of TAO rewards on this subnet. result = subtensor.set_weights( netuid=config.netuid, # Subnet to set weights on. wallet=wallet, # Wallet to sign set weights using hotkey. uids=metagraph.uids, # Uids of the miners to set weights for. weights=chain_weights, # Weights to set for the miners. version_key=compute.__version_as_int__, wait_for_inclusion=False, ) if result: bt.logging.success("Successfully set weights.") else: bt.logging.error("Failed to set weights.") # Main takes the config and starts the miner. def main(config): # Activating Bittensor's logging with the set configurations. bt.logging(config=config, logging_dir=config.full_path) bt.logging.info(f"Running miner for subnet: {config.netuid} on network: {config.subtensor.chain_endpoint} with config:") # This logs the active configuration to the specified logging directory for review. # bt.logging.info(config) # Step 4: Initialize Bittensor miner objects # These classes are vital to interact and function within the Bittensor network. bt.logging.info("Setting up bittensor objects.") # Wallet holds cryptographic information, ensuring secure transactions and communication. wallet = bt.wallet(config=config) bt.logging.info(f"Wallet: {wallet}") # subtensor manages the blockchain connection, facilitating interaction with the Bittensor blockchain. subtensor = bt.subtensor(config=config) bt.logging.info(f"Subtensor: {subtensor}") # metagraph provides the network's current state, holding state about other participants in a subnet. metagraph = subtensor.metagraph(config.netuid) bt.logging.info(f"Metagraph: {metagraph}") # Allow validators that are not permitted by stake miner_whitelist_not_enough_stake = config.miner_whitelist_not_enough_stake miner_subnet_uid = is_registered(wallet=wallet, metagraph=metagraph, subtensor=subtensor, entity="miner") bt.logging.info(f"Running miner on uid: {miner_subnet_uid}") p.check_cuda_availability() hashcat_path = config.miner_hashcat_path hashcat_workload_profile = config.miner_hashcat_workload_profile hashcat_extended_options = config.miner_hashcat_extended_options check_hashcat_version(hashcat_path=hashcat_path) current_block = subtensor.block last_updated_block = current_block - (current_block % 100) # Step 5: Set up miner functionalities # The following functions control the miner's response to incoming requests.
# The MIT License (MIT) # Copyright © 2023 GitPhantomman # Copyright © 2023 Rapiiidooo # 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. whitelist_args_hotkeys_set: set = set() whitelist_version_hotkeys_set: set = set() blacklist_args_hotkeys_set: set = set() exploiters_hotkeys_set: set = set() def get_config(): global whitelist_args_hotkeys_set global whitelist_version_hotkeys_set # Step 1: Set up the configuration parser # This function initializes the necessary command-line arguments. parser = ComputeArgPaser(description="This script aims to help miners with the compute subnet.") # Adds override arguments for network and netuid. # Activating the parser to read any command-line inputs. config = bt.config(parser) if config.whitelist_hotkeys: for hotkey in config.whitelist_hotkeys: whitelist_args_hotkeys_set.add(hotkey) if config.blacklist_hotkeys: for hotkey in config.blacklist_hotkeys: blacklist_args_hotkeys_set.add(hotkey) if config.blacklist_exploiters: for key in compute.SUSPECTED_EXPLOITERS_HOTKEYS: exploiters_hotkeys_set.add(key) # Step 3: Set up logging directory # Logging captures events for diagnosis or understanding miner's behavior. config.full_path = os.path.expanduser( "{}/{}/{}/netuid{}/{}".format( config.logging.logging_dir, config.wallet.name, config.wallet.hotkey, config.netuid, "miner", ) ) # Ensure the directory for logging exists, else create one. if not os.path.exists(config.full_path): os.makedirs(config.full_path, exist_ok=True) return config def get_valid_queryable_uids(metagraph): uids = metagraph.uids.tolist() valid_uids = [] for index, uid in enumerate(uids): if metagraph.total_stake[index]: valid_uids.append(uid) return valid_uids def get_queryable_axons(metagraph): queryable_uids = get_valid_queryable_uids(metagraph) queryable_axons = {metagraph.uids.tolist().index(uid): metagraph.axons[metagraph.uids.tolist().index(uid)] for uid in queryable_uids} return queryable_axons def get_valid_validator_uids(metagraph: bt.metagraph): uids = metagraph.uids.tolist() valid_uids = [] for index, uid in enumerate(uids): if metagraph.total_stake[index] > compute.validator_permit_stake: valid_uids.append(uid) return valid_uids def get_valid_validator(config, subtensor: bt.subtensor, metagraph: bt.metagraph): valid_validator_uids = get_valid_validator_uids(metagraph=metagraph) valid_validator = [] for uid in valid_validator_uids: neuron = subtensor.neuron_for_uid(uid, config.netuid) hotkey = neuron.hotkey version = neuron.prometheus_info.version valid_validator.append((uid, hotkey, version)) return valid_validator def get_valid_hotkeys(config, subtensor: bt.subtensor, metagraph: bt.metagraph): whitelist_version_hotkeys_set.clear() try: latest_version = version2number(get_remote_version(pattern="__minimal_validator_version__")) if latest_version is None: bt.logging.error(f"Github API call failed or version string is incorrect!") return valid_validators = get_valid_validator(config=config, subtensor=subtensor, metagraph=metagraph) for uid, hotkey, version in valid_validators: try: if version >= latest_version: bt.logging.debug(f"Version signature match for hotkey : {hotkey}") whitelist_version_hotkeys_set.add(hotkey) continue bt.logging.debug(f"Version signature mismatch for hotkey : {hotkey}") except Exception: bt.logging.error(f"exception in get_valid_hotkeys: {traceback.format_exc()}") bt.logging.info(f"Total valid validator hotkeys = {whitelist_version_hotkeys_set}") except json.JSONDecodeError: bt.logging.error(f"exception in get_valid_hotkeys: {traceback.format_exc()}") def set_weights(config, subtensor, wallet, metagraph, miner_subnet_uid): chain_weights = torch.zeros(subtensor.subnetwork_n(netuid=config.netuid)) chain_weights[miner_subnet_uid] = 1 # This is a crucial step that updates the incentive mechanism on the Bittensor blockchain. # Miners with higher scores (or weights) receive a larger share of TAO rewards on this subnet. result = subtensor.set_weights( netuid=config.netuid, # Subnet to set weights on. wallet=wallet, # Wallet to sign set weights using hotkey. uids=metagraph.uids, # Uids of the miners to set weights for. weights=chain_weights, # Weights to set for the miners. version_key=compute.__version_as_int__, wait_for_inclusion=False, ) if result: bt.logging.success("Successfully set weights.") else: bt.logging.error("Failed to set weights.") # Main takes the config and starts the miner. def main(config): # Activating Bittensor's logging with the set configurations. bt.logging(config=config, logging_dir=config.full_path) bt.logging.info(f"Running miner for subnet: {config.netuid} on network: {config.subtensor.chain_endpoint} with config:") # This logs the active configuration to the specified logging directory for review. # bt.logging.info(config) # Step 4: Initialize Bittensor miner objects # These classes are vital to interact and function within the Bittensor network. bt.logging.info("Setting up bittensor objects.") # Wallet holds cryptographic information, ensuring secure transactions and communication. wallet = bt.wallet(config=config) bt.logging.info(f"Wallet: {wallet}") # subtensor manages the blockchain connection, facilitating interaction with the Bittensor blockchain. subtensor = bt.subtensor(config=config) bt.logging.info(f"Subtensor: {subtensor}") # metagraph provides the network's current state, holding state about other participants in a subnet. metagraph = subtensor.metagraph(config.netuid) bt.logging.info(f"Metagraph: {metagraph}") # Allow validators that are not permitted by stake miner_whitelist_not_enough_stake = config.miner_whitelist_not_enough_stake miner_subnet_uid = is_registered(wallet=wallet, metagraph=metagraph, subtensor=subtensor, entity="miner") bt.logging.info(f"Running miner on uid: {miner_subnet_uid}") p.check_cuda_availability() hashcat_path = config.miner_hashcat_path hashcat_workload_profile = config.miner_hashcat_workload_profile hashcat_extended_options = config.miner_hashcat_extended_options check_hashcat_version(hashcat_path=hashcat_path) current_block = subtensor.block last_updated_block = current_block - (current_block % 100) # Step 5: Set up miner functionalities # The following functions control the miner's response to incoming requests.
def base_blacklist(synapse: typing.Union[PerfInfo, Allocate, Challenge]) -> typing.Tuple[bool, str]:
0
2023-10-11 12:35:20+00:00
8k
unitreerobotics/unitree_rl_gym
legged_gym/envs/h1/h1_config.py
[ { "identifier": "LeggedRobotCfg", "path": "legged_gym/envs/base/legged_robot_config.py", "snippet": "class LeggedRobotCfg(BaseConfig):\n class env:\n num_envs = 4096\n num_observations = 48\n num_privileged_obs = None # if not None a priviledge_obs_buf will be returned by step() ...
from legged_gym.envs.base.legged_robot_config import LeggedRobotCfg, LeggedRobotCfgPPO
3,608
class H1RoughCfg( LeggedRobotCfg ): class init_state( LeggedRobotCfg.init_state ): pos = [0.0, 0.0, 1.0] # x,y,z [m] default_joint_angles = { # = target angles [rad] when action = 0.0 'left_hip_yaw_joint' : 0. , 'left_hip_roll_joint' : 0, 'left_hip_pitch_joint' : -0.4, 'left_knee_joint' : 0.8, 'left_ankle_joint' : -0.4, 'right_hip_yaw_joint' : 0., 'right_hip_roll_joint' : 0, 'right_hip_pitch_joint' : -0.4, 'right_knee_joint' : 0.8, 'right_ankle_joint' : -0.4, 'torso_joint' : 0., 'left_shoulder_pitch_joint' : 0., 'left_shoulder_roll_joint' : 0, 'left_shoulder_yaw_joint' : 0., 'left_elbow_joint' : 0., 'right_shoulder_pitch_joint' : 0., 'right_shoulder_roll_joint' : 0.0, 'right_shoulder_yaw_joint' : 0., 'right_elbow_joint' : 0., } class env(LeggedRobotCfg.env): num_observations = 42 num_actions = 10 class control( LeggedRobotCfg.control ): # PD Drive parameters: control_type = 'P' # PD Drive parameters: stiffness = {'hip_yaw': 200, 'hip_roll': 200, 'hip_pitch': 200, 'knee': 300, 'ankle': 40, 'torso': 300, 'shoulder': 100, "elbow":100, } # [N*m/rad] damping = { 'hip_yaw': 5, 'hip_roll': 5, 'hip_pitch': 5, 'knee': 6, 'ankle': 2, 'torso': 6, 'shoulder': 2, "elbow":2, } # [N*m/rad] # [N*m*s/rad] # action scale: target angle = actionScale * action + defaultAngle action_scale = 0.25 # decimation: Number of control action updates @ sim DT per policy DT decimation = 4 class asset( LeggedRobotCfg.asset ): file = '{LEGGED_GYM_ROOT_DIR}/resources/robots/h1/urdf/h1.urdf' name = "h1" foot_name = "ankle" penalize_contacts_on = ["hip", "knee"] terminate_after_contacts_on = ["pelvis"] self_collisions = 1 # 1 to disable, 0 to enable...bitwise filter flip_visual_attachments = False class rewards( LeggedRobotCfg.rewards ): soft_dof_pos_limit = 0.9 base_height_target = 0.98 class scales( LeggedRobotCfg.rewards.scales ): tracking_lin_vel = 1.0 tracking_ang_vel = 0.5 lin_vel_z = -2.0 ang_vel_xy = -1.0 orientation = -1.0 base_height = -100.0 dof_acc = -3.5e-8 feet_air_time = 1.0 collision = 0.0 action_rate = -0.01 torques = 0.0 dof_pos_limits = -10.0
class H1RoughCfg( LeggedRobotCfg ): class init_state( LeggedRobotCfg.init_state ): pos = [0.0, 0.0, 1.0] # x,y,z [m] default_joint_angles = { # = target angles [rad] when action = 0.0 'left_hip_yaw_joint' : 0. , 'left_hip_roll_joint' : 0, 'left_hip_pitch_joint' : -0.4, 'left_knee_joint' : 0.8, 'left_ankle_joint' : -0.4, 'right_hip_yaw_joint' : 0., 'right_hip_roll_joint' : 0, 'right_hip_pitch_joint' : -0.4, 'right_knee_joint' : 0.8, 'right_ankle_joint' : -0.4, 'torso_joint' : 0., 'left_shoulder_pitch_joint' : 0., 'left_shoulder_roll_joint' : 0, 'left_shoulder_yaw_joint' : 0., 'left_elbow_joint' : 0., 'right_shoulder_pitch_joint' : 0., 'right_shoulder_roll_joint' : 0.0, 'right_shoulder_yaw_joint' : 0., 'right_elbow_joint' : 0., } class env(LeggedRobotCfg.env): num_observations = 42 num_actions = 10 class control( LeggedRobotCfg.control ): # PD Drive parameters: control_type = 'P' # PD Drive parameters: stiffness = {'hip_yaw': 200, 'hip_roll': 200, 'hip_pitch': 200, 'knee': 300, 'ankle': 40, 'torso': 300, 'shoulder': 100, "elbow":100, } # [N*m/rad] damping = { 'hip_yaw': 5, 'hip_roll': 5, 'hip_pitch': 5, 'knee': 6, 'ankle': 2, 'torso': 6, 'shoulder': 2, "elbow":2, } # [N*m/rad] # [N*m*s/rad] # action scale: target angle = actionScale * action + defaultAngle action_scale = 0.25 # decimation: Number of control action updates @ sim DT per policy DT decimation = 4 class asset( LeggedRobotCfg.asset ): file = '{LEGGED_GYM_ROOT_DIR}/resources/robots/h1/urdf/h1.urdf' name = "h1" foot_name = "ankle" penalize_contacts_on = ["hip", "knee"] terminate_after_contacts_on = ["pelvis"] self_collisions = 1 # 1 to disable, 0 to enable...bitwise filter flip_visual_attachments = False class rewards( LeggedRobotCfg.rewards ): soft_dof_pos_limit = 0.9 base_height_target = 0.98 class scales( LeggedRobotCfg.rewards.scales ): tracking_lin_vel = 1.0 tracking_ang_vel = 0.5 lin_vel_z = -2.0 ang_vel_xy = -1.0 orientation = -1.0 base_height = -100.0 dof_acc = -3.5e-8 feet_air_time = 1.0 collision = 0.0 action_rate = -0.01 torques = 0.0 dof_pos_limits = -10.0
class H1RoughCfgPPO( LeggedRobotCfgPPO ):
1
2023-10-11 07:24:59+00:00
8k
harishsiravuri/kgforge
tests/test_pdftokg.py
[ { "identifier": "KGConfig", "path": "kgforge/config/config.py", "snippet": "class KGConfig:\n \"\"\"A configuration object.\"\"\"\n\n DEFAULT_CONCEPTS: List[str] = [\"contribution\", \"methods\", \"datasets\", \"findings\"]\n\n DEFAULT_PROMPTS: List[Prompt] = [\n Prompt(\n con...
import os from kgforge.config import KGConfig from kgforge.data_models import ResearchArtifact from kgforge.kg import KnowledgeGraph from kgforge.utils import OpenAlexUtil, TextLoader
3,983
def test_get_full_text() -> None: oa_util = OpenAlexUtil() oa_resp = oa_util.search_works(search_query="machine+learning", results_limit=1)
def test_get_full_text() -> None: oa_util = OpenAlexUtil() oa_resp = oa_util.search_works(search_query="machine+learning", results_limit=1)
artifacts = [ResearchArtifact.model_validate(_) for _ in oa_resp]
1
2023-10-12 17:57:07+00:00
8k
bilibini/Lovely_Image_Downloader
dist/py/Python38/site-packages/charset_normalizer/md.py
[ { "identifier": "COMMON_SAFE_ASCII_CHARACTERS", "path": "dist/py/Python38/site-packages/charset_normalizer/constant.py", "snippet": "COMMON_SAFE_ASCII_CHARACTERS: Set[str] = {\n \"<\",\n \">\",\n \"=\",\n \":\",\n \"/\",\n \"&\",\n \";\",\n \"{\",\n \"}\",\n \"[\",\n \"]...
from functools import lru_cache from logging import getLogger from typing import List, Optional from .constant import ( COMMON_SAFE_ASCII_CHARACTERS, TRACE, UNICODE_SECONDARY_RANGE_KEYWORD, ) from .utils import ( is_accentuated, is_case_variable, is_cjk, is_emoticon, is_hangul, is_hiragana, is_katakana, is_latin, is_punctuation, is_separator, is_symbol, is_thai, is_unprintable, remove_accent, unicode_range, )
3,717
return (self._unprintable_count * 8) / self._character_count class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin): def __init__(self) -> None: self._successive_count: int = 0 self._character_count: int = 0 self._last_latin_character: Optional[str] = None def eligible(self, character: str) -> bool: return character.isalpha() and is_latin(character) def feed(self, character: str) -> None: self._character_count += 1 if ( self._last_latin_character is not None and is_accentuated(character) and is_accentuated(self._last_latin_character) ): if character.isupper() and self._last_latin_character.isupper(): self._successive_count += 1 # Worse if its the same char duplicated with different accent. if remove_accent(character) == remove_accent(self._last_latin_character): self._successive_count += 1 self._last_latin_character = character def reset(self) -> None: # pragma: no cover self._successive_count = 0 self._character_count = 0 self._last_latin_character = None @property def ratio(self) -> float: if self._character_count == 0: return 0.0 return (self._successive_count * 2) / self._character_count class SuspiciousRange(MessDetectorPlugin): def __init__(self) -> None: self._suspicious_successive_range_count: int = 0 self._character_count: int = 0 self._last_printable_seen: Optional[str] = None def eligible(self, character: str) -> bool: return character.isprintable() def feed(self, character: str) -> None: self._character_count += 1 if ( character.isspace() or is_punctuation(character) or character in COMMON_SAFE_ASCII_CHARACTERS ): self._last_printable_seen = None return if self._last_printable_seen is None: self._last_printable_seen = character return unicode_range_a: Optional[str] = unicode_range(self._last_printable_seen) unicode_range_b: Optional[str] = unicode_range(character) if is_suspiciously_successive_range(unicode_range_a, unicode_range_b): self._suspicious_successive_range_count += 1 self._last_printable_seen = character def reset(self) -> None: # pragma: no cover self._character_count = 0 self._suspicious_successive_range_count = 0 self._last_printable_seen = None @property def ratio(self) -> float: if self._character_count == 0: return 0.0 ratio_of_suspicious_range_usage: float = ( self._suspicious_successive_range_count * 2 ) / self._character_count if ratio_of_suspicious_range_usage < 0.1: return 0.0 return ratio_of_suspicious_range_usage class SuperWeirdWordPlugin(MessDetectorPlugin): def __init__(self) -> None: self._word_count: int = 0 self._bad_word_count: int = 0 self._foreign_long_count: int = 0 self._is_current_word_bad: bool = False self._foreign_long_watch: bool = False self._character_count: int = 0 self._bad_character_count: int = 0 self._buffer: str = "" self._buffer_accent_count: int = 0 def eligible(self, character: str) -> bool: return True def feed(self, character: str) -> None: if character.isalpha(): self._buffer += character if is_accentuated(character): self._buffer_accent_count += 1 if ( self._foreign_long_watch is False and (is_latin(character) is False or is_accentuated(character)) and is_cjk(character) is False and is_hangul(character) is False
class MessDetectorPlugin: """ Base abstract class used for mess detection plugins. All detectors MUST extend and implement given methods. """ def eligible(self, character: str) -> bool: """ Determine if given character should be fed in. """ raise NotImplementedError # pragma: nocover def feed(self, character: str) -> None: """ The main routine to be executed upon character. Insert the logic in witch the text would be considered chaotic. """ raise NotImplementedError # pragma: nocover def reset(self) -> None: # pragma: no cover """ Permit to reset the plugin to the initial state. """ raise NotImplementedError @property def ratio(self) -> float: """ Compute the chaos ratio based on what your feed() has seen. Must NOT be lower than 0.; No restriction gt 0. """ raise NotImplementedError # pragma: nocover class TooManySymbolOrPunctuationPlugin(MessDetectorPlugin): def __init__(self) -> None: self._punctuation_count: int = 0 self._symbol_count: int = 0 self._character_count: int = 0 self._last_printable_char: Optional[str] = None self._frenzy_symbol_in_word: bool = False def eligible(self, character: str) -> bool: return character.isprintable() def feed(self, character: str) -> None: self._character_count += 1 if ( character != self._last_printable_char and character not in COMMON_SAFE_ASCII_CHARACTERS ): if is_punctuation(character): self._punctuation_count += 1 elif ( character.isdigit() is False and is_symbol(character) and is_emoticon(character) is False ): self._symbol_count += 2 self._last_printable_char = character def reset(self) -> None: # pragma: no cover self._punctuation_count = 0 self._character_count = 0 self._symbol_count = 0 @property def ratio(self) -> float: if self._character_count == 0: return 0.0 ratio_of_punctuation: float = ( self._punctuation_count + self._symbol_count ) / self._character_count return ratio_of_punctuation if ratio_of_punctuation >= 0.3 else 0.0 class TooManyAccentuatedPlugin(MessDetectorPlugin): def __init__(self) -> None: self._character_count: int = 0 self._accentuated_count: int = 0 def eligible(self, character: str) -> bool: return character.isalpha() def feed(self, character: str) -> None: self._character_count += 1 if is_accentuated(character): self._accentuated_count += 1 def reset(self) -> None: # pragma: no cover self._character_count = 0 self._accentuated_count = 0 @property def ratio(self) -> float: if self._character_count == 0 or self._character_count < 8: return 0.0 ratio_of_accentuation: float = self._accentuated_count / self._character_count return ratio_of_accentuation if ratio_of_accentuation >= 0.35 else 0.0 class UnprintablePlugin(MessDetectorPlugin): def __init__(self) -> None: self._unprintable_count: int = 0 self._character_count: int = 0 def eligible(self, character: str) -> bool: return True def feed(self, character: str) -> None: if is_unprintable(character): self._unprintable_count += 1 self._character_count += 1 def reset(self) -> None: # pragma: no cover self._unprintable_count = 0 @property def ratio(self) -> float: if self._character_count == 0: return 0.0 return (self._unprintable_count * 8) / self._character_count class SuspiciousDuplicateAccentPlugin(MessDetectorPlugin): def __init__(self) -> None: self._successive_count: int = 0 self._character_count: int = 0 self._last_latin_character: Optional[str] = None def eligible(self, character: str) -> bool: return character.isalpha() and is_latin(character) def feed(self, character: str) -> None: self._character_count += 1 if ( self._last_latin_character is not None and is_accentuated(character) and is_accentuated(self._last_latin_character) ): if character.isupper() and self._last_latin_character.isupper(): self._successive_count += 1 # Worse if its the same char duplicated with different accent. if remove_accent(character) == remove_accent(self._last_latin_character): self._successive_count += 1 self._last_latin_character = character def reset(self) -> None: # pragma: no cover self._successive_count = 0 self._character_count = 0 self._last_latin_character = None @property def ratio(self) -> float: if self._character_count == 0: return 0.0 return (self._successive_count * 2) / self._character_count class SuspiciousRange(MessDetectorPlugin): def __init__(self) -> None: self._suspicious_successive_range_count: int = 0 self._character_count: int = 0 self._last_printable_seen: Optional[str] = None def eligible(self, character: str) -> bool: return character.isprintable() def feed(self, character: str) -> None: self._character_count += 1 if ( character.isspace() or is_punctuation(character) or character in COMMON_SAFE_ASCII_CHARACTERS ): self._last_printable_seen = None return if self._last_printable_seen is None: self._last_printable_seen = character return unicode_range_a: Optional[str] = unicode_range(self._last_printable_seen) unicode_range_b: Optional[str] = unicode_range(character) if is_suspiciously_successive_range(unicode_range_a, unicode_range_b): self._suspicious_successive_range_count += 1 self._last_printable_seen = character def reset(self) -> None: # pragma: no cover self._character_count = 0 self._suspicious_successive_range_count = 0 self._last_printable_seen = None @property def ratio(self) -> float: if self._character_count == 0: return 0.0 ratio_of_suspicious_range_usage: float = ( self._suspicious_successive_range_count * 2 ) / self._character_count if ratio_of_suspicious_range_usage < 0.1: return 0.0 return ratio_of_suspicious_range_usage class SuperWeirdWordPlugin(MessDetectorPlugin): def __init__(self) -> None: self._word_count: int = 0 self._bad_word_count: int = 0 self._foreign_long_count: int = 0 self._is_current_word_bad: bool = False self._foreign_long_watch: bool = False self._character_count: int = 0 self._bad_character_count: int = 0 self._buffer: str = "" self._buffer_accent_count: int = 0 def eligible(self, character: str) -> bool: return True def feed(self, character: str) -> None: if character.isalpha(): self._buffer += character if is_accentuated(character): self._buffer_accent_count += 1 if ( self._foreign_long_watch is False and (is_latin(character) is False or is_accentuated(character)) and is_cjk(character) is False and is_hangul(character) is False
and is_katakana(character) is False
9
2023-10-11 09:08:57+00:00
8k
eCrimeLabs/cratos-fastapi
app/main.py
[ { "identifier": "feeds", "path": "app/core/feeds.py", "snippet": "def feedDefineMISPSearch(feed: str, requestData: dict) -> dict:\ndef getFeedNameToTag(prependTag: str, customFeeds: dict) -> dict:\ndef formatWarninglistOutputData(inputBlob: dict, outputType: str) -> dict:\ndef formatFeedOutputData(input...
from sys import prefix from fastapi import Security, Depends, FastAPI, HTTPException, Request, Response, Form, Path, Query from fastapi.security.api_key import APIKeyQuery, APIKeyCookie, APIKeyHeader, APIKey from fastapi.openapi.docs import get_swagger_ui_html from fastapi.openapi.utils import get_openapi from fastapi_versioning import VersionedFastAPI, version from fastapi.exceptions import RequestValidationError from fastapi.exception_handlers import request_validation_exception_handler from fastapi.responses import FileResponse from fastapi.encoders import jsonable_encoder from typing import Union from typing_extensions import Annotated from datetime import date, datetime from pydantic import BaseModel, Field from starlette.status import HTTP_403_FORBIDDEN, HTTP_503_SERVICE_UNAVAILABLE, HTTP_504_GATEWAY_TIMEOUT, HTTP_415_UNSUPPORTED_MEDIA_TYPE from starlette.responses import RedirectResponse, JSONResponse from starlette.exceptions import HTTPException as StarletteHTTPException from fastapi.templating import Jinja2Templates from fastapi.staticfiles import StaticFiles from app.core import feeds, misp from app.config import GLOBALCONFIG from app import dependencies from app.models import models import pprint import logging
4,097
): authKeyToken = {} inputData = str(item.proto) + ";" + str(item.port) + ";" + str(item.domain) + ";" + str(item.auth) + ";" + str(item.expire) result = dependencies.encryptString(inputData, app.salt, app.password) authKeyToken['MISP'] = str(item.proto) + '//' + str(item.domain) + ':' + str(item.port) + '/' authKeyToken['validity'] = str(item.expire) authKeyToken['token'] = result['detail'] return authKeyToken @app.get("/v1/openapi.json", tags=["documentations"]) async def get_open_api_endpoint(): response = JSONResponse( get_openapi(title="CRATOS - FastAPI proxy", version=3, routes=app.routes) ) return response @app.get("/v1/help", tags=["documentations"]) async def get_documentation(): """ The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to HTTP APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. :param apiKey: apiKey to authenticate the request :return: WebUI for documentation and tests """ response = get_swagger_ui_html( openapi_url="/openapi.json", title="CRATOS - FastAPI proxy Documentation", ) return response @app.get("/v1/check", tags=["status"], summary="Check connection to MISP") async def check_misp_connection(api_key: APIKey = Depends(getApiToken)): """ Check the connection status to the MISP instance :param apiKey: apiKey to authenticate the request :return: JSON output of the minor informaiton on the MISP instance such as version and pyMISP version """ mispResponse = {} mispURL = ("{}://{}:{}".format(app.configCore['requestConfig']['apiTokenProto'], app.configCore['requestConfig']['apiTokenFQDN'], app.configCore['requestConfig']['apiTokenPort'])) mispAuthKey = app.configCore['requestConfig']['apiTokenAuthKey'] mispResponse = misp.mispGetVersion(mispURL, mispAuthKey) if (not (mispResponse['status']) and (mispResponse['error_num'] == 1)): raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=mispResponse['error'] + ' - ' + str(mispResponse['status_code']) ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 2)): raise HTTPException( status_code=HTTP_503_SERVICE_UNAVAILABLE, detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 3)): raise HTTPException( status_code=HTTP_504_GATEWAY_TIMEOUT , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 4)): raise HTTPException( status_code=HTTP_504_GATEWAY_TIMEOUT , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 5)): raise HTTPException( status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 6)): raise HTTPException( status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE , detail=mispResponse['error'] ) else: mispResponse.pop('status') return(mispResponse) @app.get("/v1/statistics", tags=["info"], summary="Get attribute type statistics from the MISP", description="Connects to the MISP instance and returns statistics API and outputs count of attribute types in a JSON format" ) async def get_misp_statistics(api_key: APIKey = Depends(getApiToken)): """ Get content of MISP warninglists or list avaliable MISP warninglists :param apiKey: apiKey to authenticate the request :return: JSON output of the statictics """ mispResponse = {} mispURL = ("{}://{}:{}".format(app.configCore['requestConfig']['apiTokenProto'], app.configCore['requestConfig']['apiTokenFQDN'], app.configCore['requestConfig']['apiTokenPort'])) mispAuthKey = app.configCore['requestConfig']['apiTokenAuthKey'] mispResponse = misp.mispGetStatistics(mispURL, mispAuthKey) if (not (mispResponse['status']) and (mispResponse['error_num'] == 1)): raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=mispResponse['error'] + ' - ' + str(mispResponse['status_code']) ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 2)): raise HTTPException( status_code=HTTP_503_SERVICE_UNAVAILABLE, detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 3)): raise HTTPException( status_code=HTTP_504_GATEWAY_TIMEOUT , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 4)): raise HTTPException( status_code=HTTP_504_GATEWAY_TIMEOUT , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 5)): raise HTTPException( status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 6)): raise HTTPException( status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE , detail=mispResponse['error'] ) else: mispResponse.pop('status') return(mispResponse) @app.get("/v1/warninglist/id/{warninglistId}/output/{returnedDataType}", tags=["info"], summary="Get lists and content of Warning lists from MISP", description="""<b>Connects to the MISP instance for collecting information around Warninglists</b><br><br> id 0 returns a list of avaliable warninglists and content around this, choosing an id higher than 0 has to be aligned with the MISP warninglist ID. """ ) async def get_misp_warninglist( *, warninglistId: int = Path(title="The ID of the Warninglist to show, 0 lists avaliable Warninglists", ge=0, le=1000), returnedDataType: Annotated[models.ModelOutputType, Path(description="Defines the output that the feed will be presented in.")], api_key: APIKey = Depends(getApiToken) ): """ Get content of MISP warninglists or list avaliable MISP warninglists :param warninglistId: ID number of warninglist :param returnedDataType: What format does the data have to be returned in :return: Contant of warninglist of avaliable warninglists in the choosen output format """ mispResponse = {} mispURL = ("{}://{}:{}".format(app.configCore['requestConfig']['apiTokenProto'], app.configCore['requestConfig']['apiTokenFQDN'], app.configCore['requestConfig']['apiTokenPort'])) mispAuthKey = app.configCore['requestConfig']['apiTokenAuthKey'] mispResponse = misp.mispGetWarninglists(mispURL, mispAuthKey, warninglistId) if (not (mispResponse['status']) and (mispResponse['error_num'] == 1)): raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=mispResponse['error'] + ' - ' + str(mispResponse['status_code']) ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 2)): raise HTTPException( status_code=HTTP_503_SERVICE_UNAVAILABLE, detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 3)): raise HTTPException( status_code=HTTP_504_GATEWAY_TIMEOUT , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 4)): raise HTTPException( status_code=HTTP_504_GATEWAY_TIMEOUT , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 5)): raise HTTPException( status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 6)): raise HTTPException( status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE , detail=mispResponse['error'] ) else:
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sub elements logger = logging.getLogger(__name__) API_KEY_NAME = "token" CRATOS_VERSION="1.0.1" apiKeyQuery = APIKeyQuery(name=API_KEY_NAME, auto_error=False) apiKeyHeader = APIKeyHeader(name=API_KEY_NAME, auto_error=False) description = """ CRATOS - FastAPI proxy is your secure and optimized integration between your security infrastructure and your MISP Threat Sharing Platform. ## Feeds You can in a structured form **custom build** your threat feeds from MISP in the format you need for integrations into your security components, while also ensuring automated expiration of "old" data. """ app = FastAPI( title="CRATOS - FastAPI proxy integration for MISP", description=description, version=CRATOS_VERSION, contact={ "name": "eCrimeLabs ApS", "url": "https://github.com/eCrimeLabs/cratos-fastapi" }, docs_url=None, swagger_ui_parameters={"defaultModelsExpandDepth": -1}, license_info={ "name": "License: MIT License", "url": "https://spdx.org/licenses/MIT.html", }, ) app.mount("/img", StaticFiles(directory="img"), name='images') templates = Jinja2Templates(directory="templates/") favicon_path = 'templates/favicon.ico' app.configCore = GLOBALCONFIG app.password = app.configCore['encryption_key'].encode() app.salt= app.configCore['salt'].encode() async def getApiToken( apiKeyQuery: str = Security(apiKeyQuery), apiKeyHeader: str = Security(apiKeyHeader), ): if not (apiKeyQuery is None): returnValue = dependencies.checkApiToken(apiKeyQuery, app.salt, app.password, app.ClientIP) if returnValue['status']: app.configCore['requestConfig'] = returnValue['config'] return apiKeyQuery raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=returnValue['detail'] ) if not (apiKeyHeader is None): returnValue = dependencies.checkApiToken(apiKeyHeader, app.salt, app.password, app.ClientIP) if returnValue['status']: app.configCore['requestConfig'] = returnValue['config'] return apiKeyHeader raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=returnValue['detail'] ) raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Could not validate token or not set" ) @app.exception_handler(ValueError) async def value_error_exception_handler(request: Request, exc: ValueError): return JSONResponse( status_code=400, content={"message": str(exc)}, ) @app.middleware("http") async def add_process_time_header(request: Request, call_next): """ It is essential that the FastAPI gets the real IP address of the visitor in order to validate the IP address """ x_get_real = request.headers.get("X-Real-IP") if x_get_real: # From nginx: proxy_set_header X-Real-IP $remote_addr; client_ip = x_get_real else: # Fallback to using the client's IP from request.client.host client_ip = request.client.host app.ClientIP = client_ip response = await call_next(request) return response @app.get("/") async def homepage(): """ Default front page of CRATOS FastAPI proxy """ return {"message": "CRATOS - FastAPI proxy integration for MISP", "IP": app.ClientIP} @app.get('/favicon.ico', include_in_schema=False) async def favicon(): return FileResponse(favicon_path) @app.get("/v1/generate_token_form", tags=["authentication"], summary="UI based access to generate the Auth keys", description="This provides a UI interface to generate the auth keys based on information from your MISP instance." ) def form_post(request: Request): result = "Type a number" return templates.TemplateResponse('generate_token_form.html', context={'request': request, 'result': result}) @app.post("/v1/generate_token_form", tags=["authentication"], include_in_schema=False) def form_post_form(request: Request, expire: str = Form(...), port: str = Form(...), proto: str = Form(...), domain: str = Form(...), auth: str = Form(...)): inputData = str(proto) + ";" + str(port) + ";" + str(domain) + ";" + str(auth) + ";" + str(expire) result = dependencies.encryptString(inputData, app.salt, app.password) reultLen = str(len(result['detail'])) return templates.TemplateResponse('generate_token_form.html', context={'request': request, 'result': result['detail'], 'reultLen': reultLen}) @app.post("/v1/generate_token_json", tags=["authentication"] ) def form_post_json( item: models.formAuthGenItem ): authKeyToken = {} inputData = str(item.proto) + ";" + str(item.port) + ";" + str(item.domain) + ";" + str(item.auth) + ";" + str(item.expire) result = dependencies.encryptString(inputData, app.salt, app.password) authKeyToken['MISP'] = str(item.proto) + '//' + str(item.domain) + ':' + str(item.port) + '/' authKeyToken['validity'] = str(item.expire) authKeyToken['token'] = result['detail'] return authKeyToken @app.get("/v1/openapi.json", tags=["documentations"]) async def get_open_api_endpoint(): response = JSONResponse( get_openapi(title="CRATOS - FastAPI proxy", version=3, routes=app.routes) ) return response @app.get("/v1/help", tags=["documentations"]) async def get_documentation(): """ The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to HTTP APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. :param apiKey: apiKey to authenticate the request :return: WebUI for documentation and tests """ response = get_swagger_ui_html( openapi_url="/openapi.json", title="CRATOS - FastAPI proxy Documentation", ) return response @app.get("/v1/check", tags=["status"], summary="Check connection to MISP") async def check_misp_connection(api_key: APIKey = Depends(getApiToken)): """ Check the connection status to the MISP instance :param apiKey: apiKey to authenticate the request :return: JSON output of the minor informaiton on the MISP instance such as version and pyMISP version """ mispResponse = {} mispURL = ("{}://{}:{}".format(app.configCore['requestConfig']['apiTokenProto'], app.configCore['requestConfig']['apiTokenFQDN'], app.configCore['requestConfig']['apiTokenPort'])) mispAuthKey = app.configCore['requestConfig']['apiTokenAuthKey'] mispResponse = misp.mispGetVersion(mispURL, mispAuthKey) if (not (mispResponse['status']) and (mispResponse['error_num'] == 1)): raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=mispResponse['error'] + ' - ' + str(mispResponse['status_code']) ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 2)): raise HTTPException( status_code=HTTP_503_SERVICE_UNAVAILABLE, detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 3)): raise HTTPException( status_code=HTTP_504_GATEWAY_TIMEOUT , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 4)): raise HTTPException( status_code=HTTP_504_GATEWAY_TIMEOUT , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 5)): raise HTTPException( status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 6)): raise HTTPException( status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE , detail=mispResponse['error'] ) else: mispResponse.pop('status') return(mispResponse) @app.get("/v1/statistics", tags=["info"], summary="Get attribute type statistics from the MISP", description="Connects to the MISP instance and returns statistics API and outputs count of attribute types in a JSON format" ) async def get_misp_statistics(api_key: APIKey = Depends(getApiToken)): """ Get content of MISP warninglists or list avaliable MISP warninglists :param apiKey: apiKey to authenticate the request :return: JSON output of the statictics """ mispResponse = {} mispURL = ("{}://{}:{}".format(app.configCore['requestConfig']['apiTokenProto'], app.configCore['requestConfig']['apiTokenFQDN'], app.configCore['requestConfig']['apiTokenPort'])) mispAuthKey = app.configCore['requestConfig']['apiTokenAuthKey'] mispResponse = misp.mispGetStatistics(mispURL, mispAuthKey) if (not (mispResponse['status']) and (mispResponse['error_num'] == 1)): raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=mispResponse['error'] + ' - ' + str(mispResponse['status_code']) ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 2)): raise HTTPException( status_code=HTTP_503_SERVICE_UNAVAILABLE, detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 3)): raise HTTPException( status_code=HTTP_504_GATEWAY_TIMEOUT , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 4)): raise HTTPException( status_code=HTTP_504_GATEWAY_TIMEOUT , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 5)): raise HTTPException( status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 6)): raise HTTPException( status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE , detail=mispResponse['error'] ) else: mispResponse.pop('status') return(mispResponse) @app.get("/v1/warninglist/id/{warninglistId}/output/{returnedDataType}", tags=["info"], summary="Get lists and content of Warning lists from MISP", description="""<b>Connects to the MISP instance for collecting information around Warninglists</b><br><br> id 0 returns a list of avaliable warninglists and content around this, choosing an id higher than 0 has to be aligned with the MISP warninglist ID. """ ) async def get_misp_warninglist( *, warninglistId: int = Path(title="The ID of the Warninglist to show, 0 lists avaliable Warninglists", ge=0, le=1000), returnedDataType: Annotated[models.ModelOutputType, Path(description="Defines the output that the feed will be presented in.")], api_key: APIKey = Depends(getApiToken) ): """ Get content of MISP warninglists or list avaliable MISP warninglists :param warninglistId: ID number of warninglist :param returnedDataType: What format does the data have to be returned in :return: Contant of warninglist of avaliable warninglists in the choosen output format """ mispResponse = {} mispURL = ("{}://{}:{}".format(app.configCore['requestConfig']['apiTokenProto'], app.configCore['requestConfig']['apiTokenFQDN'], app.configCore['requestConfig']['apiTokenPort'])) mispAuthKey = app.configCore['requestConfig']['apiTokenAuthKey'] mispResponse = misp.mispGetWarninglists(mispURL, mispAuthKey, warninglistId) if (not (mispResponse['status']) and (mispResponse['error_num'] == 1)): raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail=mispResponse['error'] + ' - ' + str(mispResponse['status_code']) ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 2)): raise HTTPException( status_code=HTTP_503_SERVICE_UNAVAILABLE, detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 3)): raise HTTPException( status_code=HTTP_504_GATEWAY_TIMEOUT , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 4)): raise HTTPException( status_code=HTTP_504_GATEWAY_TIMEOUT , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 5)): raise HTTPException( status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE , detail=mispResponse['error'] ) elif (not (mispResponse['status']) and (mispResponse['error_num'] == 6)): raise HTTPException( status_code=HTTP_415_UNSUPPORTED_MEDIA_TYPE , detail=mispResponse['error'] ) else:
warninglistResponse = feeds.formatWarninglistOutputData(mispResponse, returnedDataType)
0
2023-10-08 09:04:06+00:00
8k
MTgeophysics/mtpy-v2
mtpy/imaging/plot_mt_responses.py
[ { "identifier": "get_log_tick_labels", "path": "mtpy/imaging/mtplot_tools/utils.py", "snippet": "def get_log_tick_labels(ax, spacing=1):\n \"\"\"\n\n :param ax: DESCRIPTION\n :type ax: TYPE\n :return: DESCRIPTION\n :rtype: TYPE\n\n \"\"\"\n\n tklabels = []\n xticks = []\n for ...
import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import MultipleLocator from mtpy.imaging.mtplot_tools import ( PlotBase, plot_pt_lateral, get_log_tick_labels, plot_resistivity, plot_phase, plot_tipper_lateral, )
6,192
) return eb_list, label_list def _plot_phase(self, axp, period, z_obj, mode="od", index=0, axp2=None): if mode == "od": comps = ["xy", "yx"] if axp2 is not None: ax_list = [axp, axp2] else: ax_list = [axp, axp] props = [ self.xy_error_bar_properties, self.yx_error_bar_properties, ] elif mode == "d": comps = ["xx", "yy"] props = [ self.xy_error_bar_properties, self.yx_error_bar_properties, ] elif mode == "det": comps = ["xy", "yx", "det"] props = [ self.xy_error_bar_properties, self.yx_error_bar_properties, self.det_error_bar_properties, ] if axp2 is not None: ax_list = [axp, axp2, axp] else: ax_list = [axp, axp, axp] elif mode == "det_only": comps = ["det"] props = [self.det_error_bar_properties] ax_list = [axp] phase_limits = self.set_phase_limits(z_obj.phase, mode=mode) for comp, prop, ax in zip(comps, props, ax_list): if comp == "yx": plot_phase( ax, period, getattr(z_obj, f"phase_{comp}"), getattr(z_obj, f"phase_{self._error_str}_{comp}"), yx=True, **prop, ) else: plot_phase( ax, period, getattr(z_obj, f"phase_{comp}"), getattr(z_obj, f"phase_{self._error_str}_{comp}"), yx=False, **prop, ) ax.set_ylim(phase_limits) if phase_limits[0] < -10 or phase_limits[1] > 100: ax.yaxis.set_major_locator(MultipleLocator(30)) ax.yaxis.set_minor_locator(MultipleLocator(10)) else: ax.yaxis.set_major_locator(MultipleLocator(15)) ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.grid( True, alpha=0.25, which="both", color=(0.25, 0.25, 0.25), lw=0.25, ) ax.set_xscale("log", nonpositive="clip") if "y" not in self.plot_tipper and not self.plot_pt: ax.set_xlabel("Period (s)", self.font_dict) # --> set axes properties if index == 0: axp.set_ylabel("Phase (deg)", self.font_dict) def _plot_tipper( self, axt, period, t_obj, index=0, legend=False, zero_reference=False ): if t_obj is None: return None, None axt, tip_list, tip_label = plot_tipper_lateral( axt, t_obj, self.plot_tipper, self.arrow_real_properties, self.arrow_imag_properties, self.font_size, legend=legend, zero_reference=zero_reference, ) if axt is None: return None, None axt.set_xlabel("Period (s)", fontdict=self.font_dict) axt.yaxis.set_major_locator(MultipleLocator(0.2)) axt.yaxis.set_minor_locator(MultipleLocator(0.1)) axt.set_xlabel("Period (s)", fontdict=self.font_dict) if index == 0: axt.set_ylabel("Tipper", fontdict=self.font_dict) # set th xaxis tick labels to invisible if self.plot_pt: plt.setp(axt.xaxis.get_ticklabels(), visible=False) axt.set_xlabel("") return tip_list, tip_label def _plot_pt( self, axpt, period, pt_obj, index=0, y_shift=0, edge_color=None ): # ----plot phase tensor ellipse--------------------------------------- if self.plot_pt: color_array = self.get_pt_color_array(pt_obj) x_limits = self.set_period_limits(period) # -------------plot ellipses-----------------------------------
# -*- coding: utf-8 -*- """ plots multiple MT responses simultaneously Created on Thu May 30 17:02:39 2013 @author: jpeacock-pr YG: the code there is massey, todo may need to rewrite it sometime """ # ============================================================================ # ============================================================================ class PlotMultipleResponses(PlotBase): """ plots multiple MT responses simultaneously either in single plots or in one plot of sub-figures or in a single plot with subfigures for each component. Arguments: ---------- **fn_list** : list of filenames to plot ie. [fn_1, fn_2, ...], *default* is None **plot_num** : [ 1 | 2 | 3 ] * 1 for just Ex/By and Ey/Bx *default* * 2 for all 4 components * 3 for off diagonal plus the determinant **plot_style** : [ '1' | 'all' | 'compare' ] determines the plotting style: * '1' for plotting each station in a different figure. *default* * 'all' for plotting each station in a subplot all in the same figure * 'compare' for comparing the responses all in one plot. Here the responses are colored from dark to light. This plot can get messy if too many stations are plotted. """ def __init__(self, mt_data, **kwargs): """ Initialize parameters """ self.plot_num = 1 self.plot_style = "1" self.mt_data = mt_data self.include_survey = True super().__init__(**kwargs) self.plot_dict = dict( [ (kk, vv) for kk, vv in zip( ["tip", "pt", "strike", "skew"], [ self.plot_tipper, self.plot_pt, self.plot_strike, self.plot_skew, ], ) ] ) # set arrow properties self.arrow_head_length = 0.03 self.arrow_head_width = 0.03 self.arrow_lw = 0.5 self.plot_model_error = None # ellipse_properties self.ellipse_size = 0.25 # plot on initializing if self.show_plot: self.plot() # ---need to rotate data on setting rotz @property def rotation_angle(self): return self._rotation_angle @rotation_angle.setter def rotation_angle(self, value): """ only a single value is allowed """ for tf in self.mt_data: tf.rotation_angle = value self._rotation_angle = value @property def plot_model_error(self): return self._plot_model_error @plot_model_error.setter def plot_model_error(self, value): if value: self._error_str = "model_error" else: self._error_str = "error" self._plot_model_error = value def _plot_resistivity( self, axr, period, z_obj, mode="od", index=0, axr2=None ): if mode == "od": comps = ["xy", "yx"] props = [ self.xy_error_bar_properties, self.yx_error_bar_properties, ] if axr2 is not None: ax_list = [axr, axr2] else: ax_list = [axr, axr] elif mode == "d": comps = ["xx", "yy"] props = [ self.xy_error_bar_properties, self.yx_error_bar_properties, ] if axr2 is not None: ax_list = [axr, axr2] else: ax_list = [axr, axr] elif mode == "det": comps = ["xy", "yx", "det"] props = [ self.xy_error_bar_properties, self.yx_error_bar_properties, self.det_error_bar_properties, ] if axr2 is not None: ax_list = [axr, axr2, axr] else: ax_list = [axr, axr, axr] elif mode == "det_only": comps = ["det"] props = [self.det_error_bar_properties] ax_list = [axr] res_limits = self.set_resistivity_limits(z_obj.resistivity, mode=mode) x_limits = self.set_period_limits(period) eb_list = [] label_list = [] for comp, prop, ax in zip(comps, props, ax_list): ebax = plot_resistivity( ax, period, getattr(z_obj, f"res_{comp}"), getattr(z_obj, f"res_{self._error_str}_{comp}"), **prop, ) eb_list.append(ebax[0]) label_list.append("$Z_{" + comp + "}$") # --> set axes properties plt.setp(ax.get_xticklabels(), visible=False) ax.set_yscale("log", nonpositive="clip") ax.set_xscale("log", nonpositive="clip") ax.set_xlim(x_limits) ax.set_ylim(res_limits) ax.grid( True, alpha=0.25, which="both", color=(0.25, 0.25, 0.25), lw=0.25, ) if index == 0: axr.set_ylabel( r"App. Res. ($\mathbf{\Omega \cdot m}$)", fontdict=self.font_dict, ) else: plt.setp(axr.get_yticklabels(), visible=False) axr.legend( eb_list, label_list, loc=3, markerscale=1, borderaxespad=0.01, labelspacing=0.07, handletextpad=0.2, borderpad=0.02, ) return eb_list, label_list def _plot_phase(self, axp, period, z_obj, mode="od", index=0, axp2=None): if mode == "od": comps = ["xy", "yx"] if axp2 is not None: ax_list = [axp, axp2] else: ax_list = [axp, axp] props = [ self.xy_error_bar_properties, self.yx_error_bar_properties, ] elif mode == "d": comps = ["xx", "yy"] props = [ self.xy_error_bar_properties, self.yx_error_bar_properties, ] elif mode == "det": comps = ["xy", "yx", "det"] props = [ self.xy_error_bar_properties, self.yx_error_bar_properties, self.det_error_bar_properties, ] if axp2 is not None: ax_list = [axp, axp2, axp] else: ax_list = [axp, axp, axp] elif mode == "det_only": comps = ["det"] props = [self.det_error_bar_properties] ax_list = [axp] phase_limits = self.set_phase_limits(z_obj.phase, mode=mode) for comp, prop, ax in zip(comps, props, ax_list): if comp == "yx": plot_phase( ax, period, getattr(z_obj, f"phase_{comp}"), getattr(z_obj, f"phase_{self._error_str}_{comp}"), yx=True, **prop, ) else: plot_phase( ax, period, getattr(z_obj, f"phase_{comp}"), getattr(z_obj, f"phase_{self._error_str}_{comp}"), yx=False, **prop, ) ax.set_ylim(phase_limits) if phase_limits[0] < -10 or phase_limits[1] > 100: ax.yaxis.set_major_locator(MultipleLocator(30)) ax.yaxis.set_minor_locator(MultipleLocator(10)) else: ax.yaxis.set_major_locator(MultipleLocator(15)) ax.yaxis.set_minor_locator(MultipleLocator(5)) ax.grid( True, alpha=0.25, which="both", color=(0.25, 0.25, 0.25), lw=0.25, ) ax.set_xscale("log", nonpositive="clip") if "y" not in self.plot_tipper and not self.plot_pt: ax.set_xlabel("Period (s)", self.font_dict) # --> set axes properties if index == 0: axp.set_ylabel("Phase (deg)", self.font_dict) def _plot_tipper( self, axt, period, t_obj, index=0, legend=False, zero_reference=False ): if t_obj is None: return None, None axt, tip_list, tip_label = plot_tipper_lateral( axt, t_obj, self.plot_tipper, self.arrow_real_properties, self.arrow_imag_properties, self.font_size, legend=legend, zero_reference=zero_reference, ) if axt is None: return None, None axt.set_xlabel("Period (s)", fontdict=self.font_dict) axt.yaxis.set_major_locator(MultipleLocator(0.2)) axt.yaxis.set_minor_locator(MultipleLocator(0.1)) axt.set_xlabel("Period (s)", fontdict=self.font_dict) if index == 0: axt.set_ylabel("Tipper", fontdict=self.font_dict) # set th xaxis tick labels to invisible if self.plot_pt: plt.setp(axt.xaxis.get_ticklabels(), visible=False) axt.set_xlabel("") return tip_list, tip_label def _plot_pt( self, axpt, period, pt_obj, index=0, y_shift=0, edge_color=None ): # ----plot phase tensor ellipse--------------------------------------- if self.plot_pt: color_array = self.get_pt_color_array(pt_obj) x_limits = self.set_period_limits(period) # -------------plot ellipses-----------------------------------
self.cbax, self.cbpt, = plot_pt_lateral(
3
2023-10-11 22:24:50+00:00
8k
hiroi-sora/Umi-OCR_runtime_windows
UmiOCR-data/site-packages/psutil/_psposix.py
[ { "identifier": "MACOS", "path": "UmiOCR-data/site-packages/psutil/_common.py", "snippet": "MACOS = sys.platform.startswith(\"darwin\")" }, { "identifier": "TimeoutExpired", "path": "UmiOCR-data/site-packages/psutil/_common.py", "snippet": "class TimeoutExpired(Error):\n \"\"\"Raised ...
import glob import os import signal import sys import time import enum from ._common import MACOS from ._common import TimeoutExpired from ._common import memoize from ._common import sdiskusage from ._common import usage_percent from ._compat import PY3 from ._compat import ChildProcessError from ._compat import FileNotFoundError from ._compat import InterruptedError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import unicode from . import _psutil_osx
4,368
If *timeout* != None and process is still alive raise TimeoutExpired. timeout=0 is also possible (either return immediately or raise). """ if pid <= 0: raise ValueError("can't wait for PID 0") # see "man waitpid" interval = 0.0001 flags = 0 if timeout is not None: flags |= os.WNOHANG stop_at = _timer() + timeout def sleep(interval): # Sleep for some time and return a new increased interval. if timeout is not None: if _timer() >= stop_at: raise TimeoutExpired(timeout, pid=pid, name=proc_name) _sleep(interval) return _min(interval * 2, 0.04) # See: https://linux.die.net/man/2/waitpid while True: try: retpid, status = os.waitpid(pid, flags) except InterruptedError: interval = sleep(interval) except ChildProcessError: # This has two meanings: # - PID is not a child of os.getpid() in which case # we keep polling until it's gone # - PID never existed in the first place # In both cases we'll eventually return None as we # can't determine its exit status code. while _pid_exists(pid): interval = sleep(interval) return else: if retpid == 0: # WNOHANG flag was used and PID is still running. interval = sleep(interval) continue elif os.WIFEXITED(status): # Process terminated normally by calling exit(3) or _exit(2), # or by returning from main(). The return value is the # positive integer passed to *exit(). return os.WEXITSTATUS(status) elif os.WIFSIGNALED(status): # Process exited due to a signal. Return the negative value # of that signal. return negsig_to_enum(-os.WTERMSIG(status)) # elif os.WIFSTOPPED(status): # # Process was stopped via SIGSTOP or is being traced, and # # waitpid() was called with WUNTRACED flag. PID is still # # alive. From now on waitpid() will keep returning (0, 0) # # until the process state doesn't change. # # It may make sense to catch/enable this since stopped PIDs # # ignore SIGTERM. # interval = sleep(interval) # continue # elif os.WIFCONTINUED(status): # # Process was resumed via SIGCONT and waitpid() was called # # with WCONTINUED flag. # interval = sleep(interval) # continue else: # Should never happen. raise ValueError("unknown process exit status %r" % status) def disk_usage(path): """Return disk usage associated with path. Note: UNIX usually reserves 5% disk space which is not accessible by user. In this function "total" and "used" values reflect the total and used disk space whereas "free" and "percent" represent the "free" and "used percent" user disk space. """ if PY3: st = os.statvfs(path) else: # pragma: no cover # os.statvfs() does not support unicode on Python 2: # - https://github.com/giampaolo/psutil/issues/416 # - http://bugs.python.org/issue18695 try: st = os.statvfs(path) except UnicodeEncodeError: if isinstance(path, unicode): try: path = path.encode(sys.getfilesystemencoding()) except UnicodeEncodeError: pass st = os.statvfs(path) else: raise # Total space which is only available to root (unless changed # at system level). total = (st.f_blocks * st.f_frsize) # Remaining free space usable by root. avail_to_root = (st.f_bfree * st.f_frsize) # Remaining free space usable by user. avail_to_user = (st.f_bavail * st.f_frsize) # Total space being used in general. used = (total - avail_to_root) if MACOS: # see: https://github.com/giampaolo/psutil/pull/2152 used = _psutil_osx.disk_usage_used(path, used) # Total space which is available to user (same as 'total' but # for the user). total_user = used + avail_to_user # User usage percent compared to the total amount of space # the user can use. This number would be higher if compared # to root's because the user has less space (usually -5%). usage_percent_user = usage_percent(used, total_user, round_=1) # NB: the percentage is -5% than what shown by df due to # reserved blocks that we are currently not considering: # https://github.com/giampaolo/psutil/issues/829#issuecomment-223750462 return sdiskusage( total=total, used=used, free=avail_to_user, percent=usage_percent_user)
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Routines common to all posix systems.""" if MACOS: if PY3: else: enum = None __all__ = ['pid_exists', 'wait_pid', 'disk_usage', 'get_terminal_map'] def pid_exists(pid): """Check whether pid exists in the current process table.""" if pid == 0: # According to "man 2 kill" PID 0 has a special meaning: # it refers to <<every process in the process group of the # calling process>> so we don't want to go any further. # If we get here it means this UNIX platform *does* have # a process with id 0. return True try: os.kill(pid, 0) except ProcessLookupError: return False except PermissionError: # EPERM clearly means there's a process to deny access to return True # According to "man 2 kill" possible error values are # (EINVAL, EPERM, ESRCH) else: return True # Python 3.5 signals enum (contributed by me ^^): # https://bugs.python.org/issue21076 if enum is not None and hasattr(signal, "Signals"): Negsignal = enum.IntEnum( 'Negsignal', dict([(x.name, -x.value) for x in signal.Signals])) def negsig_to_enum(num): """Convert a negative signal value to an enum.""" try: return Negsignal(num) except ValueError: return num else: # pragma: no cover def negsig_to_enum(num): return num def wait_pid(pid, timeout=None, proc_name=None, _waitpid=os.waitpid, _timer=getattr(time, 'monotonic', time.time), # noqa: B008 _min=min, _sleep=time.sleep, _pid_exists=pid_exists): """Wait for a process PID to terminate. If the process terminated normally by calling exit(3) or _exit(2), or by returning from main(), the return value is the positive integer passed to *exit(). If it was terminated by a signal it returns the negated value of the signal which caused the termination (e.g. -SIGTERM). If PID is not a children of os.getpid() (current process) just wait until the process disappears and return None. If PID does not exist at all return None immediately. If *timeout* != None and process is still alive raise TimeoutExpired. timeout=0 is also possible (either return immediately or raise). """ if pid <= 0: raise ValueError("can't wait for PID 0") # see "man waitpid" interval = 0.0001 flags = 0 if timeout is not None: flags |= os.WNOHANG stop_at = _timer() + timeout def sleep(interval): # Sleep for some time and return a new increased interval. if timeout is not None: if _timer() >= stop_at: raise TimeoutExpired(timeout, pid=pid, name=proc_name) _sleep(interval) return _min(interval * 2, 0.04) # See: https://linux.die.net/man/2/waitpid while True: try: retpid, status = os.waitpid(pid, flags) except InterruptedError: interval = sleep(interval) except ChildProcessError: # This has two meanings: # - PID is not a child of os.getpid() in which case # we keep polling until it's gone # - PID never existed in the first place # In both cases we'll eventually return None as we # can't determine its exit status code. while _pid_exists(pid): interval = sleep(interval) return else: if retpid == 0: # WNOHANG flag was used and PID is still running. interval = sleep(interval) continue elif os.WIFEXITED(status): # Process terminated normally by calling exit(3) or _exit(2), # or by returning from main(). The return value is the # positive integer passed to *exit(). return os.WEXITSTATUS(status) elif os.WIFSIGNALED(status): # Process exited due to a signal. Return the negative value # of that signal. return negsig_to_enum(-os.WTERMSIG(status)) # elif os.WIFSTOPPED(status): # # Process was stopped via SIGSTOP or is being traced, and # # waitpid() was called with WUNTRACED flag. PID is still # # alive. From now on waitpid() will keep returning (0, 0) # # until the process state doesn't change. # # It may make sense to catch/enable this since stopped PIDs # # ignore SIGTERM. # interval = sleep(interval) # continue # elif os.WIFCONTINUED(status): # # Process was resumed via SIGCONT and waitpid() was called # # with WCONTINUED flag. # interval = sleep(interval) # continue else: # Should never happen. raise ValueError("unknown process exit status %r" % status) def disk_usage(path): """Return disk usage associated with path. Note: UNIX usually reserves 5% disk space which is not accessible by user. In this function "total" and "used" values reflect the total and used disk space whereas "free" and "percent" represent the "free" and "used percent" user disk space. """ if PY3: st = os.statvfs(path) else: # pragma: no cover # os.statvfs() does not support unicode on Python 2: # - https://github.com/giampaolo/psutil/issues/416 # - http://bugs.python.org/issue18695 try: st = os.statvfs(path) except UnicodeEncodeError: if isinstance(path, unicode): try: path = path.encode(sys.getfilesystemencoding()) except UnicodeEncodeError: pass st = os.statvfs(path) else: raise # Total space which is only available to root (unless changed # at system level). total = (st.f_blocks * st.f_frsize) # Remaining free space usable by root. avail_to_root = (st.f_bfree * st.f_frsize) # Remaining free space usable by user. avail_to_user = (st.f_bavail * st.f_frsize) # Total space being used in general. used = (total - avail_to_root) if MACOS: # see: https://github.com/giampaolo/psutil/pull/2152 used = _psutil_osx.disk_usage_used(path, used) # Total space which is available to user (same as 'total' but # for the user). total_user = used + avail_to_user # User usage percent compared to the total amount of space # the user can use. This number would be higher if compared # to root's because the user has less space (usually -5%). usage_percent_user = usage_percent(used, total_user, round_=1) # NB: the percentage is -5% than what shown by df due to # reserved blocks that we are currently not considering: # https://github.com/giampaolo/psutil/issues/829#issuecomment-223750462 return sdiskusage( total=total, used=used, free=avail_to_user, percent=usage_percent_user)
@memoize
2
2023-10-09 01:31:01+00:00
8k
MorvanZhou/rethink
src/rethink/depend/mongita/collection.py
[ { "identifier": "support_alert", "path": "src/rethink/depend/mongita/common.py", "snippet": "def support_alert(func):\n \"\"\"\n Provide smart tips if the user tries to use un-implemented / deprecated\n known kwargs.\n \"\"\"\n\n @functools.wraps(func)\n def inner(*args, **kwargs):\n ...
import collections import copy import datetime import functools import re import bson import sortedcontainers from .common import support_alert, ASCENDING, DESCENDING, MetaStorageObject from .cursor import Cursor, _validate_sort from .errors import (MongitaError, MongitaNotImplementedError, DuplicateKeyError, InvalidName, OperationFailure) from .read_concern import ReadConcern from .results import InsertOneResult, InsertManyResult, DeleteResult, UpdateResult from .write_concern import WriteConcern
5,048
sort = _validate_sort(sort) return self.__find_one(filter, sort, skip) @support_alert def find(self, filter=None, sort=None, limit=None, skip=None): """ Return a cursor of all matching documents. :param filter dict: :param sort list[(key, direction)]|None: :param limit int|None: :param skip int|None: :rtype: cursor.Cursor """ filter = filter or {} _validate_filter(filter) if sort is not None: sort = _validate_sort(sort) if limit is not None and not isinstance(limit, int): raise TypeError('Limit must be an integer') if skip is not None: if not isinstance(skip, int): raise TypeError('Skip must be an integer') if skip < 0: raise ValueError('Skip must be >=0') return Cursor(self.__find, filter, sort, limit, skip) def __update_doc(self, doc_id, update): """ Given a doc_id and an update dict, find the document and safely update it. Returns the updated document :param doc_id str: :param update dict: :rtype: dict """ doc = self._engine.get_doc(self.full_name, doc_id) for update_op, update_op_dict in update.items(): _update_item_in_doc(update_op, update_op_dict, doc) assert self._engine.put_doc(self.full_name, doc) return dict(doc) @support_alert async def update_one(self, filter, update, upsert=False): """ Find one document matching the filter and update it. The 'upsert' parameter is not supported. :param filter dict: :param update dict: :param upsert bool: :rtype: results.UpdateResult """ _validate_filter(filter) _validate_update(update) self.__create() if upsert: raise MongitaNotImplementedError("Mongita does not support 'upsert' on " "update operations. Use `replace_one`.") with self._engine.lock: doc_ids = list(self.__find_ids(filter)) matched_count = len(doc_ids) if not matched_count: return UpdateResult(matched_count, 0) metadata = self.__get_metadata() doc = self.__update_doc(doc_ids[0], update) self.__update_indicies([doc], metadata) return UpdateResult(matched_count, 1) @support_alert async def update_many(self, filter, update, upsert=False): """ Update every document matched by the filter. The 'upsert' parameter is not supported. :param filter dict: :param update dict: :param upsert bool: :rtype: results.UpdateResult """ _validate_filter(filter) _validate_update(update) self.__create() if upsert: raise MongitaNotImplementedError("Mongita does not support 'upsert' " "on update operations. Use `replace_one`.") success_docs = [] matched_cnt = 0 with self._engine.lock: doc_ids = list(self.__find_ids(filter)) metadata = self.__get_metadata() for doc_id in doc_ids: doc = self.__update_doc(doc_id, update) success_docs.append(doc) matched_cnt += 1 self.__update_indicies(success_docs, metadata) return UpdateResult(matched_cnt, len(success_docs)) @support_alert async def delete_one(self, filter): """ Delete one document matching the filter. :param filter dict: :rtype: results.DeleteResult """ _validate_filter(filter) self.__create() with self._engine.lock: doc_id = self.__find_one_id(filter) if not doc_id:
_SUPPORTED_FILTER_OPERATORS = ('$in', '$eq', '$gt', '$gte', '$lt', '$lte', '$ne', '$nin') _SUPPORTED_UPDATE_OPERATORS = ('$set', '$inc', '$push') _DEFAULT_METADATA = { 'options': {}, 'indexes': {}, '_id': str(bson.ObjectId()), } # FROM docs.mongodb.com/manual/reference/bson-type-comparison-order/#comparison-sort-order SORT_ORDER = { int: b'\x02', float: b'\x02', str: b'\x03', object: b'\x04', list: b'\x05', bytes: b'\x06', bson.ObjectId: b'\x07', bool: b'\x08', datetime.datetime: b'\t', re.Pattern: b'\n', } def _validate_filter(filter): """ Validate the 'filter' parameter. This is near the top of most public methods. :param filter dict: :rtype: None """ if not isinstance(filter, dict): raise MongitaError("The filter parameter must be a dict, not %r" % type(filter)) for k in filter.keys(): if not isinstance(k, str): raise MongitaError("Filter keys must be strings, not %r" % type(filter)) _id = filter.get('_id') if _id: if not isinstance(_id, (bson.ObjectId, str, dict)): raise MongitaError("If present, the '_id' filter must be a bson ObjectId, string, or a dict") for query_ops in filter.values(): if isinstance(query_ops, dict): for op in query_ops.keys(): if op.startswith('$') and op not in _SUPPORTED_FILTER_OPERATORS: raise MongitaError( "Mongita does not support %r. These filter operators are " "supported: %r" % (op, _SUPPORTED_FILTER_OPERATORS)) def _validate_update(update): """ Validate the 'update' parameter. This is near the top of the public update methods. :param update dict: :rtype: None """ if not isinstance(update, dict): raise MongitaError("The update parameter must be a dict, not %r" % type(update)) for k in update.keys(): if k in _SUPPORTED_UPDATE_OPERATORS: continue if k.startswith('$'): raise MongitaNotImplementedError( "Mongita does not support %r. These update operators are " \ "supported: %r." % (k, _SUPPORTED_UPDATE_OPERATORS)) raise MongitaError( "In update operations, you must use one of the supported " \ "update operators %r." % (_SUPPORTED_UPDATE_OPERATORS,)) for update_dict in update.values(): if not isinstance(update_dict, dict): raise MongitaError("If present, the update operator must be a dict, " "not %r" % type(update_dict)) _id = update_dict.get('_id') if _id: if not isinstance(_id, (str, bson.ObjectId)): raise MongitaError("The update _id must be a bson ObjectId or a string") def _validate_doc(doc): """ Validate the 'doc' parameter. This is near the top of the public insert / replace methods. :param doc dict: :rtype: None """ if not isinstance(doc, dict): raise MongitaError("The document must be a dict, not %r" % type(doc)) _id = doc.get('_id') if _id: if not isinstance(_id, (bson.ObjectId, str)): raise MongitaError("The document _id must be a bson ObjectId, a string, or not present") for k in doc.keys(): if not k or k.startswith('$'): raise InvalidName("All document keys must be truthy and cannot start with '$'.") def _overlap(iter_a, iter_b): """ Return if there is any overlap between iter_a and iter_b from https://stackoverflow.com/questions/3170055 :param iter_a list: :param iter_b list: :rtype: bool """ return not set(iter_a).isdisjoint(iter_b) def _doc_matches_agg(doc_v, query_ops): """ Return whether an individual document value matches a dict of query operations. Usually there will be one query_op but sometimes there are many. e.g. collection.find({'path.to.doc_v': {'$query_op': query_val}}) The loop returns False whenever we know for sure that the document is not part of the query. At the end return True :param doc_v: The value in the doc to compare against :param query_ops {$query_op: query_val}: :returns: Whether the document value matches all query operators :rtype: bool """ if any(k.startswith('$') for k in query_ops.keys()): for query_op, query_val in query_ops.items(): if query_op == '$eq': if doc_v != query_val: return False elif query_op == '$ne': if doc_v == query_val: return False elif query_op == '$in': if not isinstance(query_val, (list, tuple, set)): raise MongitaError("'$in' requires an iterable") if not ((isinstance(doc_v, list) and _overlap(doc_v, query_val)) or (doc_v in query_val)): return False elif query_op == '$nin': if not isinstance(query_val, (list, tuple, set)): raise MongitaError("'$nin' requires an iterable") if (isinstance(doc_v, list) and _overlap(doc_v, query_val)) \ or (doc_v in query_val): return False elif query_op == '$lt': try: if doc_v >= query_val: return False except TypeError: return False elif query_op == '$lte': try: if doc_v > query_val: return False except TypeError: return False elif query_op == '$gt': try: if doc_v <= query_val: return False except TypeError: return False elif query_op == '$gte': try: if doc_v < query_val: return False except TypeError: return False # agg_k check is in _validate_filter return True else: return doc_v == query_ops def _doc_matches_slow_filters(doc, slow_filters): """ Given an entire doc, return whether that doc matches every filter item in the slow_filters dict. A slow_filter is just the set of filters that we didn't have an index for. :param doc dict: :param slow_filters dict: :rtype: bool """ for doc_key, query_ops in slow_filters.items(): if isinstance(query_ops, dict): doc_v = _get_item_from_doc(doc, doc_key) if _doc_matches_agg(doc_v, query_ops): continue return False item_from_doc = _get_item_from_doc(doc, doc_key) if isinstance(item_from_doc, list) and query_ops in item_from_doc: continue if item_from_doc == query_ops: continue return False return True def _ids_given_irange_filters(matched_keys, idx, **kwargs): """ Given an existing set of matched_keys, a SortedDict (idx), and a set of kwargs to apply to SortedDict.irange, return all keys that match both the irange and the existing matched_keys :param matched_keys set: :param idx sortedcontainers.SortedDict: :param kwargs dict: irange filters :rtype set: """ clean_idx_key = kwargs.get('minimum') or kwargs.get('maximum') # if 'minimum' in kwargs: # kwargs['maximum'] = (bytes([ord(kwargs['minimum'][0]) + 1]), None) # if 'maximum' in kwargs: # kwargs['minimum'] = (bytes([ord(kwargs['maximum'][0]) - 1]), None) ret = set(idx.irange(**kwargs)) ret = set(key for key in ret if key[0] == clean_idx_key[0]) return set.intersection(matched_keys, ret) def _idx_filter_sort(query_op_tup): """ For performance, the order of filtering matters. It's best to do equality first before comparsion. Not-equal should be last becase a lot of values are liable to be returned. In and nin vary in how much they matter so go with not-equal :param query_op_tup (query_op, query_val): :rtype: bool """ query_op, _ = query_op_tup return (query_op == '$eq', query_op in ('$lt', '$lte', '$gt', '$gte')) def _get_ids_from_idx(idx, query_ops): """ Returns the ids that match a set of query_ops in an index. :param idx SortedDict: :param query_ops str|dict: :rtype: set """ if not isinstance(query_ops, dict): return set(idx.get(_make_idx_key(query_ops), set())) if not set(query_ops.keys()).intersection(_SUPPORTED_FILTER_OPERATORS): if _make_idx_key(query_ops) in idx.keys(): return idx[_make_idx_key(query_ops)] return set() keys_remain = set(idx.keys()) keys_not_cursed = keys_remain.copy() keys_cursed = set() for query_op, query_val in sorted(query_ops.items(), key=_idx_filter_sort, reverse=True): clean_idx_key = _make_idx_key(query_val) if query_op == '$eq': keys_remain = {clean_idx_key} if clean_idx_key in keys_remain else set() elif query_op == '$ne': _keys_cursed = set(k for k in keys_not_cursed if k == clean_idx_key) keys_remain -= _keys_cursed keys_not_cursed -= _keys_cursed keys_cursed.update(_keys_cursed) elif query_op == '$lt': keys_remain = _ids_given_irange_filters(keys_remain, idx, maximum=clean_idx_key, inclusive=(False, False)) elif query_op == '$lte': keys_remain = _ids_given_irange_filters(keys_remain, idx, maximum=clean_idx_key, inclusive=(False, True)) elif query_op == '$gt': keys_remain = _ids_given_irange_filters(keys_remain, idx, minimum=clean_idx_key, inclusive=(False, False)) elif query_op == '$gte': keys_remain = _ids_given_irange_filters(keys_remain, idx, minimum=clean_idx_key, inclusive=(True, False)) elif query_op == '$in': if not isinstance(query_val, (list, tuple, set)): raise MongitaError("'$in' requires an iterable") clean_q_val = [_make_idx_key(e) for e in query_val] keys_remain = set(k for k in keys_remain if k in clean_q_val) elif query_op == '$nin': if not isinstance(query_val, (list, tuple, set)): raise MongitaError("'$nin' requires an iterable") clean_q_val = [_make_idx_key(e) for e in query_val] _keys_cursed = set(k for k in keys_not_cursed if k in clean_q_val) keys_remain -= _keys_cursed keys_not_cursed -= _keys_cursed keys_cursed.update(_keys_cursed) # validation of options is done earlier ids_cursed = set() for k in keys_cursed: ids_cursed.update(idx[k]) ret = set() for k in keys_remain: ret.update(idx[k]) ret -= ids_cursed return ret def _failed_update_error(update_op, update_op_dict, doc, msg): """Helper for raising errors on update""" return MongitaError("Cannot apply operation %r to %r (%s)" % ({update_op: update_op_dict}, doc, msg)) def _update_item_in_doc(update_op, update_op_dict, doc): """ Given an $update_op, a {doc_key: value} update_op_dict, and a doc, Update the doc in-place at doc_key with the update operation. e.g. doc = {'hi': 'ma'} update_op = '$set' update_op_dict {'ma': 'pa'} -> {'hi': 'pa'} :param update_op str: :param update_op_dict {str: value}: :param doc dict: :rtype: None """ for doc_key, value in update_op_dict.items(): ds, last_key = _get_datastructure_from_doc(doc, doc_key) if isinstance(ds, list): _rightpad(ds, last_key) if ds is None: raise _failed_update_error(update_op, update_op_dict, doc, "Could not find item") if update_op == '$set': ds[last_key] = value elif update_op == '$inc': if not isinstance(value, (int, float)): raise _failed_update_error(update_op, update_op_dict, doc, "Increment was not numeric") elif not isinstance(ds.get(last_key), (int, float)): raise _failed_update_error(update_op, update_op_dict, doc, "Document value was not numeric") ds[last_key] += value elif update_op == '$push': if isinstance(ds.get(last_key), list): ds[last_key].append(value) elif last_key not in ds: ds[last_key] = [value] else: raise _failed_update_error(update_op, update_op_dict, doc, "Document value was not a list") # Should never get an update key we don't recognize b/c _validate_update def _rightpad(item, desired_length): """ Given a list, pad to the desired_length with Nones This might be slow but it modifies the list in place :param item list: :param desired_length int: :rtype: None """ pad_len = desired_length - len(item) + 1 for _ in range(pad_len): item.append(None) def _get_datastructure_from_doc(doc, key): """ Get a pass-by-reference data structure from the document so that we can update it in-place. This dives deep into the document with the key parameter which uses dot notation. e.g. doc = {'deep': {'nested': {'list': [1, 2, 3]}}} key = 'deep.nested.list.5' -> a reference to [1, 2, 3, None, None] and 5 :param doc dict: :param key str: :returns: the datastructure and the final accessor :rtype: list|dict|None, value """ if '.' not in key: return doc, key item = doc levels = key.split('.') levels, last_level = levels[:-1], levels[-1] for level in levels: if isinstance(item, list): try: level_int = int(level) except ValueError: return None, None if level_int < 0: return None, None try: item = item[level_int] except IndexError: _rightpad(item, level_int) item = item[level_int] or {} elif isinstance(item, dict): if level not in item or not isinstance(item[level], (list, dict)): item[level] = {} item = item[level] else: return None, None if isinstance(item, list): try: last_level = int(last_level) except ValueError: return None, None return item, last_level def _get_item_from_doc(doc, key): """ Get an item from the document given a key which might use dot notation. e.g. doc = {'deep': {'nested': {'list': ['a', 'b', 'c']}}} key = 'deep.nested.list.1' -> 'b' :param doc dict: :param key str: :rtype: value """ if '.' in key: item = doc for level in key.split('.'): if isinstance(item, list): try: level_int = int(level) except ValueError: return None try: item = item[level_int] except IndexError: return None elif isinstance(item, dict): item = item.get(level, {}) else: return None return item or None return doc.get(key) def _make_idx_key(idx_key): """ MongoDB is very liberal when it comes to what keys it can compare on. When we get something weird, it makes sense to just store it as a hashable key :param idx_key value: :rtype: hashable value """ if isinstance(idx_key, collections.abc.Hashable): return _sort_tup(idx_key) try: return _sort_tup(str(bson.encode(idx_key))) except TypeError: return _sort_tup(str(bson.encode({'idx_key': idx_key}))) def _update_idx_doc_with_new_documents(documents, idx_doc): """ Update an idx_doc given documents which were just inserted / modified / etc :param documents list[dict]: :param idx_doc {key_str: str, direction: int idx: SortedDict, ...}: :rtype: None """ documents = list(documents) _remove_docs_from_idx_doc(set(d['_id'] for d in documents), idx_doc) key_str = idx_doc['key_str'] new_idx = sortedcontainers.SortedDict(idx_doc['idx']) for doc in documents: item_from_doc = _get_item_from_doc(doc, key_str) if isinstance(item_from_doc, list): for item in item_from_doc: key = _make_idx_key(item) new_idx.setdefault(key, set()).add(doc['_id']) key = _make_idx_key(item_from_doc) new_idx.setdefault(key, set()).add(doc['_id']) reverse = idx_doc['direction'] == DESCENDING idx_doc['idx'] = sortedcontainers.SortedDict(sorted(new_idx.items(), reverse=reverse)) def _remove_docs_from_idx_doc(doc_ids, idx_doc): """ Update an idx_doc given documents which were just removed :param doc_ids set[str]: :param idx_doc {key_str: str, direction: int idx: SortedDict, ...}: :rtype: None """ idx_doc_idx = idx_doc['idx'] for k in idx_doc_idx.keys(): idx_doc_idx[k] -= doc_ids def _sort_tup(item): """ Get sort tuple of item type according to mongodb rules :param item Value: :rtype: (int, Value) """ try: return (SORT_ORDER[type(item)], item) except KeyError: pass # this assumes the item is None but could catch other # types if we are not careful. Sorting bugs are minor though return (b'\x01', item) def _sort_func(doc, sort_key): """ Sorter to sort different types according to MongoDB rules :param doc dict: :param sort_key str: :rtype: tuple """ item = _get_item_from_doc(doc, sort_key) return _sort_tup(item) def _sort_docs(docs, sort_list): """ Given the sort list provided in the .sort() method, sort the documents in place. from https://docs.python.org/3/howto/sorting.html :param docs list[dict]: :param sort_list list[(key, direction)] :rtype: None """ for sort_key, direction in reversed(sort_list): _sort_func_partial = functools.partial(_sort_func, sort_key=sort_key) if direction == ASCENDING: docs.sort(key=_sort_func_partial) elif direction == DESCENDING: docs.sort(key=_sort_func_partial, reverse=True) # validation on direction happens in cursor def _split_filter(filter, metadata): """ Split the filter into indx_ops and slow_filters which are later used differently :param filter {doc_key: query_ops}: :param metadata dict: :rtype: {doc_key: query_ops}, [(SortedDict idx, dict query_ops), ...] """ slow_filters = {} indx_ops = [] indexes = metadata.get('indexes', {}) for doc_key, query_ops in filter.items(): if doc_key + '_1' in indexes: indx_ops.append((indexes[doc_key + '_1']['idx'], query_ops)) elif doc_key + '_-1' in indexes: indx_ops.append((indexes[doc_key + '_-1']['idx'], query_ops)) else: slow_filters[doc_key] = query_ops return slow_filters, indx_ops def _apply_indx_ops(indx_ops): """ Return all doc_ids that can be found through the index filters :param indx_ops {idx_key: query_ops}: :param indexes dict: :rtype: set """ doc_ids_so_far = set() for idx, query_ops in indx_ops: doc_ids = _get_ids_from_idx(idx, query_ops) if not doc_ids: return set() if doc_ids_so_far: doc_ids_so_far = doc_ids_so_far.intersection(doc_ids) if not doc_ids_so_far: return set() else: doc_ids_so_far = doc_ids return doc_ids_so_far class Collection(): UNIMPLEMENTED = ['aggregate', 'aggregate_raw_batches', 'bulk_write', 'codec_options', 'create_indexes', 'drop', 'drop_indexes', 'ensure_index', 'estimated_document_count', 'find_one_and_delete', 'find_one_and_replace', 'find_one_and_update', 'find_raw_batches', 'inline_map_reduce', 'list_indexes', 'map_reduce', 'next', 'options', 'read_concern', 'read_preference', 'rename', 'watch', ] DEPRECATED = ['reindex', 'parallel_scan', 'initialize_unordered_bulk_op', 'initialize_ordered_bulk_op', 'group', 'count', 'insert', 'save', 'update', 'remove', 'find_and_modify', 'ensure_index'] def __init__(self, collection_name, database, write_concern=None, read_concern=None): self.name = collection_name self.database = database self._write_concern = write_concern or WriteConcern() self._read_concern = read_concern or ReadConcern() self._engine = database._engine self._existence_verified = False self._base_location = f'{database.name}.{collection_name}' def __repr__(self): return "Collection(%s, %r)" % (repr(self.database), self.name) def __getattr__(self, attr): """ First check for deprecated / unimplemented. Then, MongoDB has this weird thing where there can be dots in a collection name. """ if attr in self.DEPRECATED: raise MongitaNotImplementedError.create_depr("Collection", attr) if attr in self.UNIMPLEMENTED: raise MongitaNotImplementedError.create("Collection", attr) return Collection(collection_name=self.name + '.' + attr, database=self.database) @property def full_name(self): return self._base_location @property def write_concern(self): return self._write_concern @property def read_concern(self): return self._read_concern def with_options(self, **kwargs): write_concern = kwargs.pop('write_concern', None) read_concern = kwargs.pop('read_concern', None) if kwargs: raise MongitaNotImplementedError("The method 'with_options' doesn't yet " "accept %r" % kwargs) return Collection(self.name, self.database, write_concern=write_concern, read_concern=read_concern) def __create(self): """ MongoDB doesn't require you to explicitly create collections. They are created when first accessed. This creates the collection and is called early in modifier methods. """ if self._existence_verified: return with self._engine.lock: if not self._engine.get_metadata(self._base_location): self._engine.create_path(self._base_location) metadata = MetaStorageObject(copy.deepcopy(_DEFAULT_METADATA)) assert self._engine.put_metadata(self._base_location, metadata) self.database.__create(self.name) self._existence_verified = True def __insert_one(self, document): """ Insert a single document. :param document dict: :rtype: None """ success = self._engine.put_doc(self.full_name, document, no_overwrite=True) if not success: assert self._engine.doc_exists(self.full_name, document['_id']) raise DuplicateKeyError("Document %r already exists" % document['_id']) @support_alert async def insert_one(self, document): """ Insert a single document. :param document dict: :rtype: results.InsertOneResult """ _validate_doc(document) document = copy.deepcopy(document) document['_id'] = document.get('_id') or bson.ObjectId() self.__create() with self._engine.lock: metadata = self.__get_metadata() self.__insert_one(document) self.__update_indicies([document], metadata) return InsertOneResult(document['_id']) @support_alert async def insert_many(self, documents, ordered=True): """ Insert documents. If ordered, stop inserting if there is an error. If not ordered, all operations are attempted :param list documents: :param bool ordered: :rtype: results.InsertManyResult """ if not isinstance(documents, list): raise MongitaError("Documents must be a list") ready_docs = [] for doc in documents: _validate_doc(doc) doc = copy.deepcopy(doc) doc['_id'] = doc.get('_id') or bson.ObjectId() ready_docs.append(doc) self.__create() success_docs = [] exception = None with self._engine.lock: metadata = self.__get_metadata() for doc in ready_docs: try: self.__insert_one(doc) success_docs.append(doc) except Exception as ex: if ordered: self.__update_indicies(success_docs, metadata) raise MongitaError("Ending insert_many because of error") from ex exception = ex continue self.__update_indicies(success_docs, metadata) if exception: raise MongitaError("Not all documents inserted") from exception return InsertManyResult(success_docs) @support_alert async def replace_one(self, filter, replacement, upsert=False): """ Replace one document. If no document was found with the filter, and upsert is True, insert the replacement. :param filter dict: :param replacement dict: :param bool upsert: :rtype: results.UpdateResult """ filter = filter or {} _validate_filter(filter) _validate_doc(replacement) self.__create() replacement = copy.deepcopy(replacement) with self._engine.lock: doc_id = self.__find_one_id(filter, upsert=upsert) if not doc_id: if upsert: metadata = self.__get_metadata() replacement['_id'] = replacement.get('_id') or bson.ObjectId() self.__insert_one(replacement) self.__update_indicies([replacement], metadata) return UpdateResult(0, 1, replacement['_id']) return UpdateResult(0, 0) replacement['_id'] = doc_id metadata = self.__get_metadata() assert self._engine.put_doc(self.full_name, replacement) self.__update_indicies([replacement], metadata) return UpdateResult(1, 1) def __find_one_id(self, filter, sort=None, skip=None, upsert=False): """ Given the filter, return a single object_id or None. :param filter dict: :param sort list[(key, direction)]|None :param skip int|None :rtype: str|None """ if not filter and not sort: return self._engine.find_one_id(self._base_location) if '_id' in filter: if upsert or self._engine.doc_exists(self.full_name, filter['_id']): return filter['_id'] return None try: return next(self.__find_ids(filter, sort, skip=skip)) except StopIteration: return None def __find_one(self, filter, sort, skip): """ Given the filter, return a single doc or None. :param filter dict: :param sort list[(key, direction)]|None :param skip int|None :rtype: dict|None """ doc_id = self.__find_one_id(filter, sort, skip) if doc_id: doc = self._engine.get_doc(self.full_name, doc_id) if doc: return copy.deepcopy(doc) def __find_ids(self, filter, sort=None, limit=None, skip=None, metadata=None): """ Given a filter, find all doc_ids that match this filter. Be sure to also sort and limit them. This method will download documents for non-indexed filters (slow_filters). Downloaded docs are cached in the engine layer so performance cost is minimal. This method returns a generator :param filter dict: :param sort list[(key, direction)]|None: :param limit int|None: :param skip int|None: :param metadata dict|None: :rtype: Generator(list[str]) """ filter = filter or {} sort = sort or [] if limit == 0: return metadata = metadata or self.__get_metadata() slow_filters, indx_ops = _split_filter(filter, metadata) # If we have index ops, we can use those ids as a starting point. # otherwise, we need to get all_ids and filter one-by-one if indx_ops: doc_ids = _apply_indx_ops(indx_ops) else: doc_ids = self._engine.list_ids(self._base_location) if not doc_ids: return if sort: docs_to_return = [] for doc_id in doc_ids: doc = self._engine.get_doc(self.full_name, doc_id) if _doc_matches_slow_filters(doc, slow_filters): docs_to_return.append(doc) _sort_docs(docs_to_return, sort) if skip: docs_to_return = docs_to_return[skip:] if limit is None: for doc in docs_to_return: yield doc['_id'] else: i = 0 for doc in docs_to_return: yield doc['_id'] i += 1 if i == limit: return return if skip: doc_ids = doc_ids[skip:] if limit is None: for doc_id in doc_ids: doc = self._engine.get_doc(self.full_name, doc_id) if doc and _doc_matches_slow_filters(doc, slow_filters): yield doc['_id'] return i = 0 for doc_id in doc_ids: doc = self._engine.get_doc(self.full_name, doc_id) if _doc_matches_slow_filters(doc, slow_filters): yield doc['_id'] i += 1 if i == limit: return def __find(self, filter, sort=None, limit=None, skip=None, metadata=None, shallow=False): """ Given a filter, find all docs that match this filter. This method returns a generator. :param filter dict: :param sort list[(key, direction)]|None: :param limit int|None: :param skip int|None: :param metadata dict|None: :rtype: Generator(list[dict]) """ gen = self.__find_ids(filter, sort, limit, skip, metadata=metadata) if shallow: for doc_id in gen: doc = self._engine.get_doc(self.full_name, doc_id) yield doc else: for doc_id in gen: doc = self._engine.get_doc(self.full_name, doc_id) yield copy.deepcopy(doc) @support_alert async def find_one(self, filter=None, sort=None, skip=None): """ Return the first matching document. :param filter dict: :param sort list[(key, direction)]|None: :param skip int|None: :rtype: dict|None """ filter = filter or {} _validate_filter(filter) if sort is not None: sort = _validate_sort(sort) return self.__find_one(filter, sort, skip) @support_alert def find(self, filter=None, sort=None, limit=None, skip=None): """ Return a cursor of all matching documents. :param filter dict: :param sort list[(key, direction)]|None: :param limit int|None: :param skip int|None: :rtype: cursor.Cursor """ filter = filter or {} _validate_filter(filter) if sort is not None: sort = _validate_sort(sort) if limit is not None and not isinstance(limit, int): raise TypeError('Limit must be an integer') if skip is not None: if not isinstance(skip, int): raise TypeError('Skip must be an integer') if skip < 0: raise ValueError('Skip must be >=0') return Cursor(self.__find, filter, sort, limit, skip) def __update_doc(self, doc_id, update): """ Given a doc_id and an update dict, find the document and safely update it. Returns the updated document :param doc_id str: :param update dict: :rtype: dict """ doc = self._engine.get_doc(self.full_name, doc_id) for update_op, update_op_dict in update.items(): _update_item_in_doc(update_op, update_op_dict, doc) assert self._engine.put_doc(self.full_name, doc) return dict(doc) @support_alert async def update_one(self, filter, update, upsert=False): """ Find one document matching the filter and update it. The 'upsert' parameter is not supported. :param filter dict: :param update dict: :param upsert bool: :rtype: results.UpdateResult """ _validate_filter(filter) _validate_update(update) self.__create() if upsert: raise MongitaNotImplementedError("Mongita does not support 'upsert' on " "update operations. Use `replace_one`.") with self._engine.lock: doc_ids = list(self.__find_ids(filter)) matched_count = len(doc_ids) if not matched_count: return UpdateResult(matched_count, 0) metadata = self.__get_metadata() doc = self.__update_doc(doc_ids[0], update) self.__update_indicies([doc], metadata) return UpdateResult(matched_count, 1) @support_alert async def update_many(self, filter, update, upsert=False): """ Update every document matched by the filter. The 'upsert' parameter is not supported. :param filter dict: :param update dict: :param upsert bool: :rtype: results.UpdateResult """ _validate_filter(filter) _validate_update(update) self.__create() if upsert: raise MongitaNotImplementedError("Mongita does not support 'upsert' " "on update operations. Use `replace_one`.") success_docs = [] matched_cnt = 0 with self._engine.lock: doc_ids = list(self.__find_ids(filter)) metadata = self.__get_metadata() for doc_id in doc_ids: doc = self.__update_doc(doc_id, update) success_docs.append(doc) matched_cnt += 1 self.__update_indicies(success_docs, metadata) return UpdateResult(matched_cnt, len(success_docs)) @support_alert async def delete_one(self, filter): """ Delete one document matching the filter. :param filter dict: :rtype: results.DeleteResult """ _validate_filter(filter) self.__create() with self._engine.lock: doc_id = self.__find_one_id(filter) if not doc_id:
return DeleteResult(0)
14
2023-10-08 08:01:07+00:00
8k
ingra14m/Specular-Gaussians-MLP
scene/dataset_readers.py
[ { "identifier": "read_extrinsics_text", "path": "scene/colmap_loader.py", "snippet": "def read_extrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n images = {}\n with open(path, \"r\") as fid:\n while T...
import os import sys import numpy as np import json import imageio import cv2 as cv from PIL import Image from typing import NamedTuple, Optional from scene.colmap_loader import read_extrinsics_text, read_intrinsics_text, qvec2rotmat, \ read_extrinsics_binary, read_intrinsics_binary, read_points3D_binary, read_points3D_text from utils.graphics_utils import getWorld2View2, focal2fov, fov2focal from glob import glob from pathlib import Path from plyfile import PlyData, PlyElement from utils.sh_utils import SH2RGB from scene.gaussian_model import BasicPointCloud from utils.camera_utils import camera_nerfies_from_JSON
4,595
def load_K_Rt_from_P(filename, P=None): if P is None: lines = open(filename).read().splitlines() if len(lines) == 4: lines = lines[1:] lines = [[x[0], x[1], x[2], x[3]] for x in (x.split(" ") for x in lines)] P = np.asarray(lines).astype(np.float32).squeeze() out = cv.decomposeProjectionMatrix(P) K = out[0] R = out[1] t = out[2] K = K / K[2, 2] pose = np.eye(4, dtype=np.float32) pose[:3, :3] = R.transpose() pose[:3, 3] = (t[:3] / t[3])[:, 0] return K, pose def getNerfppNorm(cam_info): def get_center_and_diag(cam_centers): cam_centers = np.hstack(cam_centers) avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True) center = avg_cam_center dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True) diagonal = np.max(dist) return center.flatten(), diagonal cam_centers = [] for cam in cam_info: W2C = getWorld2View2(cam.R, cam.T) C2W = np.linalg.inv(W2C) cam_centers.append(C2W[:3, 3:4]) center, diagonal = get_center_and_diag(cam_centers) radius = diagonal * 1.1 translate = -center return {"translate": translate, "radius": radius} def readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder): cam_infos = [] num_frames = len(cam_extrinsics) for idx, key in enumerate(cam_extrinsics): sys.stdout.write('\r') # the exact output you're looking for: sys.stdout.write("Reading camera {}/{}".format(idx + 1, len(cam_extrinsics))) sys.stdout.flush() extr = cam_extrinsics[key] intr = cam_intrinsics[extr.camera_id] height = intr.height width = intr.width uid = intr.id R = np.transpose(qvec2rotmat(extr.qvec)) T = np.array(extr.tvec) if intr.model == "SIMPLE_PINHOLE": focal_length_x = intr.params[0] FovY = focal2fov(focal_length_x, height) FovX = focal2fov(focal_length_x, width) elif intr.model == "PINHOLE": focal_length_x = intr.params[0] focal_length_y = intr.params[1] FovY = focal2fov(focal_length_y, height) FovX = focal2fov(focal_length_x, width) else: assert False, "Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!" image_path = os.path.join(images_folder, os.path.basename(extr.name)) image_name = os.path.basename(image_path).split(".")[0] image = Image.open(image_path) cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height) cam_infos.append(cam_info) sys.stdout.write('\n') return cam_infos def fetchPly(path): plydata = PlyData.read(path) vertices = plydata['vertex'] positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0 normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T return BasicPointCloud(points=positions, colors=colors, normals=normals) def storePly(path, xyz, rgb): # Define the dtype for the structured array dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')] normals = np.zeros_like(xyz) elements = np.empty(xyz.shape[0], dtype=dtype) attributes = np.concatenate((xyz, normals, rgb), axis=1) elements[:] = list(map(tuple, attributes)) # Create the PlyData object and write to file vertex_element = PlyElement.describe(elements, 'vertex') ply_data = PlyData([vertex_element]) ply_data.write(path) def readColmapSceneInfo(path, images, eval, llffhold=8): try: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.bin") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.bin")
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # class CameraInfo(NamedTuple): uid: int R: np.array T: np.array FovY: np.array FovX: np.array image: np.array image_path: str image_name: str width: int height: int depth: Optional[np.array] = None class SceneInfo(NamedTuple): point_cloud: BasicPointCloud train_cameras: list test_cameras: list nerf_normalization: dict ply_path: str def load_K_Rt_from_P(filename, P=None): if P is None: lines = open(filename).read().splitlines() if len(lines) == 4: lines = lines[1:] lines = [[x[0], x[1], x[2], x[3]] for x in (x.split(" ") for x in lines)] P = np.asarray(lines).astype(np.float32).squeeze() out = cv.decomposeProjectionMatrix(P) K = out[0] R = out[1] t = out[2] K = K / K[2, 2] pose = np.eye(4, dtype=np.float32) pose[:3, :3] = R.transpose() pose[:3, 3] = (t[:3] / t[3])[:, 0] return K, pose def getNerfppNorm(cam_info): def get_center_and_diag(cam_centers): cam_centers = np.hstack(cam_centers) avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True) center = avg_cam_center dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True) diagonal = np.max(dist) return center.flatten(), diagonal cam_centers = [] for cam in cam_info: W2C = getWorld2View2(cam.R, cam.T) C2W = np.linalg.inv(W2C) cam_centers.append(C2W[:3, 3:4]) center, diagonal = get_center_and_diag(cam_centers) radius = diagonal * 1.1 translate = -center return {"translate": translate, "radius": radius} def readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder): cam_infos = [] num_frames = len(cam_extrinsics) for idx, key in enumerate(cam_extrinsics): sys.stdout.write('\r') # the exact output you're looking for: sys.stdout.write("Reading camera {}/{}".format(idx + 1, len(cam_extrinsics))) sys.stdout.flush() extr = cam_extrinsics[key] intr = cam_intrinsics[extr.camera_id] height = intr.height width = intr.width uid = intr.id R = np.transpose(qvec2rotmat(extr.qvec)) T = np.array(extr.tvec) if intr.model == "SIMPLE_PINHOLE": focal_length_x = intr.params[0] FovY = focal2fov(focal_length_x, height) FovX = focal2fov(focal_length_x, width) elif intr.model == "PINHOLE": focal_length_x = intr.params[0] focal_length_y = intr.params[1] FovY = focal2fov(focal_length_y, height) FovX = focal2fov(focal_length_x, width) else: assert False, "Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!" image_path = os.path.join(images_folder, os.path.basename(extr.name)) image_name = os.path.basename(image_path).split(".")[0] image = Image.open(image_path) cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height) cam_infos.append(cam_info) sys.stdout.write('\n') return cam_infos def fetchPly(path): plydata = PlyData.read(path) vertices = plydata['vertex'] positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0 normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T return BasicPointCloud(points=positions, colors=colors, normals=normals) def storePly(path, xyz, rgb): # Define the dtype for the structured array dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')] normals = np.zeros_like(xyz) elements = np.empty(xyz.shape[0], dtype=dtype) attributes = np.concatenate((xyz, normals, rgb), axis=1) elements[:] = list(map(tuple, attributes)) # Create the PlyData object and write to file vertex_element = PlyElement.describe(elements, 'vertex') ply_data = PlyData([vertex_element]) ply_data.write(path) def readColmapSceneInfo(path, images, eval, llffhold=8): try: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.bin") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.bin")
cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file)
3
2023-10-14 05:42:02+00:00
8k
adymaharana/d2pruning
core/data/Coreset.py
[ { "identifier": "kCenterGreedy", "path": "core/data/sampling.py", "snippet": "class kCenterGreedy(SamplingMethod):\n\n def __init__(self, X, y, seed, metric='euclidean'):\n self.X = X\n self.y = y\n self.flat_X = self.flatten_X()\n self.name = 'kcenter'\n self.features = self.flat_X\n ...
import random, math import torch import numpy as np import queue from collections import Counter from .sampling import kCenterGreedy, GraphDensitySampler from .aucpr import get_aucpr from tqdm import tqdm from multiprocessing import Lock, Process, Queue, current_process, Manager
6,198
target_coreset_num = targets_num * ratio selected_index = selected_index + list(target_index[:int(target_coreset_num)]) print("Selected %s samples for %s label" % (len(selected_index), target)) selected_index = torch.tensor(selected_index) print(f'High priority {key}: {score[score_sorted_index[selected_index][:15]]}') print(f'Low priority {key}: {score[score_sorted_index[selected_index][-15:]]}') return score_sorted_index[selected_index] else: print(f'High priority {key}: {score[score_sorted_index[:15]]}') print(f'Low priority {key}: {score[score_sorted_index[-15:]]}') return score_sorted_index[:int(total_num)] @staticmethod def mislabel_mask(data_score, mis_key, mis_num, mis_descending, coreset_key): mis_score = data_score[mis_key] mis_score_sorted_index = mis_score.argsort(descending=mis_descending) hard_index = mis_score_sorted_index[:mis_num] print(f'Bad data -> High priority {mis_key}: {data_score[mis_key][hard_index][:15]}') print(f'Prune {hard_index.shape[0]} samples.') easy_index = mis_score_sorted_index[mis_num:] data_score[coreset_key] = data_score[coreset_key][easy_index] return data_score, easy_index @staticmethod # def stratified_sampling(data_score, coreset_key, coreset_num, budget='uniform', # sampling='random', data_embeds=None, # n_neighbor=10, median=False, stratas=50): def stratified_sampling(data_score, coreset_num, args, data_embeds=None): if args.sampling_mode == 'graph' and args.coreset_key in ['accumulated_margin']: # TODO: check again score = data_score[args.coreset_key] min_score = torch.min(score) max_score = torch.max(score) score = score - min_score data_score[args.coreset_key] = -score print('Using stratified sampling...') score = data_score[args.coreset_key] if args.graph_score: graph = GraphDensitySampler(X=data_embeds, y=None, gamma=args.gamma, seed=0, importance_scores=score, args=args) # n_neighbor=args.n_neighbor, graph_mode=args.graph_mode, # graph_sampling_mode=args.graph_sampling_mode, # precomputed_dists=args.precomputed_dists, # precomputed_neighbors=args.precomputed_neighbors) score = torch.tensor(graph.graph_density) total_num = len(score) min_score = torch.min(score) max_score = torch.max(score) * 1.0001 print("Min score: %s, max score: %s" % (min_score.item(), max_score.item())) step = (max_score - min_score) / args.stratas def bin_range(k): return min_score + k * step, min_score + (k + 1) * step strata_num = [] ##### calculate number of samples in each strata ##### for i in range(args.stratas): start, end = bin_range(i) num = torch.logical_and(score >= start, score < end).sum() strata_num.append(num) strata_num = torch.tensor(strata_num) if args.budget_mode == 'uniform': budgets = bin_allocate(coreset_num, strata_num) elif args.budget_mode == 'confidence': confs = data_score['confidence'] mean_confs = [] for i in range(args.stratas): start, end = bin_range(i) sample_idxs = torch.logical_and(score >= start, (score < end)).nonzero().squeeze() if sample_idxs.size()[0] != 0: mean_confs.append(1-torch.mean(confs[sample_idxs]).item()) else: mean_confs.append(0) total_conf = np.sum(mean_confs) budgets = [int(n*coreset_num/total_conf) for n in mean_confs] print("Initial budget", budgets) budgets = bin_allocate(coreset_num, strata_num, mode='confidence', initial_budget=budgets) elif args.budget_mode == 'aucpr': budgets = bin_allocate(coreset_num, strata_num) sample_index = torch.arange(data_score[args.coreset_key].shape[0]) aucpr_values = [] min_budgets = {} for i in tqdm(range(args.stratas), desc='Getting k-centers for aucpr-based budgeting'): if budgets[i] == 0: aucpr_values.append(0) continue start, end = bin_range(i) mask = torch.logical_and(score >= start, score < end) pool = sample_index[mask] if args.sampling_mode == 'random': rand_index = torch.randperm(pool.shape[0]) selected_idxs = [idx.item() for idx in rand_index[:budgets[i]]] elif args.sampling_mode == 'kcenter': sampling_method = kCenterGreedy(X=data_embeds[pool], y=None, seed=0) selected_idxs = sampling_method.select_batch_(None, budgets[i]) elif args.sampling_mode == 'graph': if pool.shape[0] <= args.n_neighbor: rand_index = torch.randperm(pool.shape[0]) selected_idxs = rand_index[:budgets[i]].numpy().tolist() else: sampling_method = GraphDensitySampler(X=None if data_embeds is None else data_embeds[pool], y=None, gamma=args.gamma, seed=0, importance_scores=score[pool], args=args) # n_neighbor=args.n_neighbor, graph_mode=args.graph_mode, # graph_sampling_mode=args.graph_sampling_mode, # precomputed_dists=args.precomputed_dists, # precomputed_neighbors=args.precomputed_neighbors # ) selected_idxs = sampling_method.select_batch_(budgets[i]) else: raise ValueError kcenters = pool[selected_idxs] non_coreset = list(set(pool.tolist()).difference(set(kcenters.tolist())))
def get_median(features, targets): # get the median feature vector of each class num_classes = len(np.unique(targets, axis=0)) prot = np.zeros((num_classes, features.shape[-1]), dtype=features.dtype) for i in range(num_classes): prot[i] = np.median(features[(targets == i).nonzero(), :].squeeze(), axis=0, keepdims=False) return prot def get_distance(features, labels): prots = get_median(features, labels) prots_for_each_example = np.zeros(shape=(features.shape[0], prots.shape[-1])) num_classes = len(np.unique(labels)) for i in range(num_classes): prots_for_each_example[(labels == i).nonzero()[0], :] = prots[i] distance = np.linalg.norm(features - prots_for_each_example, axis=1) return distance def bin_allocate(num, bins, mode='uniform', initial_budget=None): sorted_index = torch.argsort(bins) sort_bins = bins[sorted_index] num_bin = bins.shape[0] rest_exp_num = num budgets = [] for i in range(num_bin): if sort_bins[i] == 0: budgets.append(0) continue # rest_bins = num_bin - i rest_bins = torch.count_nonzero(sort_bins[i:]) if mode == 'uniform': avg = rest_exp_num // rest_bins cur_num = min(sort_bins[i].item(), avg) rest_exp_num -= cur_num else: avg = initial_budget[sorted_index[i]] cur_num = min(sort_bins[i].item(), avg) delta = int((avg - cur_num)/max(1, (rest_bins - 1))) # print("At index %s, changing budget from %s to %s and reallocating %s to %s bins" % (i, avg, cur_num, delta, rest_bins-1)) for j in range(i+1, num_bin): initial_budget[sorted_index[j]] += delta budgets.append(cur_num) budgets = torch.tensor(budgets) if torch.sum(budgets) < num: # TODO: check again delta = num - torch.sum(budgets) i = 1 while delta and i <= num_bin: if budgets[-i] < sort_bins[-i]: budgets[-i] += 1 delta -= 1 i += 1 rst = torch.zeros((num_bin,)).type(torch.int) rst[sorted_index] = torch.tensor(budgets).type(torch.int) assert all([b<= r for r, b in zip(bins, rst)]), ([(r.item(),b.item()) for r, b in zip(bins, rst)], bins, [x.item() for x in torch.tensor(budgets)[sorted_index]]) return rst class CoresetSelection(object): @staticmethod def moderate_selection(data_score, ratio, features): def get_prune_idx(rate, distance): rate = 1-rate low = 0.5 - rate / 2 high = 0.5 + rate / 2 sorted_idx = distance.argsort() low_idx = round(distance.shape[0] * low) high_idx = round(distance.shape[0] * high) ids = np.concatenate((sorted_idx[:low_idx], sorted_idx[high_idx:])) return ids targets_list = data_score['targets'] distance = get_distance(features, targets_list) ids = get_prune_idx(ratio, distance) return ids @staticmethod def score_monotonic_selection(data_score, key, ratio, descending, class_balanced): score = data_score[key] score_sorted_index = score.argsort(descending=descending) total_num = ratio * data_score[key].shape[0] print("Selecting from %s samples" % total_num) if class_balanced: print('Class balance mode.') all_index = torch.arange(data_score['targets'].shape[0]) #Permutation selected_index = [] targets_list = data_score['targets'][score_sorted_index] targets_unique = torch.unique(targets_list) for target in targets_unique: target_index_mask = (targets_list == target) target_index = all_index[target_index_mask] targets_num = target_index_mask.sum() target_coreset_num = targets_num * ratio selected_index = selected_index + list(target_index[:int(target_coreset_num)]) print("Selected %s samples for %s label" % (len(selected_index), target)) selected_index = torch.tensor(selected_index) print(f'High priority {key}: {score[score_sorted_index[selected_index][:15]]}') print(f'Low priority {key}: {score[score_sorted_index[selected_index][-15:]]}') return score_sorted_index[selected_index] else: print(f'High priority {key}: {score[score_sorted_index[:15]]}') print(f'Low priority {key}: {score[score_sorted_index[-15:]]}') return score_sorted_index[:int(total_num)] @staticmethod def mislabel_mask(data_score, mis_key, mis_num, mis_descending, coreset_key): mis_score = data_score[mis_key] mis_score_sorted_index = mis_score.argsort(descending=mis_descending) hard_index = mis_score_sorted_index[:mis_num] print(f'Bad data -> High priority {mis_key}: {data_score[mis_key][hard_index][:15]}') print(f'Prune {hard_index.shape[0]} samples.') easy_index = mis_score_sorted_index[mis_num:] data_score[coreset_key] = data_score[coreset_key][easy_index] return data_score, easy_index @staticmethod # def stratified_sampling(data_score, coreset_key, coreset_num, budget='uniform', # sampling='random', data_embeds=None, # n_neighbor=10, median=False, stratas=50): def stratified_sampling(data_score, coreset_num, args, data_embeds=None): if args.sampling_mode == 'graph' and args.coreset_key in ['accumulated_margin']: # TODO: check again score = data_score[args.coreset_key] min_score = torch.min(score) max_score = torch.max(score) score = score - min_score data_score[args.coreset_key] = -score print('Using stratified sampling...') score = data_score[args.coreset_key] if args.graph_score: graph = GraphDensitySampler(X=data_embeds, y=None, gamma=args.gamma, seed=0, importance_scores=score, args=args) # n_neighbor=args.n_neighbor, graph_mode=args.graph_mode, # graph_sampling_mode=args.graph_sampling_mode, # precomputed_dists=args.precomputed_dists, # precomputed_neighbors=args.precomputed_neighbors) score = torch.tensor(graph.graph_density) total_num = len(score) min_score = torch.min(score) max_score = torch.max(score) * 1.0001 print("Min score: %s, max score: %s" % (min_score.item(), max_score.item())) step = (max_score - min_score) / args.stratas def bin_range(k): return min_score + k * step, min_score + (k + 1) * step strata_num = [] ##### calculate number of samples in each strata ##### for i in range(args.stratas): start, end = bin_range(i) num = torch.logical_and(score >= start, score < end).sum() strata_num.append(num) strata_num = torch.tensor(strata_num) if args.budget_mode == 'uniform': budgets = bin_allocate(coreset_num, strata_num) elif args.budget_mode == 'confidence': confs = data_score['confidence'] mean_confs = [] for i in range(args.stratas): start, end = bin_range(i) sample_idxs = torch.logical_and(score >= start, (score < end)).nonzero().squeeze() if sample_idxs.size()[0] != 0: mean_confs.append(1-torch.mean(confs[sample_idxs]).item()) else: mean_confs.append(0) total_conf = np.sum(mean_confs) budgets = [int(n*coreset_num/total_conf) for n in mean_confs] print("Initial budget", budgets) budgets = bin_allocate(coreset_num, strata_num, mode='confidence', initial_budget=budgets) elif args.budget_mode == 'aucpr': budgets = bin_allocate(coreset_num, strata_num) sample_index = torch.arange(data_score[args.coreset_key].shape[0]) aucpr_values = [] min_budgets = {} for i in tqdm(range(args.stratas), desc='Getting k-centers for aucpr-based budgeting'): if budgets[i] == 0: aucpr_values.append(0) continue start, end = bin_range(i) mask = torch.logical_and(score >= start, score < end) pool = sample_index[mask] if args.sampling_mode == 'random': rand_index = torch.randperm(pool.shape[0]) selected_idxs = [idx.item() for idx in rand_index[:budgets[i]]] elif args.sampling_mode == 'kcenter': sampling_method = kCenterGreedy(X=data_embeds[pool], y=None, seed=0) selected_idxs = sampling_method.select_batch_(None, budgets[i]) elif args.sampling_mode == 'graph': if pool.shape[0] <= args.n_neighbor: rand_index = torch.randperm(pool.shape[0]) selected_idxs = rand_index[:budgets[i]].numpy().tolist() else: sampling_method = GraphDensitySampler(X=None if data_embeds is None else data_embeds[pool], y=None, gamma=args.gamma, seed=0, importance_scores=score[pool], args=args) # n_neighbor=args.n_neighbor, graph_mode=args.graph_mode, # graph_sampling_mode=args.graph_sampling_mode, # precomputed_dists=args.precomputed_dists, # precomputed_neighbors=args.precomputed_neighbors # ) selected_idxs = sampling_method.select_batch_(budgets[i]) else: raise ValueError kcenters = pool[selected_idxs] non_coreset = list(set(pool.tolist()).difference(set(kcenters.tolist())))
aucpr = get_aucpr(data_embeds[kcenters], data_embeds[non_coreset])
2
2023-10-10 08:35:53+00:00
8k
Jacoo-ai/HIC-Yolov5
pl.py
[ { "identifier": "check_anchor_order", "path": "utils/autoanchor.py", "snippet": "def check_anchor_order(m):\n # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary\n a = m.anchors.prod(-1).view(-1) # anchor area\n da = a[-1] - a[0] # delta a\n ds ...
import os import pytorch_lightning import torch import torch.nn.functional as F import pytorch_lightning as pl import argparse import sys import thop # for FLOPs computation import yaml # for torch hub from torch import nn from torchvision import transforms from torchvision.datasets import MNIST from torch.utils.data import DataLoader, random_split from copy import deepcopy from pathlib import Path from models.common import * from models.experimental import * from utils.autoanchor import check_anchor_order from utils.general import check_yaml, make_divisible, print_args, set_logging from utils.plots import feature_visualization from utils.torch_utils import copy_attr, fuse_conv_and_bn, initialize_weights, model_info, scale_img, \ select_device, time_sync
4,809
self.stride = m.stride self._initialize_biases() # only run once # Init weights, biases initialize_weights(self) self.info() LOGGER.info('') def forward(self, x, augment=False, profile=False, visualize=False): if augment: return self._forward_augment(x) # augmented inference, None return self._forward_once(x, profile, visualize) # single-scale inference, train def _forward_augment(self, x): img_size = x.shape[-2:] # height, width s = [1, 0.83, 0.67] # scales f = [None, 3, None] # flips (2-ud, 3-lr) y = [] # outputs for si, fi in zip(s, f): xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) yi = self._forward_once(xi)[0] # forward # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save yi = self._descale_pred(yi, fi, si, img_size) y.append(yi) y = self._clip_augmented(y) # clip augmented tails return torch.cat(y, 1), None # augmented inference, train def _forward_once(self, x, profile=False, visualize=False): y, dt = [], [] # outputs for m in self.model: if m.f != -1: # if not from previous layer x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers if profile: self._profile_one_layer(m, x, dt) x = m(x) # run y.append(x if m.i in self.save else None) # save output if visualize: feature_visualization(x, m.type, m.i, save_dir=visualize) return x def _descale_pred(self, p, flips, scale, img_size): # de-scale predictions following augmented inference (inverse operation) if self.inplace: p[..., :4] /= scale # de-scale if flips == 2: p[..., 1] = img_size[0] - p[..., 1] # de-flip ud elif flips == 3: p[..., 0] = img_size[1] - p[..., 0] # de-flip lr else: x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale if flips == 2: y = img_size[0] - y # de-flip ud elif flips == 3: x = img_size[1] - x # de-flip lr p = torch.cat((x, y, wh, p[..., 4:]), -1) return p def _clip_augmented(self, y): # Clip YOLOv5 augmented inference tails nl = self.model[-1].nl # number of detection layers (P3-P5) g = sum(4 ** x for x in range(nl)) # grid points e = 1 # exclude layer count i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices y[0] = y[0][:, :-i] # large i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices y[-1] = y[-1][:, i:] # small return y def _profile_one_layer(self, m, x, dt): c = isinstance(m, Detect) # is final layer, copy input as inplace fix o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs t = time_sync() for _ in range(10): m(x.copy() if c else x) dt.append((time_sync() - t) * 100) if m == self.model[0]: LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}") LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}') if c: LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total") def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency # https://arxiv.org/abs/1708.02002 section 3.3 # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. m = self.model[-1] # Detect() module for mi, s in zip(m.m, m.stride): # from b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) def _print_biases(self): m = self.model[-1] # Detect() module for mi in m.m: # from b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) LOGGER.info( ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean())) # def _print_weights(self): # for m in self.model.modules(): # if type(m) is Bottleneck: # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers LOGGER.info('Fusing layers... ') for m in self.model.modules(): if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'): m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv delattr(m, 'bn') # remove batchnorm m.forward = m.forward_fuse # update forward self.info() return self def autoshape(self): # add AutoShape module LOGGER.info('Adding AutoShape... ') m = AutoShape(self) # wrap model copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes return m def info(self, verbose=False, img_size=640): # print model information
FILE = Path(__file__).resolve() ROOT = FILE.parents[1] # YOLOv5 root directory if str(ROOT) not in sys.path: sys.path.append(str(ROOT)) # add ROOT to PATH # ROOT = ROOT.relative_to(Path.cwd()) # relative try: except ImportError: thop = None LOGGER = logging.getLogger(__name__) ################################################### ################################################### class Yolo(torch.nn.Module): def __init__(self, cfg='yolov5s.yaml', ch=3, nc=10, anchors=None): # model, input channels, number of classes super().__init__() if isinstance(cfg, dict): self.yaml = cfg # model dict else: # is *.yaml self.yaml_file = Path(cfg).name with open(cfg, errors='ignore') as f: self.yaml = yaml.safe_load(f) # model dict # Define model ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels if nc and nc != self.yaml['nc']: LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}") self.yaml['nc'] = nc # override yaml value if anchors: LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}') self.yaml['anchors'] = round(anchors) # override yaml value self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist self.names = [str(i) for i in range(self.yaml['nc'])] # default names self.inplace = self.yaml.get('inplace', True) # Build strides, anchors m = self.model[-1] # Detect() if isinstance(m, Detect): s = 256 # 2x min stride m.inplace = self.inplace m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward m.anchors /= m.stride.view(-1, 1, 1) check_anchor_order(m) self.stride = m.stride self._initialize_biases() # only run once # Init weights, biases initialize_weights(self) self.info() LOGGER.info('') def forward(self, x, augment=False, profile=False, visualize=False): if augment: return self._forward_augment(x) # augmented inference, None return self._forward_once(x, profile, visualize) # single-scale inference, train def _forward_augment(self, x): img_size = x.shape[-2:] # height, width s = [1, 0.83, 0.67] # scales f = [None, 3, None] # flips (2-ud, 3-lr) y = [] # outputs for si, fi in zip(s, f): xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max())) yi = self._forward_once(xi)[0] # forward # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save yi = self._descale_pred(yi, fi, si, img_size) y.append(yi) y = self._clip_augmented(y) # clip augmented tails return torch.cat(y, 1), None # augmented inference, train def _forward_once(self, x, profile=False, visualize=False): y, dt = [], [] # outputs for m in self.model: if m.f != -1: # if not from previous layer x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers if profile: self._profile_one_layer(m, x, dt) x = m(x) # run y.append(x if m.i in self.save else None) # save output if visualize: feature_visualization(x, m.type, m.i, save_dir=visualize) return x def _descale_pred(self, p, flips, scale, img_size): # de-scale predictions following augmented inference (inverse operation) if self.inplace: p[..., :4] /= scale # de-scale if flips == 2: p[..., 1] = img_size[0] - p[..., 1] # de-flip ud elif flips == 3: p[..., 0] = img_size[1] - p[..., 0] # de-flip lr else: x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale if flips == 2: y = img_size[0] - y # de-flip ud elif flips == 3: x = img_size[1] - x # de-flip lr p = torch.cat((x, y, wh, p[..., 4:]), -1) return p def _clip_augmented(self, y): # Clip YOLOv5 augmented inference tails nl = self.model[-1].nl # number of detection layers (P3-P5) g = sum(4 ** x for x in range(nl)) # grid points e = 1 # exclude layer count i = (y[0].shape[1] // g) * sum(4 ** x for x in range(e)) # indices y[0] = y[0][:, :-i] # large i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices y[-1] = y[-1][:, i:] # small return y def _profile_one_layer(self, m, x, dt): c = isinstance(m, Detect) # is final layer, copy input as inplace fix o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs t = time_sync() for _ in range(10): m(x.copy() if c else x) dt.append((time_sync() - t) * 100) if m == self.model[0]: LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}") LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}') if c: LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total") def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency # https://arxiv.org/abs/1708.02002 section 3.3 # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1. m = self.model[-1] # Detect() module for mi, s in zip(m.m, m.stride): # from b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85) b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image) b.data[:, 5:] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True) def _print_biases(self): m = self.model[-1] # Detect() module for mi in m.m: # from b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85) LOGGER.info( ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean())) # def _print_weights(self): # for m in self.model.modules(): # if type(m) is Bottleneck: # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers LOGGER.info('Fusing layers... ') for m in self.model.modules(): if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'): m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv delattr(m, 'bn') # remove batchnorm m.forward = m.forward_fuse # update forward self.info() return self def autoshape(self): # add AutoShape module LOGGER.info('Adding AutoShape... ') m = AutoShape(self) # wrap model copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes return m def info(self, verbose=False, img_size=640): # print model information
model_info(self, verbose, img_size)
9
2023-10-12 08:52:01+00:00
8k
OmicsML/scDiff
scdiff/data/cellxgene.py
[ { "identifier": "MaskDataset", "path": "scdiff/data/base.py", "snippet": "class MaskDataset(SplitDataset):\n SPLIT: Optional[str] = None\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def __getitem__(self, index):\n item_dict = {\n \"in...
import os.path as osp import anndata as ad import numpy as np import pandas as pd import scanpy as sc import torch from abc import ABC, abstractmethod from sklearn.preprocessing import LabelEncoder from scdiff.data.base import MaskDataset, SplitDataset, GenerationDataset from scdiff.modules.text import SimpleEmbeddingGenerator, CLEmbeddingGenerator from scdiff.utils.data import mask_data_offline, dict_to_list_of_tuples from scdiff.utils.misc import default
6,319
def _prepare_split(self, splits={'train': 0.8, 'valid': 0.1, 'test': 0.1}, split_strategy='random', seed=10, fname='HLCA_zstd_sub.h5ad', subsample_ratio=None, force_split=False): if split_strategy == 'reduce': # No validation assert self.reduce_type in ['full', 'partial'] if ( ( self.reduce_type == 'full' and False ) or ( self.reduce_type == 'partial' and f'split_partial_{self.n_preserve}' in self.adata.uns.keys() and 'preserve_idx' in self.adata.uns[f'split_partial_{self.n_preserve}'].keys() and all( x in sorted(self.adata.uns[f'split_partial_{self.n_preserve}']['preserve_idx']) for x in sorted(self.target_cell_types) ) ) ): pass else: if self.reduce_type == 'full': target_cell_types_flag = self.adata.obs['cell_type'].isin(self.target_cell_types).values if 'split_full' in self.adata.obs.columns: del self.adata.obs['split_full'] self.adata.obs['split_full'] = 'train' self.adata.obs['split_full'][target_cell_types_flag] = 'test' elif self.reduce_type == 'partial': # save a separate file for n_preserve in range(1, self.disgard_threshold + 1): self.adata.uns[f'split_partial_{n_preserve}'] = { 'reduce_type': self.reduce_type, 'n_preserve': n_preserve } rng = np.random.default_rng(seed) preserve_idx = {} for ct in self.target_cell_types: test_cell_types_idx = np.where(self.adata.obs['cell_type'] == ct)[0] preserve_idx[ct] = rng.choice(test_cell_types_idx, n_preserve, replace=False).tolist() # self.adata.obs['split'][preserve_idx[ct]] = 'train' self.adata.uns[f'split_partial_{n_preserve}'].update({ 'preserve_idx': preserve_idx, }) if self.save_processed and fname is not None: print(f"Saving processed file to {osp.join(self.datadir, fname)}") self.adata.write_h5ad(osp.join(self.datadir, fname), compression='gzip') else: if ( ('split' in self.adata.obs.columns) and sorted(splits) == sorted(np.unique(self.adata.obs['split'])) and not force_split and split_strategy != 'reduce' ): pass else: if subsample_ratio is not None: assert 0 < subsample_ratio <= 1 obs = self.adata.obs obs_sub = obs.groupby(self.batch_key, group_keys=False).apply( lambda x: x.sample(int(len(x) * subsample_ratio), random_state=seed)) self.adata = self.adata[obs_sub.index] assert 'train' in splits and 'valid' in splits assert sum([splits[k] for k in splits.keys()]) == 1 assert split_strategy in ['random', 'cell_type', 'batch'] self.adata.obs['split'] = 'train' if split_strategy == 'random': rng = np.random.default_rng(seed) N = len(self.adata) perm = rng.permutation(range(N)) self.adata.obs['split'][ perm[int(N * splits['train']):int(N * (splits['train'] + splits['valid']))]] = 'valid' if 'test' in splits: self.adata.obs['split'][perm[int(N * (splits['train'] + splits['valid'])):]] = 'test' else: group_key = self.celltype_key if split_strategy == 'cell_type' else self.batch_key obs = self.adata.obs obs_valid = obs.groupby(group_key, group_keys=False).apply( lambda x: x.sample(int(len(x) * splits['valid']), random_state=seed)) self.adata.obs['split'][obs_valid.index] = 'valid' if 'test' in splits: obs = obs[~obs.index.isin(obs_valid.index)] test_ratio = splits['test'] / (splits['train'] + splits['test']) obs_test = obs.groupby(group_key, group_keys=False).apply( lambda x: x.sample(int(len(x) * test_ratio), random_state=seed)) self.adata.obs['split'][obs_test.index] = 'test' if self.save_processed and fname is not None: print(f"Saving processed file to {osp.join(self.datadir, fname)}") self.adata.write_h5ad(osp.join(self.datadir, fname), compression='gzip') def _init_condiitons(self): self.le_dict = {} for key, raw_key in self.default_cond_key_dict.items(): self.le_dict[key] = LabelEncoder() self.le_dict[key].classes_ = np.array( ["null"] + sorted(self.adata.obs[raw_key].astype(str).unique()) ) if self.post_cond_flag: cond_keys = list(set(self.default_cond_key_dict) - set(self.default_post_cond_key_dict)) self.cond_num_dict = { k: len(self.le_dict[k].classes_) for k in cond_keys } self.post_cond_num_dict = { k: len(self.le_dict[k].classes_) for k in self.default_post_cond_key_dict } else: self.cond_num_dict = { k: len(self.le_dict[k].classes_) for k in self.default_cond_key_dict } self.post_cond_num_dict = None if self.text_cond_flag: text_cond_dict = { k: self.adata.obs[k].values.tolist() for k in self.TEXT_COND_KEYS[self.text_emb_type] } self.unique_cond_dict = pd.DataFrame(text_cond_dict).drop_duplicates().to_dict(orient='list')
DATASETS = { 'HLCA': { 'fname': 'HLCA_zstd_processed.h5ad', 'batch_key': 'batch' }, 'HLCA_sub': { 'fname': 'HLCA_zstd_sub.h5ad', 'batch_key': 'batch' }, 'HLCA_naw': { 'fname': 'HLCA_zstd_Nawijin_GRO-09.h5ad', 'batch_key': 'batch' }, 'Immune': { 'fname': 'Immune_processed.h5ad', 'batch_key': 'donor_id' }, 'Immune_sub': { 'fname': 'Immune_sub.h5ad', 'batch_key': 'donor_id' }, 'Liver': { 'fname': 'Liver_processed.h5ad', 'batch_key': 'donor_id', 'raw_path': '/egr/research-dselab/shared/dance/cellxgene/datasets/human/a43aa46b-bd16-47fe-bc3e-19a052624e79.h5ad', }, 'Brain': { 'fname': 'Brain_processed.h5ad', 'batch_key': 'donor_id', 'raw_path': '/egr/research-dselab/shared/dance/cellxgene/datasets/human_manual_download_2023-09-27/c05e6940-729c-47bd-a2a6-6ce3730c4919.h5ad', }, } class CellXGeneBase(ABC): N_PRESERVE = 5 LIB_SIZE_FACTOR = 1e4 TEXT_COND_KEYS = { 'simple': ['cell_type', 'sex'], 'CL': ['cell_type_ontology_term_id'] } GENE_LIST_FNAME='HLCA_gene_list.npy' def __init__(self, datadir='./data', seed=10, normalize=True, n_genes=None, dataset='HLCA_sub', save_processed=False, splits={'train': 0.8, 'valid': 0.1, 'test': 0.1}, split_strategy='random', subsample_ratio=None, force_split=False, post_cond_flag=False, return_raw=False, rescale=False, text_cond_flag=False, text_emb_model='michiyasunaga/BioLinkBERT-large', text_emb_type='CL', pretrained_gene_list_fname=None, text_null_flag=False, reduce_type='full', test_cell_types=None, train_cell_types=None, overwrite_test=False, n_preserve=None, disgard_flag=True, disgard_threshold=10): self.batch_key = DATASETS[dataset]['batch_key'] self.default_cond_key_dict = dict(batch=self.batch_key, cell_type="cell_type") self.default_post_cond_key_dict = dict(batch=self.batch_key) self.seed = seed self.datadir = datadir self.rescale = rescale self.normalize = normalize self.return_raw = return_raw self.save_processed = save_processed self.post_cond_flag = post_cond_flag self.text_cond_flag = text_cond_flag self.text_emb_model = text_emb_model self.text_emb_type = text_emb_type self.text_null_flag = text_null_flag self.reduce_type = reduce_type self.pretrained_gene_list_fname = pretrained_gene_list_fname self.n_preserve = default(n_preserve, self.N_PRESERVE) self.dataset = dataset fname = DATASETS[dataset]['fname'] self._read(datadir=datadir, normalize=normalize, rescale=rescale, n_genes=n_genes, fname=fname) self.disgard_threshold = disgard_threshold if disgard_flag: cell_type_counts = self.adata.obs['cell_type'].value_counts() disgard_ct = cell_type_counts[cell_type_counts <= disgard_threshold].index.tolist() self.adata = self.adata[~self.adata.obs['cell_type'].isin(disgard_ct)] test_cell_types = test_cell_types.split(' | ') if test_cell_types is not None else None train_cell_types = train_cell_types.split(' | ') if train_cell_types is not None else None if train_cell_types is not None and overwrite_test: self.target_cell_types = list(set(self.adata.obs['cell_type']) - set(train_cell_types)) else: self.target_cell_types = test_cell_types self.target_cell_types = default(self.target_cell_types, list(set(self.adata.obs['cell_type']))) self._prepare_split(splits=splits, split_strategy=split_strategy, seed=seed, fname=fname, subsample_ratio=subsample_ratio, force_split=force_split) self._init_condiitons() self._prepare() def _read(self, datadir='./data', normalize=True, rescale=False, n_genes=None, fname='HLCA_zstd_sub.h5ad'): if osp.exists(osp.join(datadir, fname)) and fname.endswith('.h5ad'): self.adata = ad.read_h5ad(osp.join(datadir, fname)) else: self.adata = ad.read_h5ad(DATASETS[self.dataset]['raw_path']) # currently only for Brain and Liver self.adata.var = self.adata.var.reset_index().set_index('feature_name') self.adata.var_names_make_unique() self.adata.X = self.adata.raw.X.copy() sc.pp.filter_genes(self.adata, min_cells=1) sc.pp.filter_cells(self.adata, min_genes=1) self.adata.layers['counts'] = self.adata.X.copy() if self.pretrained_gene_list_fname is not None: assert self.pretrained_gene_list_fname.endswith('npy') pretrained_gene_list_path = osp.join(datadir, self.pretrained_gene_list_fname) pretrained_gene_list = np.load(pretrained_gene_list_path, allow_pickle=True) self.gene_list = self.adata.var.index.to_list() self.gene_list = [x for x in self.gene_list if x in pretrained_gene_list] self.adata = self.adata[:, self.gene_list] if normalize: sc.pp.normalize_total(self.adata, target_sum=self.LIB_SIZE_FACTOR, key_added='library_size') sc.pp.log1p(self.adata) if rescale: self.adata.X /= np.log(self.LIB_SIZE_FACTOR + 1) if n_genes is not None: sc.pp.highly_variable_genes(self.adata, n_top_genes=n_genes) def _prepare_split(self, splits={'train': 0.8, 'valid': 0.1, 'test': 0.1}, split_strategy='random', seed=10, fname='HLCA_zstd_sub.h5ad', subsample_ratio=None, force_split=False): if split_strategy == 'reduce': # No validation assert self.reduce_type in ['full', 'partial'] if ( ( self.reduce_type == 'full' and False ) or ( self.reduce_type == 'partial' and f'split_partial_{self.n_preserve}' in self.adata.uns.keys() and 'preserve_idx' in self.adata.uns[f'split_partial_{self.n_preserve}'].keys() and all( x in sorted(self.adata.uns[f'split_partial_{self.n_preserve}']['preserve_idx']) for x in sorted(self.target_cell_types) ) ) ): pass else: if self.reduce_type == 'full': target_cell_types_flag = self.adata.obs['cell_type'].isin(self.target_cell_types).values if 'split_full' in self.adata.obs.columns: del self.adata.obs['split_full'] self.adata.obs['split_full'] = 'train' self.adata.obs['split_full'][target_cell_types_flag] = 'test' elif self.reduce_type == 'partial': # save a separate file for n_preserve in range(1, self.disgard_threshold + 1): self.adata.uns[f'split_partial_{n_preserve}'] = { 'reduce_type': self.reduce_type, 'n_preserve': n_preserve } rng = np.random.default_rng(seed) preserve_idx = {} for ct in self.target_cell_types: test_cell_types_idx = np.where(self.adata.obs['cell_type'] == ct)[0] preserve_idx[ct] = rng.choice(test_cell_types_idx, n_preserve, replace=False).tolist() # self.adata.obs['split'][preserve_idx[ct]] = 'train' self.adata.uns[f'split_partial_{n_preserve}'].update({ 'preserve_idx': preserve_idx, }) if self.save_processed and fname is not None: print(f"Saving processed file to {osp.join(self.datadir, fname)}") self.adata.write_h5ad(osp.join(self.datadir, fname), compression='gzip') else: if ( ('split' in self.adata.obs.columns) and sorted(splits) == sorted(np.unique(self.adata.obs['split'])) and not force_split and split_strategy != 'reduce' ): pass else: if subsample_ratio is not None: assert 0 < subsample_ratio <= 1 obs = self.adata.obs obs_sub = obs.groupby(self.batch_key, group_keys=False).apply( lambda x: x.sample(int(len(x) * subsample_ratio), random_state=seed)) self.adata = self.adata[obs_sub.index] assert 'train' in splits and 'valid' in splits assert sum([splits[k] for k in splits.keys()]) == 1 assert split_strategy in ['random', 'cell_type', 'batch'] self.adata.obs['split'] = 'train' if split_strategy == 'random': rng = np.random.default_rng(seed) N = len(self.adata) perm = rng.permutation(range(N)) self.adata.obs['split'][ perm[int(N * splits['train']):int(N * (splits['train'] + splits['valid']))]] = 'valid' if 'test' in splits: self.adata.obs['split'][perm[int(N * (splits['train'] + splits['valid'])):]] = 'test' else: group_key = self.celltype_key if split_strategy == 'cell_type' else self.batch_key obs = self.adata.obs obs_valid = obs.groupby(group_key, group_keys=False).apply( lambda x: x.sample(int(len(x) * splits['valid']), random_state=seed)) self.adata.obs['split'][obs_valid.index] = 'valid' if 'test' in splits: obs = obs[~obs.index.isin(obs_valid.index)] test_ratio = splits['test'] / (splits['train'] + splits['test']) obs_test = obs.groupby(group_key, group_keys=False).apply( lambda x: x.sample(int(len(x) * test_ratio), random_state=seed)) self.adata.obs['split'][obs_test.index] = 'test' if self.save_processed and fname is not None: print(f"Saving processed file to {osp.join(self.datadir, fname)}") self.adata.write_h5ad(osp.join(self.datadir, fname), compression='gzip') def _init_condiitons(self): self.le_dict = {} for key, raw_key in self.default_cond_key_dict.items(): self.le_dict[key] = LabelEncoder() self.le_dict[key].classes_ = np.array( ["null"] + sorted(self.adata.obs[raw_key].astype(str).unique()) ) if self.post_cond_flag: cond_keys = list(set(self.default_cond_key_dict) - set(self.default_post_cond_key_dict)) self.cond_num_dict = { k: len(self.le_dict[k].classes_) for k in cond_keys } self.post_cond_num_dict = { k: len(self.le_dict[k].classes_) for k in self.default_post_cond_key_dict } else: self.cond_num_dict = { k: len(self.le_dict[k].classes_) for k in self.default_cond_key_dict } self.post_cond_num_dict = None if self.text_cond_flag: text_cond_dict = { k: self.adata.obs[k].values.tolist() for k in self.TEXT_COND_KEYS[self.text_emb_type] } self.unique_cond_dict = pd.DataFrame(text_cond_dict).drop_duplicates().to_dict(orient='list')
self.unique_cond_list = dict_to_list_of_tuples(self.unique_cond_dict)
6
2023-10-13 14:20:34+00:00
8k
weavel-ai/promptmodel-python
promptmodel/websocket/websocket_client.py
[ { "identifier": "DevApp", "path": "promptmodel/dev_app.py", "snippet": "class DevApp:\n _nest_asyncio_applied = False\n\n def __init__(self):\n self.function_models: List[FunctionModelInterface] = []\n self.chat_models: List[ChatModelInterface] = []\n self.samples: List[Dict[s...
import asyncio import json import datetime import re import promptmodel.utils.logger as logger from uuid import UUID, uuid4 from typing import Dict, Any, Optional, AsyncGenerator, List from dotenv import load_dotenv from collections import defaultdict from asyncio import Queue from websockets.client import connect, WebSocketClientProtocol from websockets.exceptions import ConnectionClosedError, ConnectionClosedOK from readerwriterlock import rwlock from playhouse.shortcuts import model_to_dict from promptmodel import DevApp from promptmodel.llms.llm_dev import LLMDev from promptmodel.database.models import ( DeployedFunctionModel, DeployedFunctionModelVersion, DeployedPrompt, ) from promptmodel.types.enums import ServerTask, LocalTask, LocalTaskErrorType from promptmodel.utils.config_utils import upsert_config, read_config from promptmodel.utils.output_utils import update_dict from promptmodel.types.response import LLMStreamResponse from promptmodel.constants import ENDPOINT_URL
4,362
load_dotenv() GATEWAY_URL = f"wss://{ENDPOINT_URL.split('://')[1]}/open_websocket" class CustomJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, UUID): return str(obj) elif isinstance(obj, datetime.datetime): aware_datetime = obj.replace(tzinfo=datetime.timezone.utc) return aware_datetime.isoformat() # This will include timezone information return super().default(obj) class DevWebsocketClient:
load_dotenv() GATEWAY_URL = f"wss://{ENDPOINT_URL.split('://')[1]}/open_websocket" class CustomJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, UUID): return str(obj) elif isinstance(obj, datetime.datetime): aware_datetime = obj.replace(tzinfo=datetime.timezone.utc) return aware_datetime.isoformat() # This will include timezone information return super().default(obj) class DevWebsocketClient:
def __init__(self, _devapp: DevApp):
0
2023-10-09 03:35:44+00:00
8k
goldoak/DMSR
demo.py
[ { "identifier": "SPGANet", "path": "lib/sgpa.py", "snippet": "class SPGANet(nn.Module):\n def __init__(self, n_cat=6, nv_prior=1024, num_structure_points=128, mode='train'):\n super(SPGANet, self).__init__()\n self.n_cat = n_cat\n self.mode = mode\n self.psp = PSPNet(bins=...
import os import time import argparse import cv2 import numpy as np import pickle as cPickle import torch import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as transforms from tqdm import tqdm from lib.sgpa import SPGANet from lib.align import ransacPnP_LM from lib.utils import load_depth, get_bbox, draw_detections
4,037
parser = argparse.ArgumentParser() parser.add_argument('--data', type=str, default='val', help='val, real_test') parser.add_argument('--data_dir', type=str, default='./toy_dataset/NOCS', help='data directory') parser.add_argument('--model', type=str, default='./pretrained/camera_model.pth', help='resume from saved model') parser.add_argument('--result_dir', type=str, default='results/camera', help='result directory') parser.add_argument('--gpu', type=str, default='0', help='GPU to use') parser.add_argument('--n_cat', type=int, default=6, help='number of object categories') parser.add_argument('--nv_prior', type=int, default=1024, help='number of vertices in shape priors') parser.add_argument('--n_pts', type=int, default=1024, help='number of foreground points') parser.add_argument('--img_size', type=int, default=192, help='cropped image size') parser.add_argument('--num_structure_points', type=int, default=256, help='number of key-points used for pose estimation') opt = parser.parse_args() os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu assert opt.data in ['val', 'real_test'] if opt.data == 'val': cam_fx, cam_fy, cam_cx, cam_cy = 577.5, 577.5, 319.5, 239.5 file_path = 'CAMERA/val_list.txt' else: cam_fx, cam_fy, cam_cx, cam_cy = 591.0125, 590.16775, 322.525, 244.11084 file_path = 'Real/test_list.txt' K = np.eye(3) K[0, 0] = cam_fx K[1, 1] = cam_fy K[0, 2] = cam_cx K[1, 2] = cam_cy result_dir = opt.result_dir result_img_dir = os.path.join(result_dir, 'images') if not os.path.exists(result_dir): os.makedirs(result_dir) os.makedirs(result_img_dir) dpt_dir = opt.data_dir.replace('NOCS', 'dpt_output') # path for shape & scale prior mean_shapes = np.load('assets/mean_points_emb.npy') with open('assets/mean_scale.pkl', 'rb') as f: mean_scale = cPickle.load(f) xmap = np.array([[i for i in range(640)] for j in range(480)]) ymap = np.array([[j for i in range(640)] for j in range(480)]) norm_scale = 1000.0 norm_color = transforms.Compose( [transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])] ) def run_demo(): # resume model
parser = argparse.ArgumentParser() parser.add_argument('--data', type=str, default='val', help='val, real_test') parser.add_argument('--data_dir', type=str, default='./toy_dataset/NOCS', help='data directory') parser.add_argument('--model', type=str, default='./pretrained/camera_model.pth', help='resume from saved model') parser.add_argument('--result_dir', type=str, default='results/camera', help='result directory') parser.add_argument('--gpu', type=str, default='0', help='GPU to use') parser.add_argument('--n_cat', type=int, default=6, help='number of object categories') parser.add_argument('--nv_prior', type=int, default=1024, help='number of vertices in shape priors') parser.add_argument('--n_pts', type=int, default=1024, help='number of foreground points') parser.add_argument('--img_size', type=int, default=192, help='cropped image size') parser.add_argument('--num_structure_points', type=int, default=256, help='number of key-points used for pose estimation') opt = parser.parse_args() os.environ['CUDA_VISIBLE_DEVICES'] = opt.gpu assert opt.data in ['val', 'real_test'] if opt.data == 'val': cam_fx, cam_fy, cam_cx, cam_cy = 577.5, 577.5, 319.5, 239.5 file_path = 'CAMERA/val_list.txt' else: cam_fx, cam_fy, cam_cx, cam_cy = 591.0125, 590.16775, 322.525, 244.11084 file_path = 'Real/test_list.txt' K = np.eye(3) K[0, 0] = cam_fx K[1, 1] = cam_fy K[0, 2] = cam_cx K[1, 2] = cam_cy result_dir = opt.result_dir result_img_dir = os.path.join(result_dir, 'images') if not os.path.exists(result_dir): os.makedirs(result_dir) os.makedirs(result_img_dir) dpt_dir = opt.data_dir.replace('NOCS', 'dpt_output') # path for shape & scale prior mean_shapes = np.load('assets/mean_points_emb.npy') with open('assets/mean_scale.pkl', 'rb') as f: mean_scale = cPickle.load(f) xmap = np.array([[i for i in range(640)] for j in range(480)]) ymap = np.array([[j for i in range(640)] for j in range(480)]) norm_scale = 1000.0 norm_color = transforms.Compose( [transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])] ) def run_demo(): # resume model
estimator = SPGANet(opt.n_cat, opt.nv_prior, num_structure_points=opt.num_structure_points, mode='test')
0
2023-10-13 11:28:15+00:00
8k
censys-workshop/threatfox-censys
threatfox_censys/__main__.py
[ { "identifier": "Fingerprint", "path": "threatfox_censys/fingerprint.py", "snippet": "class Fingerprint(BaseModel):\n name: str\n censys_query: str\n censys_virtual_hosts: bool = False\n threat_type: str = \"botnet_cc\"\n malware_name: str\n confidence_level: int = 50\n tags: list[s...
import logging import yaml from argparse import ArgumentParser, Namespace from datetime import datetime from enum import Enum from censys.common.exceptions import CensysException from censys.common.version import __version__ as censys_version from censys.search import CensysHosts from InquirerPy import prompt from InquirerPy.validator import EmptyInputValidator from mastodon import Mastodon from sqlalchemy import create_engine from sqlalchemy.orm import Session from .fingerprint import Fingerprint, load_fingerprints_from_yaml from .models import Base, IoC from .settings import settings from .threatfox import ThreatFoxClient, log_summary, log_threatfox_response_data from .utils import is_ipv4_address
4,482
DOMAIN = "domain" URL = "url" # Currently not supported by ThreatFox Censys def migrate_database(_: Namespace) -> int: with Session(engine) as session: # Create the tables Base.metadata.create_all(bind=engine) # Commit the session try: session.commit() except Exception as e: logging.error(f"Error committing session: {e}") return 1 # Log that we're done logging.info("Database migrations complete.") # Exit return 0 def submit_ioc( session: Session, threatfox_client: ThreatFoxClient, fingerprint: Fingerprint, ioc: str, ioc_type: IoCType, additional_tags: list[str] | None = None, reference: str | None = None, ) -> dict | None: """ Submit an IoC to ThreatFox. :param session: The database session. :param threatfox_client: The ThreatFox client. :param fingerprint: The fingerprint. :param ioc: The IoC. :param ioc_type: The IoC type. :param additional_tags: Additional tags to add to the IoC. :param reference: The reference to add to the IoC. :return: The ThreatFox response data. """ # Check if the IoC is already in the database ioc_in_database = ( session.query(IoC) .filter( IoC.ioc == ioc, IoC.ioc_type == ioc_type, IoC.threat_type == fingerprint.threat_type, ) .first() is not None ) # If the IoC is already in the database, return None if ioc_in_database: scan_logger.debug(f"IoC {ioc} already in database.") return None # Get fingerprint tags fingerprint_tags = [] # If the fingerprint has tags, add them if fingerprint.tags: fingerprint_tags.extend(fingerprint.tags) # Get additional tags fingerprint_tags.extend(additional_tags or []) # Add the "censys" tag fingerprint_tags.append("censys") # Create the tag list tags = list(set(fingerprint_tags)) # Log the tags # scan_logger.debug(f"Tags: {tags}") # Log that we're submitting the IoC to ThreatFox scan_logger.debug(f"Submitting {fingerprint.name} IoC {ioc} to ThreatFox...") # Submit the IoC to ThreatFox try: threatfox_response = threatfox_client.submit_ioc( threat_type=fingerprint.threat_type, ioc_type=ioc_type.value, malware=fingerprint.malware_name, iocs=[ioc], confidence_level=fingerprint.confidence_level, reference=reference, tags=tags, ) except Exception as e: scan_logger.error(f"Error submitting IoC '{ioc}' to ThreatFox: {e}") return None # Get the query status query_status = threatfox_response.get("query_status", "unknown") # If the query was successful, add the IoC to the database if query_status == "ok": # Create the IoC ioc_obj = IoC( ioc=ioc, ioc_type=ioc_type.value, threat_type=fingerprint.threat_type, submitted=True, ) # Add the IoC to the database session.add(ioc_obj) # Commit the session session.commit() # Get the data if data := threatfox_response.get("data", {}): # Log the response data
#!/usr/bin/env python3 """This is the main entrypoint for ThreatFox Censys.""" # Constants TIMEOUT = 45 USER_AGENT = ( f"censys-python/{censys_version} (ThreatfoxCensys;" " +https://github.com/censys-workshop/threatfox-censys)" ) # Create the scan logger scan_logger = logging.getLogger("scan") # Create the database engine engine = create_engine(settings.DATABASE_URL) # Create a ThreatFoxClient instance threatfox_client = ThreatFoxClient(api_key=settings.THREATFOX_API_KEY) # Create a CensysHosts instance censys_client = CensysHosts( api_id=settings.CENSYS_API_ID, api_secret=settings.CENSYS_API_SECRET, user_agent=USER_AGENT, timeout=TIMEOUT, ) # If Mastodon is configured, create a Mastodon instance mastodon_client = None if settings.MASTODON_API_URL and settings.MASTODON_ACCESS_TOKEN: mastodon_client = Mastodon( api_base_url=settings.MASTODON_API_URL, access_token=settings.MASTODON_ACCESS_TOKEN, ) class IoCType(str, Enum): """ IoC types. """ IP_PORT = "ip:port" DOMAIN = "domain" URL = "url" # Currently not supported by ThreatFox Censys def migrate_database(_: Namespace) -> int: with Session(engine) as session: # Create the tables Base.metadata.create_all(bind=engine) # Commit the session try: session.commit() except Exception as e: logging.error(f"Error committing session: {e}") return 1 # Log that we're done logging.info("Database migrations complete.") # Exit return 0 def submit_ioc( session: Session, threatfox_client: ThreatFoxClient, fingerprint: Fingerprint, ioc: str, ioc_type: IoCType, additional_tags: list[str] | None = None, reference: str | None = None, ) -> dict | None: """ Submit an IoC to ThreatFox. :param session: The database session. :param threatfox_client: The ThreatFox client. :param fingerprint: The fingerprint. :param ioc: The IoC. :param ioc_type: The IoC type. :param additional_tags: Additional tags to add to the IoC. :param reference: The reference to add to the IoC. :return: The ThreatFox response data. """ # Check if the IoC is already in the database ioc_in_database = ( session.query(IoC) .filter( IoC.ioc == ioc, IoC.ioc_type == ioc_type, IoC.threat_type == fingerprint.threat_type, ) .first() is not None ) # If the IoC is already in the database, return None if ioc_in_database: scan_logger.debug(f"IoC {ioc} already in database.") return None # Get fingerprint tags fingerprint_tags = [] # If the fingerprint has tags, add them if fingerprint.tags: fingerprint_tags.extend(fingerprint.tags) # Get additional tags fingerprint_tags.extend(additional_tags or []) # Add the "censys" tag fingerprint_tags.append("censys") # Create the tag list tags = list(set(fingerprint_tags)) # Log the tags # scan_logger.debug(f"Tags: {tags}") # Log that we're submitting the IoC to ThreatFox scan_logger.debug(f"Submitting {fingerprint.name} IoC {ioc} to ThreatFox...") # Submit the IoC to ThreatFox try: threatfox_response = threatfox_client.submit_ioc( threat_type=fingerprint.threat_type, ioc_type=ioc_type.value, malware=fingerprint.malware_name, iocs=[ioc], confidence_level=fingerprint.confidence_level, reference=reference, tags=tags, ) except Exception as e: scan_logger.error(f"Error submitting IoC '{ioc}' to ThreatFox: {e}") return None # Get the query status query_status = threatfox_response.get("query_status", "unknown") # If the query was successful, add the IoC to the database if query_status == "ok": # Create the IoC ioc_obj = IoC( ioc=ioc, ioc_type=ioc_type.value, threat_type=fingerprint.threat_type, submitted=True, ) # Add the IoC to the database session.add(ioc_obj) # Commit the session session.commit() # Get the data if data := threatfox_response.get("data", {}): # Log the response data
log_threatfox_response_data(fingerprint, ioc, data)
7
2023-10-11 22:35:29+00:00
8k
clessig/atmorep
atmorep/datasets/multifield_data_sampler.py
[ { "identifier": "DynamicFieldLevel", "path": "atmorep/datasets/dynamic_field_level.py", "snippet": "class DynamicFieldLevel() : \n \n ###################################################\n def __init__( self, file_path, years_data, field_info,\n batch_size, data_type = 'era5',\n ...
import torch import numpy as np import math import itertools import code import atmorep.config.config as config from atmorep.datasets.dynamic_field_level import DynamicFieldLevel from atmorep.datasets.static_field import StaticField from atmorep.utils.utils import days_until_month_in_year from atmorep.utils.utils import days_in_month
6,922
smoothing = 0, file_format = 'grib', month = None, lat_sampling_weighted = True, geo_range = [[-90.,90.], [0.,360.]], fields_targets = [], pre_batch_targets = None ) : ''' Data set for single dynamic field at an arbitrary number of vertical levels ''' super( MultifieldDataSampler).__init__() self.fields = fields self.batch_size = batch_size self.pre_batch = pre_batch self.years_data = years_data self.time_sampling = time_sampling self.month = month self.range_lat = 90. - np.array( geo_range[0]) self.range_lon = np.array( geo_range[1]) self.geo_range = geo_range # order North to South self.range_lat = np.flip(self.range_lat) if self.range_lat[1] < self.range_lat[0] \ else self.range_lat # prepare range_lat and range_lon for sampling self.is_global = 0 == self.range_lat[0] and self.range_lon[0] == 0. \ and 180. == self.range_lat[1] and 360. == self.range_lon[1] # TODO: this assumes file_shape is set correctly and not just per field and it defines a # reference grid, likely has to be the coarsest self.res = 360. / file_shape[2] # avoid wrap around at poles pole_offset = np.ceil(fields[0][3][1] * fields[0][4][1] / 2) * self.res self.range_lat[0] = pole_offset if self.range_lat[0] < pole_offset else self.range_lat[0] self.range_lat[1] =180.-pole_offset if 180.-self.range_lat[1]<pole_offset else self.range_lat[1] self.lat_sampling_weighted = lat_sampling_weighted self.level_type = level_type self.smoothing = smoothing self.file_path = config.path_data self.file_shape = file_shape self.file_format = file_format self.num_load = num_load self.num_patches_per_t = int(num_patches_per_t) self.num_t_samples = int(num_t_samples) self.fields_targets = fields_targets self.pre_batch_targets = pre_batch_targets # convert to mathematical latitude and ensure North -> South ordering # shrink so that cookie cutting based on sampling does not exceed domain if it is not global if not self.is_global : # TODO: check that field data is consistent and covers the same spatial domain # TODO: code below assumes that fields[0] is global # TODO: code below does not handle anisotropic grids finfo = self.fields[0] # ensure that delta is a multiple of the coarse grid resolution ngrid1 = finfo[3][1] * finfo[4][1] ngrid2 = finfo[3][2] * finfo[4][2] delta1 = 0.5 * self.res * (ngrid1-1 if ngrid1 % 2==0 else ngrid1+1) delta2 = 0.5 * self.res * (ngrid2-1 if ngrid2 % 2==0 else ngrid2+1) self.range_lat += np.array([delta1, -delta1]) self.range_lon += np.array([delta2, -delta2]) # ensure all data loaders use same rng_seed and hence generate consistent data if not rng_seed : rng_seed = np.random.randint( 0, 100000, 1)[0] self.rng = np.random.default_rng( rng_seed) # create (source) fields self.datasets = self.create_loaders( fields) # create (target) fields self.datasets_targets = self.create_loaders( fields_targets) ################################################### def create_loaders( self, fields ) : datasets = [] for field_idx, field_info in enumerate(fields) : datasets.append( []) # extract field info (vls, num_tokens, token_size) = field_info[2:5] if len(field_info) > 6 : corr_type = field_info[6] else: corr_type = 'global' smoothing = self.smoothing log_transform_data = False if len(field_info) > 7 : (data_type, file_shape, file_geo_range, file_format) = field_info[7][:4] if len( field_info[7]) > 6 : smoothing = field_info[7][6] print( '{} : smoothing = {}'.format( field_info[0], smoothing) ) if len( field_info[7]) > 7 : log_transform_data = field_info[7][7] print( '{} : log_transform_data = {}'.format( field_info[0], log_transform_data) ) else : data_type = 'era5' file_format = self.file_format file_shape = self.file_shape file_geo_range = [[90.,-90.], [0.,360.]] # static fields if 0 == field_info[1][0] : datasets[-1].append( StaticField( self.file_path, field_info, self.batch_size, data_type, file_shape, file_geo_range, num_tokens, token_size, smoothing, file_format, corr_type) ) # dynamic fields elif 1 == field_info[1][0] : for vlevel in vls :
#################################################################################################### # # Copyright (C) 2022 # #################################################################################################### # # project : atmorep # # author : atmorep collaboration # # description : # # license : # #################################################################################################### # code.interact(local=locals()) class MultifieldDataSampler( torch.utils.data.IterableDataset): ################################################### def __init__( self, file_path, years_data, fields, batch_size, num_t_samples, num_patches_per_t, num_load, pre_batch, rng_seed = None, file_shape = (-1, 721, 1440), level_type = 'ml', time_sampling = 1, smoothing = 0, file_format = 'grib', month = None, lat_sampling_weighted = True, geo_range = [[-90.,90.], [0.,360.]], fields_targets = [], pre_batch_targets = None ) : ''' Data set for single dynamic field at an arbitrary number of vertical levels ''' super( MultifieldDataSampler).__init__() self.fields = fields self.batch_size = batch_size self.pre_batch = pre_batch self.years_data = years_data self.time_sampling = time_sampling self.month = month self.range_lat = 90. - np.array( geo_range[0]) self.range_lon = np.array( geo_range[1]) self.geo_range = geo_range # order North to South self.range_lat = np.flip(self.range_lat) if self.range_lat[1] < self.range_lat[0] \ else self.range_lat # prepare range_lat and range_lon for sampling self.is_global = 0 == self.range_lat[0] and self.range_lon[0] == 0. \ and 180. == self.range_lat[1] and 360. == self.range_lon[1] # TODO: this assumes file_shape is set correctly and not just per field and it defines a # reference grid, likely has to be the coarsest self.res = 360. / file_shape[2] # avoid wrap around at poles pole_offset = np.ceil(fields[0][3][1] * fields[0][4][1] / 2) * self.res self.range_lat[0] = pole_offset if self.range_lat[0] < pole_offset else self.range_lat[0] self.range_lat[1] =180.-pole_offset if 180.-self.range_lat[1]<pole_offset else self.range_lat[1] self.lat_sampling_weighted = lat_sampling_weighted self.level_type = level_type self.smoothing = smoothing self.file_path = config.path_data self.file_shape = file_shape self.file_format = file_format self.num_load = num_load self.num_patches_per_t = int(num_patches_per_t) self.num_t_samples = int(num_t_samples) self.fields_targets = fields_targets self.pre_batch_targets = pre_batch_targets # convert to mathematical latitude and ensure North -> South ordering # shrink so that cookie cutting based on sampling does not exceed domain if it is not global if not self.is_global : # TODO: check that field data is consistent and covers the same spatial domain # TODO: code below assumes that fields[0] is global # TODO: code below does not handle anisotropic grids finfo = self.fields[0] # ensure that delta is a multiple of the coarse grid resolution ngrid1 = finfo[3][1] * finfo[4][1] ngrid2 = finfo[3][2] * finfo[4][2] delta1 = 0.5 * self.res * (ngrid1-1 if ngrid1 % 2==0 else ngrid1+1) delta2 = 0.5 * self.res * (ngrid2-1 if ngrid2 % 2==0 else ngrid2+1) self.range_lat += np.array([delta1, -delta1]) self.range_lon += np.array([delta2, -delta2]) # ensure all data loaders use same rng_seed and hence generate consistent data if not rng_seed : rng_seed = np.random.randint( 0, 100000, 1)[0] self.rng = np.random.default_rng( rng_seed) # create (source) fields self.datasets = self.create_loaders( fields) # create (target) fields self.datasets_targets = self.create_loaders( fields_targets) ################################################### def create_loaders( self, fields ) : datasets = [] for field_idx, field_info in enumerate(fields) : datasets.append( []) # extract field info (vls, num_tokens, token_size) = field_info[2:5] if len(field_info) > 6 : corr_type = field_info[6] else: corr_type = 'global' smoothing = self.smoothing log_transform_data = False if len(field_info) > 7 : (data_type, file_shape, file_geo_range, file_format) = field_info[7][:4] if len( field_info[7]) > 6 : smoothing = field_info[7][6] print( '{} : smoothing = {}'.format( field_info[0], smoothing) ) if len( field_info[7]) > 7 : log_transform_data = field_info[7][7] print( '{} : log_transform_data = {}'.format( field_info[0], log_transform_data) ) else : data_type = 'era5' file_format = self.file_format file_shape = self.file_shape file_geo_range = [[90.,-90.], [0.,360.]] # static fields if 0 == field_info[1][0] : datasets[-1].append( StaticField( self.file_path, field_info, self.batch_size, data_type, file_shape, file_geo_range, num_tokens, token_size, smoothing, file_format, corr_type) ) # dynamic fields elif 1 == field_info[1][0] : for vlevel in vls :
datasets[-1].append( DynamicFieldLevel( self.file_path, self.years_data, field_info,
0
2023-10-09 19:42:46+00:00
8k
google/mesop
mesop/editor/editor_codemod_test.py
[ { "identifier": "DeleteComponentCodemod", "path": "mesop/editor/editor_codemod.py", "snippet": "class DeleteComponentCodemod(VisitorBasedCodemodCommand):\n DESCRIPTION: str = \"Removes component callsite.\"\n METADATA_DEPENDENCIES = (PositionProvider,)\n\n def __init__(\n self, context: CodemodCon...
import unittest import mesop.protos.ui_pb2 as pb from libcst.codemod import ( CodemodTest, ) from mesop.editor.editor_codemod import ( DeleteComponentCodemod, NewComponentCodemod, UpdateCallsiteCodemod, ) from mesop.utils.runfiles import get_runfile_location
3,675
def test_delete_component(self) -> None: self.assertEditorUpdate( "delete_component", pb.EditorDeleteComponent( source_code_location=pb.SourceCodeLocation(line=6), ), ) def test_delete_only_component(self) -> None: self.assertEditorUpdate( "delete_only_component", pb.EditorDeleteComponent( source_code_location=pb.SourceCodeLocation(line=5), ), ) def test_delete_custom_component(self) -> None: self.assertEditorUpdate( "delete_custom_component", pb.EditorDeleteComponent( source_code_location=pb.SourceCodeLocation(line=6), ), ) def assertEditorUpdate( self, test_case_name: str, input: pb.EditorDeleteComponent ): self.assertCodemod( load_testdata(dir=test_case_name, filename="before.py"), load_testdata(dir=test_case_name, filename="after.py"), input=input, ) class TestNewComponentCodemod(CodemodTest): TRANSFORM = NewComponentCodemod def test_new_component(self) -> None: self.assertEditorUpdate( "new_component", pb.EditorNewComponent( component_name=me_name("divider"), source_code_location=pb.SourceCodeLocation(line=5), mode=pb.EditorNewComponent.Mode.MODE_APPEND_SIBLING, ), ) def test_new_custom_component(self) -> None: self.assertEditorUpdate( "new_custom_component", pb.EditorNewComponent( component_name=pb.ComponentName( fn_name="columns", module_path="mesop.labs.layout" ), source_code_location=pb.SourceCodeLocation(line=5), mode=pb.EditorNewComponent.Mode.MODE_APPEND_SIBLING, ), ) def test_new_component_nested_sibling(self) -> None: self.assertEditorUpdate( "new_component_nested_sibling", pb.EditorNewComponent( component_name=me_name("divider"), source_code_location=pb.SourceCodeLocation(line=6), mode=pb.EditorNewComponent.Mode.MODE_APPEND_SIBLING, ), ) def test_new_component_with_block_nested_sibling(self) -> None: self.assertEditorUpdate( "new_component_with_block_nested_sibling", pb.EditorNewComponent( component_name=me_name("divider"), source_code_location=pb.SourceCodeLocation(line=5), mode=pb.EditorNewComponent.Mode.MODE_APPEND_SIBLING, ), ) def test_new_component_child(self) -> None: self.assertEditorUpdate( "new_component_child", pb.EditorNewComponent( component_name=me_name("text"), source_code_location=pb.SourceCodeLocation(line=5), mode=pb.EditorNewComponent.Mode.MODE_CHILD, ), ) def test_new_component_child_existing_with(self) -> None: self.assertEditorUpdate( "new_component_child_existing_with", pb.EditorNewComponent( component_name=me_name("text"), source_code_location=pb.SourceCodeLocation(line=5), mode=pb.EditorNewComponent.Mode.MODE_CHILD, ), ) def test_new_component_child_existing_with_pass(self) -> None: self.assertEditorUpdate( "new_component_child_existing_with_pass", pb.EditorNewComponent( component_name=me_name("text"), source_code_location=pb.SourceCodeLocation(line=5), mode=pb.EditorNewComponent.Mode.MODE_CHILD, ), ) def assertEditorUpdate( self, test_case_name: str, input: pb.EditorNewComponent ): self.assertCodemod( load_testdata(dir=test_case_name, filename="before.py"), load_testdata(dir=test_case_name, filename="after.py"), input=input, ) class TestUpdateCallsiteCodemod(CodemodTest):
def load_testdata(dir: str, filename: str) -> str: with open( get_runfile_location(f"mesop/mesop/editor/testdata/{dir}/{filename}") ) as f: return f.read() class TestDeleteComponentCodemod(CodemodTest): TRANSFORM = DeleteComponentCodemod def test_delete_component(self) -> None: self.assertEditorUpdate( "delete_component", pb.EditorDeleteComponent( source_code_location=pb.SourceCodeLocation(line=6), ), ) def test_delete_only_component(self) -> None: self.assertEditorUpdate( "delete_only_component", pb.EditorDeleteComponent( source_code_location=pb.SourceCodeLocation(line=5), ), ) def test_delete_custom_component(self) -> None: self.assertEditorUpdate( "delete_custom_component", pb.EditorDeleteComponent( source_code_location=pb.SourceCodeLocation(line=6), ), ) def assertEditorUpdate( self, test_case_name: str, input: pb.EditorDeleteComponent ): self.assertCodemod( load_testdata(dir=test_case_name, filename="before.py"), load_testdata(dir=test_case_name, filename="after.py"), input=input, ) class TestNewComponentCodemod(CodemodTest): TRANSFORM = NewComponentCodemod def test_new_component(self) -> None: self.assertEditorUpdate( "new_component", pb.EditorNewComponent( component_name=me_name("divider"), source_code_location=pb.SourceCodeLocation(line=5), mode=pb.EditorNewComponent.Mode.MODE_APPEND_SIBLING, ), ) def test_new_custom_component(self) -> None: self.assertEditorUpdate( "new_custom_component", pb.EditorNewComponent( component_name=pb.ComponentName( fn_name="columns", module_path="mesop.labs.layout" ), source_code_location=pb.SourceCodeLocation(line=5), mode=pb.EditorNewComponent.Mode.MODE_APPEND_SIBLING, ), ) def test_new_component_nested_sibling(self) -> None: self.assertEditorUpdate( "new_component_nested_sibling", pb.EditorNewComponent( component_name=me_name("divider"), source_code_location=pb.SourceCodeLocation(line=6), mode=pb.EditorNewComponent.Mode.MODE_APPEND_SIBLING, ), ) def test_new_component_with_block_nested_sibling(self) -> None: self.assertEditorUpdate( "new_component_with_block_nested_sibling", pb.EditorNewComponent( component_name=me_name("divider"), source_code_location=pb.SourceCodeLocation(line=5), mode=pb.EditorNewComponent.Mode.MODE_APPEND_SIBLING, ), ) def test_new_component_child(self) -> None: self.assertEditorUpdate( "new_component_child", pb.EditorNewComponent( component_name=me_name("text"), source_code_location=pb.SourceCodeLocation(line=5), mode=pb.EditorNewComponent.Mode.MODE_CHILD, ), ) def test_new_component_child_existing_with(self) -> None: self.assertEditorUpdate( "new_component_child_existing_with", pb.EditorNewComponent( component_name=me_name("text"), source_code_location=pb.SourceCodeLocation(line=5), mode=pb.EditorNewComponent.Mode.MODE_CHILD, ), ) def test_new_component_child_existing_with_pass(self) -> None: self.assertEditorUpdate( "new_component_child_existing_with_pass", pb.EditorNewComponent( component_name=me_name("text"), source_code_location=pb.SourceCodeLocation(line=5), mode=pb.EditorNewComponent.Mode.MODE_CHILD, ), ) def assertEditorUpdate( self, test_case_name: str, input: pb.EditorNewComponent ): self.assertCodemod( load_testdata(dir=test_case_name, filename="before.py"), load_testdata(dir=test_case_name, filename="after.py"), input=input, ) class TestUpdateCallsiteCodemod(CodemodTest):
TRANSFORM = UpdateCallsiteCodemod
2
2023-10-13 23:24:32+00:00
8k
MachinePerceptionLab/Attentive_DFPrior
src/Mapper.py
[ { "identifier": "get_samples", "path": "src/common.py", "snippet": "def get_samples(H0, H1, W0, W1, n, H, W, fx, fy, cx, cy, c2w, depth, color, device):\n \"\"\"\n Get n rays from the image region H0..H1, W0..W1.\n c2w is its camera pose and depth/color is the corresponding image tensor.\n\n ...
import os import time import cv2 import numpy as np import torch from colorama import Fore, Style from torch.autograd import Variable from src.common import (get_samples, random_select) from src.utils.datasets import get_dataset from src.utils.Visualizer import Visualizer
4,824
Returns: selected_keyframe_list (list): list of selected keyframe id. """ device = self.device H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy rays_o, rays_d, gt_depth, gt_color = get_samples( 0, H, 0, W, pixels, H, W, fx, fy, cx, cy, c2w, gt_depth, gt_color, self.device) gt_depth = gt_depth.reshape(-1, 1) gt_depth = gt_depth.repeat(1, N_samples) t_vals = torch.linspace(0., 1., steps=N_samples).to(device) near = gt_depth*0.8 far = gt_depth+0.5 z_vals = near * (1.-t_vals) + far * (t_vals) pts = rays_o[..., None, :] + rays_d[..., None, :] * \ z_vals[..., :, None] # [N_rays, N_samples, 3] vertices = pts.reshape(-1, 3).cpu().numpy() list_keyframe = [] for keyframeid, keyframe in enumerate(keyframe_dict): c2w = keyframe['est_c2w'].cpu().numpy() w2c = np.linalg.inv(c2w) ones = np.ones_like(vertices[:, 0]).reshape(-1, 1) homo_vertices = np.concatenate( [vertices, ones], axis=1).reshape(-1, 4, 1) # (N, 4) cam_cord_homo = w2c@homo_vertices # (N, 4, 1)=(4,4)*(N, 4, 1) cam_cord = cam_cord_homo[:, :3] # (N, 3, 1) K = np.array([[fx, .0, cx], [.0, fy, cy], [.0, .0, 1.0]]).reshape(3, 3) cam_cord[:, 0] *= -1 uv = K@cam_cord z = uv[:, -1:]+1e-5 uv = uv[:, :2]/z uv = uv.astype(np.float32) edge = 20 mask = (uv[:, 0] < W-edge)*(uv[:, 0] > edge) * \ (uv[:, 1] < H-edge)*(uv[:, 1] > edge) mask = mask & (z[:, :, 0] < 0) mask = mask.reshape(-1) percent_inside = mask.sum()/uv.shape[0] list_keyframe.append( {'id': keyframeid, 'percent_inside': percent_inside}) list_keyframe = sorted( list_keyframe, key=lambda i: i['percent_inside'], reverse=True) selected_keyframe_list = [dic['id'] for dic in list_keyframe if dic['percent_inside'] > 0.00] selected_keyframe_list = list(np.random.permutation( np.array(selected_keyframe_list))[:k]) return selected_keyframe_list def eval_points(self, p, decoders, tsdf_volume, tsdf_bnds, c=None, stage='color', device='cuda:0'): """ Evaluates the occupancy and/or color value for the points. Args: p (tensor, N*3): point coordinates. decoders (nn.module decoders): decoders. c (dicts, optional): feature grids. Defaults to None. stage (str, optional): query stage, corresponds to different levels. Defaults to 'color'. device (str, optional): device name to compute on. Defaults to 'cuda:0'. Returns: ret (tensor): occupancy (and color) value of input points. """ p_split = torch.split(p, 500) bound = self.bound rets = [] for pi in p_split: # mask for points out of bound mask_x = (pi[:, 0] < bound[0][1]) & (pi[:, 0] > bound[0][0]) mask_y = (pi[:, 1] < bound[1][1]) & (pi[:, 1] > bound[1][0]) mask_z = (pi[:, 2] < bound[2][1]) & (pi[:, 2] > bound[2][0]) mask = mask_x & mask_y & mask_z pi = pi.unsqueeze(0) ret, _ = decoders(pi, c_grid=c, tsdf_volume=tsdf_volume, tsdf_bnds=tsdf_bnds, stage=stage) ret = ret.squeeze(0) if len(ret.shape) == 1 and ret.shape[0] == 4: ret = ret.unsqueeze(0) ret[~mask, 3] = 100 rets.append(ret) ret = torch.cat(rets, dim=0) return ret def optimize_map(self, num_joint_iters, lr_factor, idx, cur_gt_color, cur_gt_depth, gt_cur_c2w, keyframe_dict, keyframe_list, tsdf_volume, cur_c2w): """ Mapping iterations. Sample pixels from selected keyframes, then optimize scene representation. Args: num_joint_iters (int): number of mapping iterations. lr_factor (float): the factor to times on current lr. idx (int): the index of current frame cur_gt_color (tensor): gt_color image of the current camera. cur_gt_depth (tensor): gt_depth image of the current camera. gt_cur_c2w (tensor): groundtruth camera to world matrix corresponding to current frame. keyframe_dict (list): list of keyframes info dictionary. keyframe_list (list): list ofkeyframe index. tsdf_volume (tensor): tsdf volume. cur_c2w (tensor): the estimated camera to world matrix of current frame. Returns: return None """ H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy c = self.c cfg = self.cfg device = self.device tsdf_bnds = self.tsdf_bnds.to(device) if len(keyframe_dict) == 0: optimize_frame = [] else: if self.keyframe_selection_method == 'global': num = self.mapping_window_size-2
class Mapper(object): """ Mapper thread. """ def __init__(self, cfg, args, slam ): self.cfg = cfg self.args = args self.idx = slam.idx self.c = slam.shared_c self.bound = slam.bound self.logger = slam.logger self.mesher = slam.mesher self.output = slam.output self.verbose = slam.verbose self.renderer = slam.renderer self.low_gpu_mem = slam.low_gpu_mem self.mapping_idx = slam.mapping_idx self.mapping_cnt = slam.mapping_cnt self.decoders = slam.shared_decoders self.estimate_c2w_list = slam.estimate_c2w_list self.mapping_first_frame = slam.mapping_first_frame self.scene_id = slam.scene_id with torch.no_grad(): self.tsdf_volume_shared = slam.tsdf_volume_shared self.tsdf_bnds = slam.tsdf_bnds self.scale = cfg['scale'] self.occupancy = cfg['occupancy'] self.sync_method = cfg['sync_method'] self.device = cfg['mapping']['device'] self.fix_high = cfg['mapping']['fix_high'] self.eval_rec = cfg['meshing']['eval_rec'] self.mesh_freq = cfg['mapping']['mesh_freq'] self.ckpt_freq = cfg['mapping']['ckpt_freq'] self.fix_color = cfg['mapping']['fix_color'] self.mapping_pixels = cfg['mapping']['pixels'] self.num_joint_iters = cfg['mapping']['iters'] self.clean_mesh = cfg['meshing']['clean_mesh'] self.every_frame = cfg['mapping']['every_frame'] self.color_refine = cfg['mapping']['color_refine'] self.w_color_loss = cfg['mapping']['w_color_loss'] self.keyframe_every = cfg['mapping']['keyframe_every'] self.high_iter_ratio = cfg['mapping']['high_iter_ratio'] self.low_iter_ratio = cfg['mapping']['low_iter_ratio'] self.mapping_window_size = cfg['mapping']['mapping_window_size'] self.no_vis_on_first_frame = cfg['mapping']['no_vis_on_first_frame'] self.no_log_on_first_frame = cfg['mapping']['no_log_on_first_frame'] self.no_mesh_on_first_frame = cfg['mapping']['no_mesh_on_first_frame'] self.frustum_feature_selection = cfg['mapping']['frustum_feature_selection'] self.keyframe_selection_method = cfg['mapping']['keyframe_selection_method'] self.save_selected_keyframes_info = cfg['mapping']['save_selected_keyframes_info'] if self.save_selected_keyframes_info: self.selected_keyframes = {} self.keyframe_dict = [] self.keyframe_list = [] self.frame_reader = get_dataset( cfg, args, self.scale, device=self.device) self.n_img = len(self.frame_reader) if 'Demo' not in self.output: # disable this visualization in demo self.visualizer = Visualizer(freq=cfg['mapping']['vis_freq'], inside_freq=cfg['mapping']['vis_inside_freq'], vis_dir=os.path.join(self.output, 'mapping_vis'), renderer=self.renderer, verbose=self.verbose, device=self.device) self.H, self.W, self.fx, self.fy, self.cx, self.cy = slam.H, slam.W, slam.fx, slam.fy, slam.cx, slam.cy def get_mask_from_c2w(self, c2w, key, val_shape, depth_np): """ Frustum feature selection based on current camera pose and depth image. Args: c2w (tensor): camera pose of current frame. key (str): name of this feature grid. val_shape (tensor): shape of the grid. depth_np (numpy.array): depth image of current frame. Returns: mask (tensor): mask for selected optimizable feature. points (tensor): corresponding point coordinates. """ H, W, fx, fy, cx, cy, = self.H, self.W, self.fx, self.fy, self.cx, self.cy X, Y, Z = torch.meshgrid(torch.linspace(self.bound[0][0], self.bound[0][1], val_shape[2]), torch.linspace(self.bound[1][0], self.bound[1][1], val_shape[1]), torch.linspace(self.bound[2][0], self.bound[2][1], val_shape[0])) points = torch.stack([X, Y, Z], dim=-1).reshape(-1, 3) points_bak = points.clone() c2w = c2w.cpu().numpy() w2c = np.linalg.inv(c2w) ones = np.ones_like(points[:, 0]).reshape(-1, 1) homo_vertices = np.concatenate( [points, ones], axis=1).reshape(-1, 4, 1) cam_cord_homo = w2c@homo_vertices cam_cord = cam_cord_homo[:, :3] K = np.array([[fx, .0, cx], [.0, fy, cy], [.0, .0, 1.0]]).reshape(3, 3) cam_cord[:, 0] *= -1 uv = K@cam_cord z = uv[:, -1:]+1e-5 uv = uv[:, :2]/z uv = uv.astype(np.float32) remap_chunk = int(3e4) depths = [] for i in range(0, uv.shape[0], remap_chunk): depths += [cv2.remap(depth_np, uv[i:i+remap_chunk, 0], uv[i:i+remap_chunk, 1], interpolation=cv2.INTER_LINEAR)[:, 0].reshape(-1, 1)] depths = np.concatenate(depths, axis=0) edge = 0 mask = (uv[:, 0] < W-edge)*(uv[:, 0] > edge) * \ (uv[:, 1] < H-edge)*(uv[:, 1] > edge) # For ray with depth==0, fill it with maximum depth zero_mask = (depths == 0) depths[zero_mask] = np.max(depths) # depth test mask = mask & (0 <= -z[:, :, 0]) & (-z[:, :, 0] <= depths+0.5) mask = mask.reshape(-1) # add feature grid near cam center ray_o = c2w[:3, 3] ray_o = torch.from_numpy(ray_o).unsqueeze(0) dist = points_bak-ray_o dist = torch.sum(dist*dist, axis=1) mask2 = dist < 0.5*0.5 mask2 = mask2.cpu().numpy() mask = mask | mask2 points = points[mask] mask = mask.reshape(val_shape[2], val_shape[1], val_shape[0]) return mask def keyframe_selection_overlap(self, gt_color, gt_depth, c2w, keyframe_dict, k, N_samples=16, pixels=100): """ Select overlapping keyframes to the current camera observation. Args: gt_color (tensor): ground truth color image of the current frame. gt_depth (tensor): ground truth depth image of the current frame. c2w (tensor): camera to world matrix (3*4 or 4*4 both fine). keyframe_dict (list): a list containing info for each keyframe. k (int): number of overlapping keyframes to select. N_samples (int, optional): number of samples/points per ray. Defaults to 16. pixels (int, optional): number of pixels to sparsely sample from the image of the current camera. Defaults to 100. Returns: selected_keyframe_list (list): list of selected keyframe id. """ device = self.device H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy rays_o, rays_d, gt_depth, gt_color = get_samples( 0, H, 0, W, pixels, H, W, fx, fy, cx, cy, c2w, gt_depth, gt_color, self.device) gt_depth = gt_depth.reshape(-1, 1) gt_depth = gt_depth.repeat(1, N_samples) t_vals = torch.linspace(0., 1., steps=N_samples).to(device) near = gt_depth*0.8 far = gt_depth+0.5 z_vals = near * (1.-t_vals) + far * (t_vals) pts = rays_o[..., None, :] + rays_d[..., None, :] * \ z_vals[..., :, None] # [N_rays, N_samples, 3] vertices = pts.reshape(-1, 3).cpu().numpy() list_keyframe = [] for keyframeid, keyframe in enumerate(keyframe_dict): c2w = keyframe['est_c2w'].cpu().numpy() w2c = np.linalg.inv(c2w) ones = np.ones_like(vertices[:, 0]).reshape(-1, 1) homo_vertices = np.concatenate( [vertices, ones], axis=1).reshape(-1, 4, 1) # (N, 4) cam_cord_homo = w2c@homo_vertices # (N, 4, 1)=(4,4)*(N, 4, 1) cam_cord = cam_cord_homo[:, :3] # (N, 3, 1) K = np.array([[fx, .0, cx], [.0, fy, cy], [.0, .0, 1.0]]).reshape(3, 3) cam_cord[:, 0] *= -1 uv = K@cam_cord z = uv[:, -1:]+1e-5 uv = uv[:, :2]/z uv = uv.astype(np.float32) edge = 20 mask = (uv[:, 0] < W-edge)*(uv[:, 0] > edge) * \ (uv[:, 1] < H-edge)*(uv[:, 1] > edge) mask = mask & (z[:, :, 0] < 0) mask = mask.reshape(-1) percent_inside = mask.sum()/uv.shape[0] list_keyframe.append( {'id': keyframeid, 'percent_inside': percent_inside}) list_keyframe = sorted( list_keyframe, key=lambda i: i['percent_inside'], reverse=True) selected_keyframe_list = [dic['id'] for dic in list_keyframe if dic['percent_inside'] > 0.00] selected_keyframe_list = list(np.random.permutation( np.array(selected_keyframe_list))[:k]) return selected_keyframe_list def eval_points(self, p, decoders, tsdf_volume, tsdf_bnds, c=None, stage='color', device='cuda:0'): """ Evaluates the occupancy and/or color value for the points. Args: p (tensor, N*3): point coordinates. decoders (nn.module decoders): decoders. c (dicts, optional): feature grids. Defaults to None. stage (str, optional): query stage, corresponds to different levels. Defaults to 'color'. device (str, optional): device name to compute on. Defaults to 'cuda:0'. Returns: ret (tensor): occupancy (and color) value of input points. """ p_split = torch.split(p, 500) bound = self.bound rets = [] for pi in p_split: # mask for points out of bound mask_x = (pi[:, 0] < bound[0][1]) & (pi[:, 0] > bound[0][0]) mask_y = (pi[:, 1] < bound[1][1]) & (pi[:, 1] > bound[1][0]) mask_z = (pi[:, 2] < bound[2][1]) & (pi[:, 2] > bound[2][0]) mask = mask_x & mask_y & mask_z pi = pi.unsqueeze(0) ret, _ = decoders(pi, c_grid=c, tsdf_volume=tsdf_volume, tsdf_bnds=tsdf_bnds, stage=stage) ret = ret.squeeze(0) if len(ret.shape) == 1 and ret.shape[0] == 4: ret = ret.unsqueeze(0) ret[~mask, 3] = 100 rets.append(ret) ret = torch.cat(rets, dim=0) return ret def optimize_map(self, num_joint_iters, lr_factor, idx, cur_gt_color, cur_gt_depth, gt_cur_c2w, keyframe_dict, keyframe_list, tsdf_volume, cur_c2w): """ Mapping iterations. Sample pixels from selected keyframes, then optimize scene representation. Args: num_joint_iters (int): number of mapping iterations. lr_factor (float): the factor to times on current lr. idx (int): the index of current frame cur_gt_color (tensor): gt_color image of the current camera. cur_gt_depth (tensor): gt_depth image of the current camera. gt_cur_c2w (tensor): groundtruth camera to world matrix corresponding to current frame. keyframe_dict (list): list of keyframes info dictionary. keyframe_list (list): list ofkeyframe index. tsdf_volume (tensor): tsdf volume. cur_c2w (tensor): the estimated camera to world matrix of current frame. Returns: return None """ H, W, fx, fy, cx, cy = self.H, self.W, self.fx, self.fy, self.cx, self.cy c = self.c cfg = self.cfg device = self.device tsdf_bnds = self.tsdf_bnds.to(device) if len(keyframe_dict) == 0: optimize_frame = [] else: if self.keyframe_selection_method == 'global': num = self.mapping_window_size-2
optimize_frame = random_select(len(self.keyframe_dict)-1, num)
1
2023-10-13 00:49:57+00:00
8k
NKI-AI/ahcore
ahcore/utils/callbacks.py
[ { "identifier": "H5FileImageReader", "path": "ahcore/readers.py", "snippet": "class H5FileImageReader:\n def __init__(self, filename: Path, stitching_mode: StitchingMode) -> None:\n self._filename = filename\n self._stitching_mode = stitching_mode\n\n self.__empty_tile: GenericAr...
import hashlib import logging import numpy as np import numpy.typing as npt from pathlib import Path from typing import Any, Iterator, Optional from dlup import SlideImage from dlup.annotations import WsiAnnotations from dlup.data.transforms import convert_annotations, rename_labels from dlup.tiling import Grid, GridOrder, TilingMode from shapely.geometry import MultiPoint, Point from torch.utils.data import Dataset from ahcore.readers import H5FileImageReader from ahcore.transforms.pre_transforms import one_hot_encoding from ahcore.utils.data import DataDescription from ahcore.utils.io import get_logger from ahcore.utils.types import DlupDatasetSample
3,815
"""Ahcore's callbacks""" from __future__ import annotations logger = get_logger(__name__) logging.getLogger("pyvips").setLevel(logging.ERROR) class _ValidationDataset(Dataset[DlupDatasetSample]): """Helper dataset to compute the validation metrics.""" def __init__( self, data_description: Optional[DataDescription], native_mpp: float,
"""Ahcore's callbacks""" from __future__ import annotations logger = get_logger(__name__) logging.getLogger("pyvips").setLevel(logging.ERROR) class _ValidationDataset(Dataset[DlupDatasetSample]): """Helper dataset to compute the validation metrics.""" def __init__( self, data_description: Optional[DataDescription], native_mpp: float,
reader: H5FileImageReader,
0
2023-10-14 18:04:12+00:00
8k
chziakas/redeval
redeval/simulators/conservative_social_engineering_attack_simulator.py
[ { "identifier": "CosnervativeHumanAgent", "path": "redeval/agents/conservative_human_agent.py", "snippet": "class CosnervativeHumanAgent:\n\n PROMPT = PromptTemplate(\n \"\"\"\n You are a helpful person that is an expert on the given content. You are also not eager to share confidential...
import json from datetime import datetime from redeval.agents.conservative_human_agent import CosnervativeHumanAgent from redeval.evaluators.answer_relevance import AnswerRelevance from redeval.evaluators.context_relevance import ContextRelevance from redeval.evaluators.faithfulness import Faithfulness from redeval.generators.questions.conversational_generator import ConversationalGenerator from redeval.generators.questions.social_engineering_attack_question_generator import ( SocialEngineeringAttackQuestionGenerator, )
3,919
# Import necessary libraries and modules class ConservativeSocialEngineeringAttackSimulator: def __init__( self, openai_api_key, n_turns=3, num_questions=1, context_file="data/examples/company/airbnb.txt", data_path="data/examples/company", eval_path="data/examples/conservative_social_attack_simulation.json", additional_questions=[], ): # Initialize various agents and generators with provided parameters with open(context_file, "r") as file: context = file.read() self.initial_generator = SocialEngineeringAttackQuestionGenerator( model="gpt-3.5-turbo-16k", open_ai_key=openai_api_key ) self.agent = CosnervativeHumanAgent( "data/examples/company", openai_api_key=openai_api_key, model_name="gpt-3.5-turbo-16k" ) self.conversation_generator = ConversationalGenerator( model="gpt-3.5-turbo-16k", open_ai_key=openai_api_key ) self.context_relevance = ContextRelevance("gpt-3.5-turbo", openai_api_key) self.answer_relevance = AnswerRelevance("gpt-3.5-turbo", openai_api_key)
# Import necessary libraries and modules class ConservativeSocialEngineeringAttackSimulator: def __init__( self, openai_api_key, n_turns=3, num_questions=1, context_file="data/examples/company/airbnb.txt", data_path="data/examples/company", eval_path="data/examples/conservative_social_attack_simulation.json", additional_questions=[], ): # Initialize various agents and generators with provided parameters with open(context_file, "r") as file: context = file.read() self.initial_generator = SocialEngineeringAttackQuestionGenerator( model="gpt-3.5-turbo-16k", open_ai_key=openai_api_key ) self.agent = CosnervativeHumanAgent( "data/examples/company", openai_api_key=openai_api_key, model_name="gpt-3.5-turbo-16k" ) self.conversation_generator = ConversationalGenerator( model="gpt-3.5-turbo-16k", open_ai_key=openai_api_key ) self.context_relevance = ContextRelevance("gpt-3.5-turbo", openai_api_key) self.answer_relevance = AnswerRelevance("gpt-3.5-turbo", openai_api_key)
self.faithfulness = Faithfulness("gpt-3.5-turbo", openai_api_key)
3
2023-10-07 00:47:41+00:00
8k
fury-05/BookRecomendApp
.pythonlibs/lib/python3.10/site-packages/sklearn/utils/extmath.py
[ { "identifier": "check_random_state", "path": ".pythonlibs/lib/python3.10/site-packages/sklearn/utils/validation.py", "snippet": "def check_random_state(seed):\n \"\"\"Turn seed into a np.random.RandomState instance.\n\n Parameters\n ----------\n seed : None, int or instance of RandomState\n...
import warnings import numpy as np from scipy import linalg, sparse from . import check_random_state from ._array_api import _is_numpy_namespace, get_namespace from ._logistic_sigmoid import _log_logistic_sigmoid from .sparsefuncs_fast import csr_row_norms from .validation import check_array
6,834
Adjusts the columns of u and the rows of v such that the loadings in the columns in u that are largest in absolute value are always positive. Parameters ---------- u : ndarray Parameters u and v are the output of `linalg.svd` or :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner dimensions so one can compute `np.dot(u * s, v)`. v : ndarray Parameters u and v are the output of `linalg.svd` or :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner dimensions so one can compute `np.dot(u * s, v)`. The input v should really be called vt to be consistent with scipy's output. u_based_decision : bool, default=True If True, use the columns of u as the basis for sign flipping. Otherwise, use the rows of v. The choice of which variable to base the decision on is generally algorithm dependent. Returns ------- u_adjusted : ndarray Array u with adjusted columns and the same dimensions as u. v_adjusted : ndarray Array v with adjusted rows and the same dimensions as v. """ if u_based_decision: # columns of u, rows of v max_abs_cols = np.argmax(np.abs(u), axis=0) signs = np.sign(u[max_abs_cols, range(u.shape[1])]) u *= signs v *= signs[:, np.newaxis] else: # rows of v, columns of u max_abs_rows = np.argmax(np.abs(v), axis=1) signs = np.sign(v[range(v.shape[0]), max_abs_rows]) u *= signs v *= signs[:, np.newaxis] return u, v def log_logistic(X, out=None): """Compute the log of the logistic function, ``log(1 / (1 + e ** -x))``. This implementation is numerically stable because it splits positive and negative values:: -log(1 + exp(-x_i)) if x_i > 0 x_i - log(1 + exp(x_i)) if x_i <= 0 For the ordinary logistic function, use ``scipy.special.expit``. Parameters ---------- X : array-like of shape (M, N) or (M,) Argument to the logistic function. out : array-like of shape (M, N) or (M,), default=None Preallocated output array. Returns ------- out : ndarray of shape (M, N) or (M,) Log of the logistic function evaluated at every point in x. Notes ----- See the blog post describing this implementation: http://fa.bianp.net/blog/2013/numerical-optimizers-for-logistic-regression/ """ is_1d = X.ndim == 1 X = np.atleast_2d(X) X = check_array(X, dtype=np.float64) n_samples, n_features = X.shape if out is None: out = np.empty_like(X) _log_logistic_sigmoid(n_samples, n_features, X, out) if is_1d: return np.squeeze(out) return out def softmax(X, copy=True): """ Calculate the softmax function. The softmax function is calculated by np.exp(X) / np.sum(np.exp(X), axis=1) This will cause overflow when large values are exponentiated. Hence the largest value in each row is subtracted from each data point to prevent this. Parameters ---------- X : array-like of float of shape (M, N) Argument to the logistic function. copy : bool, default=True Copy X or not. Returns ------- out : ndarray of shape (M, N) Softmax function evaluated at every point in x. """ xp, is_array_api_compliant = get_namespace(X) if copy: X = xp.asarray(X, copy=True) max_prob = xp.reshape(xp.max(X, axis=1), (-1, 1)) X -= max_prob
""" Extended math utilities. """ # Authors: Gael Varoquaux # Alexandre Gramfort # Alexandre T. Passos # Olivier Grisel # Lars Buitinck # Stefan van der Walt # Kyle Kastner # Giorgio Patrini # License: BSD 3 clause def squared_norm(x): """Squared Euclidean or Frobenius norm of x. Faster than norm(x) ** 2. Parameters ---------- x : array-like The input array which could be either be a vector or a 2 dimensional array. Returns ------- float The Euclidean norm when x is a vector, the Frobenius norm when x is a matrix (2-d array). """ x = np.ravel(x, order="K") if np.issubdtype(x.dtype, np.integer): warnings.warn( ( "Array type is integer, np.dot may overflow. " "Data should be float type to avoid this issue" ), UserWarning, ) return np.dot(x, x) def row_norms(X, squared=False): """Row-wise (squared) Euclidean norm of X. Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse matrices and does not create an X.shape-sized temporary. Performs no input validation. Parameters ---------- X : array-like The input array. squared : bool, default=False If True, return squared norms. Returns ------- array-like The row-wise (squared) Euclidean norm of X. """ if sparse.issparse(X): X = X.tocsr() norms = csr_row_norms(X) else: norms = np.einsum("ij,ij->i", X, X) if not squared: np.sqrt(norms, norms) return norms def fast_logdet(A): """Compute logarithm of determinant of a square matrix. The (natural) logarithm of the determinant of a square matrix is returned if det(A) is non-negative and well defined. If the determinant is zero or negative returns -Inf. Equivalent to : np.log(np.det(A)) but more robust. Parameters ---------- A : array_like of shape (n, n) The square matrix. Returns ------- logdet : float When det(A) is strictly positive, log(det(A)) is returned. When det(A) is non-positive or not defined, then -inf is returned. See Also -------- numpy.linalg.slogdet : Compute the sign and (natural) logarithm of the determinant of an array. Examples -------- >>> import numpy as np >>> from sklearn.utils.extmath import fast_logdet >>> a = np.array([[5, 1], [2, 8]]) >>> fast_logdet(a) 3.6375861597263857 """ sign, ld = np.linalg.slogdet(A) if not sign > 0: return -np.inf return ld def density(w, **kwargs): """Compute density of a sparse vector. Parameters ---------- w : array-like The sparse vector. **kwargs : keyword arguments Ignored. .. deprecated:: 1.2 ``**kwargs`` were deprecated in version 1.2 and will be removed in 1.4. Returns ------- float The density of w, between 0 and 1. """ if kwargs: warnings.warn( ( "Additional keyword arguments are deprecated in version 1.2 and will be" " removed in version 1.4." ), FutureWarning, ) if hasattr(w, "toarray"): d = float(w.nnz) / (w.shape[0] * w.shape[1]) else: d = 0 if w is None else float((w != 0).sum()) / w.size return d def safe_sparse_dot(a, b, *, dense_output=False): """Dot product that handle the sparse matrix case correctly. Parameters ---------- a : {ndarray, sparse matrix} b : {ndarray, sparse matrix} dense_output : bool, default=False When False, ``a`` and ``b`` both being sparse will yield sparse output. When True, output will always be a dense array. Returns ------- dot_product : {ndarray, sparse matrix} Sparse if ``a`` and ``b`` are sparse and ``dense_output=False``. """ if a.ndim > 2 or b.ndim > 2: if sparse.issparse(a): # sparse is always 2D. Implies b is 3D+ # [i, j] @ [k, ..., l, m, n] -> [i, k, ..., l, n] b_ = np.rollaxis(b, -2) b_2d = b_.reshape((b.shape[-2], -1)) ret = a @ b_2d ret = ret.reshape(a.shape[0], *b_.shape[1:]) elif sparse.issparse(b): # sparse is always 2D. Implies a is 3D+ # [k, ..., l, m] @ [i, j] -> [k, ..., l, j] a_2d = a.reshape(-1, a.shape[-1]) ret = a_2d @ b ret = ret.reshape(*a.shape[:-1], b.shape[1]) else: ret = np.dot(a, b) else: ret = a @ b if ( sparse.issparse(a) and sparse.issparse(b) and dense_output and hasattr(ret, "toarray") ): return ret.toarray() return ret def randomized_range_finder( A, *, size, n_iter, power_iteration_normalizer="auto", random_state=None ): """Compute an orthonormal matrix whose range approximates the range of A. Parameters ---------- A : 2D array The input data matrix. size : int Size of the return array. n_iter : int Number of power iterations used to stabilize the result. power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' Whether the power iterations are normalized with step-by-step QR factorization (the slowest but most accurate), 'none' (the fastest but numerically unstable when `n_iter` is large, e.g. typically 5 or larger), or 'LU' factorization (numerically stable but can lose slightly in accuracy). The 'auto' mode applies no normalization if `n_iter` <= 2 and switches to LU otherwise. .. versionadded:: 0.18 random_state : int, RandomState instance or None, default=None The seed of the pseudo random number generator to use when shuffling the data, i.e. getting the random vectors to initialize the algorithm. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. Returns ------- Q : ndarray A (size x size) projection matrix, the range of which approximates well the range of the input matrix A. Notes ----- Follows Algorithm 4.3 of :arxiv:`"Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions" <0909.4061>` Halko, et al. (2009) An implementation of a randomized algorithm for principal component analysis A. Szlam et al. 2014 """ random_state = check_random_state(random_state) # Generating normal random vectors with shape: (A.shape[1], size) Q = random_state.normal(size=(A.shape[1], size)) if hasattr(A, "dtype") and A.dtype.kind == "f": # Ensure f32 is preserved as f32 Q = Q.astype(A.dtype, copy=False) # Deal with "auto" mode if power_iteration_normalizer == "auto": if n_iter <= 2: power_iteration_normalizer = "none" else: power_iteration_normalizer = "LU" # Perform power iterations with Q to further 'imprint' the top # singular vectors of A in Q for i in range(n_iter): if power_iteration_normalizer == "none": Q = safe_sparse_dot(A, Q) Q = safe_sparse_dot(A.T, Q) elif power_iteration_normalizer == "LU": Q, _ = linalg.lu(safe_sparse_dot(A, Q), permute_l=True) Q, _ = linalg.lu(safe_sparse_dot(A.T, Q), permute_l=True) elif power_iteration_normalizer == "QR": Q, _ = linalg.qr(safe_sparse_dot(A, Q), mode="economic") Q, _ = linalg.qr(safe_sparse_dot(A.T, Q), mode="economic") # Sample the range of A using by linear projection of Q # Extract an orthonormal basis Q, _ = linalg.qr(safe_sparse_dot(A, Q), mode="economic") return Q def randomized_svd( M, n_components, *, n_oversamples=10, n_iter="auto", power_iteration_normalizer="auto", transpose="auto", flip_sign=True, random_state=None, svd_lapack_driver="gesdd", ): """Compute a truncated randomized SVD. This method solves the fixed-rank approximation problem described in [1]_ (problem (1.5), p5). Parameters ---------- M : {ndarray, sparse matrix} Matrix to decompose. n_components : int Number of singular values and vectors to extract. n_oversamples : int, default=10 Additional number of random vectors to sample the range of M so as to ensure proper conditioning. The total number of random vectors used to find the range of M is n_components + n_oversamples. Smaller number can improve speed but can negatively impact the quality of approximation of singular vectors and singular values. Users might wish to increase this parameter up to `2*k - n_components` where k is the effective rank, for large matrices, noisy problems, matrices with slowly decaying spectrums, or to increase precision accuracy. See [1]_ (pages 5, 23 and 26). n_iter : int or 'auto', default='auto' Number of power iterations. It can be used to deal with very noisy problems. When 'auto', it is set to 4, unless `n_components` is small (< .1 * min(X.shape)) in which case `n_iter` is set to 7. This improves precision with few components. Note that in general users should rather increase `n_oversamples` before increasing `n_iter` as the principle of the randomized method is to avoid usage of these more costly power iterations steps. When `n_components` is equal or greater to the effective matrix rank and the spectrum does not present a slow decay, `n_iter=0` or `1` should even work fine in theory (see [1]_ page 9). .. versionchanged:: 0.18 power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' Whether the power iterations are normalized with step-by-step QR factorization (the slowest but most accurate), 'none' (the fastest but numerically unstable when `n_iter` is large, e.g. typically 5 or larger), or 'LU' factorization (numerically stable but can lose slightly in accuracy). The 'auto' mode applies no normalization if `n_iter` <= 2 and switches to LU otherwise. .. versionadded:: 0.18 transpose : bool or 'auto', default='auto' Whether the algorithm should be applied to M.T instead of M. The result should approximately be the same. The 'auto' mode will trigger the transposition if M.shape[1] > M.shape[0] since this implementation of randomized SVD tend to be a little faster in that case. .. versionchanged:: 0.18 flip_sign : bool, default=True The output of a singular value decomposition is only unique up to a permutation of the signs of the singular vectors. If `flip_sign` is set to `True`, the sign ambiguity is resolved by making the largest loadings for each component in the left singular vectors positive. random_state : int, RandomState instance or None, default='warn' The seed of the pseudo random number generator to use when shuffling the data, i.e. getting the random vectors to initialize the algorithm. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. .. versionchanged:: 1.2 The default value changed from 0 to None. svd_lapack_driver : {"gesdd", "gesvd"}, default="gesdd" Whether to use the more efficient divide-and-conquer approach (`"gesdd"`) or more general rectangular approach (`"gesvd"`) to compute the SVD of the matrix B, which is the projection of M into a low dimensional subspace, as described in [1]_. .. versionadded:: 1.2 Returns ------- u : ndarray of shape (n_samples, n_components) Unitary matrix having left singular vectors with signs flipped as columns. s : ndarray of shape (n_components,) The singular values, sorted in non-increasing order. vh : ndarray of shape (n_components, n_features) Unitary matrix having right singular vectors with signs flipped as rows. Notes ----- This algorithm finds a (usually very good) approximate truncated singular value decomposition using randomization to speed up the computations. It is particularly fast on large matrices on which you wish to extract only a small number of components. In order to obtain further speed up, `n_iter` can be set <=2 (at the cost of loss of precision). To increase the precision it is recommended to increase `n_oversamples`, up to `2*k-n_components` where k is the effective rank. Usually, `n_components` is chosen to be greater than k so increasing `n_oversamples` up to `n_components` should be enough. References ---------- .. [1] :arxiv:`"Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions" <0909.4061>` Halko, et al. (2009) .. [2] A randomized algorithm for the decomposition of matrices Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert .. [3] An implementation of a randomized algorithm for principal component analysis A. Szlam et al. 2014 Examples -------- >>> import numpy as np >>> from sklearn.utils.extmath import randomized_svd >>> a = np.array([[1, 2, 3, 5], ... [3, 4, 5, 6], ... [7, 8, 9, 10]]) >>> U, s, Vh = randomized_svd(a, n_components=2, random_state=0) >>> U.shape, s.shape, Vh.shape ((3, 2), (2,), (2, 4)) """ if sparse.issparse(M) and M.format in ("lil", "dok"): warnings.warn( "Calculating SVD of a {} is expensive. " "csr_matrix is more efficient.".format(type(M).__name__), sparse.SparseEfficiencyWarning, ) random_state = check_random_state(random_state) n_random = n_components + n_oversamples n_samples, n_features = M.shape if n_iter == "auto": # Checks if the number of iterations is explicitly specified # Adjust n_iter. 7 was found a good compromise for PCA. See #5299 n_iter = 7 if n_components < 0.1 * min(M.shape) else 4 if transpose == "auto": transpose = n_samples < n_features if transpose: # this implementation is a bit faster with smaller shape[1] M = M.T Q = randomized_range_finder( M, size=n_random, n_iter=n_iter, power_iteration_normalizer=power_iteration_normalizer, random_state=random_state, ) # project M to the (k + p) dimensional space using the basis vectors B = safe_sparse_dot(Q.T, M) # compute the SVD on the thin matrix: (k + p) wide Uhat, s, Vt = linalg.svd(B, full_matrices=False, lapack_driver=svd_lapack_driver) del B U = np.dot(Q, Uhat) if flip_sign: if not transpose: U, Vt = svd_flip(U, Vt) else: # In case of transpose u_based_decision=false # to actually flip based on u and not v. U, Vt = svd_flip(U, Vt, u_based_decision=False) if transpose: # transpose back the results according to the input convention return Vt[:n_components, :].T, s[:n_components], U[:, :n_components].T else: return U[:, :n_components], s[:n_components], Vt[:n_components, :] def _randomized_eigsh( M, n_components, *, n_oversamples=10, n_iter="auto", power_iteration_normalizer="auto", selection="module", random_state=None, ): """Computes a truncated eigendecomposition using randomized methods This method solves the fixed-rank approximation problem described in the Halko et al paper. The choice of which components to select can be tuned with the `selection` parameter. .. versionadded:: 0.24 Parameters ---------- M : ndarray or sparse matrix Matrix to decompose, it should be real symmetric square or complex hermitian n_components : int Number of eigenvalues and vectors to extract. n_oversamples : int, default=10 Additional number of random vectors to sample the range of M so as to ensure proper conditioning. The total number of random vectors used to find the range of M is n_components + n_oversamples. Smaller number can improve speed but can negatively impact the quality of approximation of eigenvectors and eigenvalues. Users might wish to increase this parameter up to `2*k - n_components` where k is the effective rank, for large matrices, noisy problems, matrices with slowly decaying spectrums, or to increase precision accuracy. See Halko et al (pages 5, 23 and 26). n_iter : int or 'auto', default='auto' Number of power iterations. It can be used to deal with very noisy problems. When 'auto', it is set to 4, unless `n_components` is small (< .1 * min(X.shape)) in which case `n_iter` is set to 7. This improves precision with few components. Note that in general users should rather increase `n_oversamples` before increasing `n_iter` as the principle of the randomized method is to avoid usage of these more costly power iterations steps. When `n_components` is equal or greater to the effective matrix rank and the spectrum does not present a slow decay, `n_iter=0` or `1` should even work fine in theory (see Halko et al paper, page 9). power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto' Whether the power iterations are normalized with step-by-step QR factorization (the slowest but most accurate), 'none' (the fastest but numerically unstable when `n_iter` is large, e.g. typically 5 or larger), or 'LU' factorization (numerically stable but can lose slightly in accuracy). The 'auto' mode applies no normalization if `n_iter` <= 2 and switches to LU otherwise. selection : {'value', 'module'}, default='module' Strategy used to select the n components. When `selection` is `'value'` (not yet implemented, will become the default when implemented), the components corresponding to the n largest eigenvalues are returned. When `selection` is `'module'`, the components corresponding to the n eigenvalues with largest modules are returned. random_state : int, RandomState instance, default=None The seed of the pseudo random number generator to use when shuffling the data, i.e. getting the random vectors to initialize the algorithm. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. Notes ----- This algorithm finds a (usually very good) approximate truncated eigendecomposition using randomized methods to speed up the computations. This method is particularly fast on large matrices on which you wish to extract only a small number of components. In order to obtain further speed up, `n_iter` can be set <=2 (at the cost of loss of precision). To increase the precision it is recommended to increase `n_oversamples`, up to `2*k-n_components` where k is the effective rank. Usually, `n_components` is chosen to be greater than k so increasing `n_oversamples` up to `n_components` should be enough. Strategy 'value': not implemented yet. Algorithms 5.3, 5.4 and 5.5 in the Halko et al paper should provide good candidates for a future implementation. Strategy 'module': The principle is that for diagonalizable matrices, the singular values and eigenvalues are related: if t is an eigenvalue of A, then :math:`|t|` is a singular value of A. This method relies on a randomized SVD to find the n singular components corresponding to the n singular values with largest modules, and then uses the signs of the singular vectors to find the true sign of t: if the sign of left and right singular vectors are different then the corresponding eigenvalue is negative. Returns ------- eigvals : 1D array of shape (n_components,) containing the `n_components` eigenvalues selected (see ``selection`` parameter). eigvecs : 2D array of shape (M.shape[0], n_components) containing the `n_components` eigenvectors corresponding to the `eigvals`, in the corresponding order. Note that this follows the `scipy.linalg.eigh` convention. See Also -------- :func:`randomized_svd` References ---------- * :arxiv:`"Finding structure with randomness: Stochastic algorithms for constructing approximate matrix decompositions" (Algorithm 4.3 for strategy 'module') <0909.4061>` Halko, et al. (2009) """ if selection == "value": # pragma: no cover # to do : an algorithm can be found in the Halko et al reference raise NotImplementedError() elif selection == "module": # Note: no need for deterministic U and Vt (flip_sign=True), # as we only use the dot product UVt afterwards U, S, Vt = randomized_svd( M, n_components=n_components, n_oversamples=n_oversamples, n_iter=n_iter, power_iteration_normalizer=power_iteration_normalizer, flip_sign=False, random_state=random_state, ) eigvecs = U[:, :n_components] eigvals = S[:n_components] # Conversion of Singular values into Eigenvalues: # For any eigenvalue t, the corresponding singular value is |t|. # So if there is a negative eigenvalue t, the corresponding singular # value will be -t, and the left (U) and right (V) singular vectors # will have opposite signs. # Fastest way: see <https://stackoverflow.com/a/61974002/7262247> diag_VtU = np.einsum("ji,ij->j", Vt[:n_components, :], U[:, :n_components]) signs = np.sign(diag_VtU) eigvals = eigvals * signs else: # pragma: no cover raise ValueError("Invalid `selection`: %r" % selection) return eigvals, eigvecs def weighted_mode(a, w, *, axis=0): """Return an array of the weighted modal (most common) value in the passed array. If there is more than one such value, only the first is returned. The bin-count for the modal bins is also returned. This is an extension of the algorithm in scipy.stats.mode. Parameters ---------- a : array-like of shape (n_samples,) Array of which values to find mode(s). w : array-like of shape (n_samples,) Array of weights for each value. axis : int, default=0 Axis along which to operate. Default is 0, i.e. the first axis. Returns ------- vals : ndarray Array of modal values. score : ndarray Array of weighted counts for each mode. See Also -------- scipy.stats.mode: Calculates the Modal (most common) value of array elements along specified axis. Examples -------- >>> from sklearn.utils.extmath import weighted_mode >>> x = [4, 1, 4, 2, 4, 2] >>> weights = [1, 1, 1, 1, 1, 1] >>> weighted_mode(x, weights) (array([4.]), array([3.])) The value 4 appears three times: with uniform weights, the result is simply the mode of the distribution. >>> weights = [1, 3, 0.5, 1.5, 1, 2] # deweight the 4's >>> weighted_mode(x, weights) (array([2.]), array([3.5])) The value 2 has the highest score: it appears twice with weights of 1.5 and 2: the sum of these is 3.5. """ if axis is None: a = np.ravel(a) w = np.ravel(w) axis = 0 else: a = np.asarray(a) w = np.asarray(w) if a.shape != w.shape: w = np.full(a.shape, w, dtype=w.dtype) scores = np.unique(np.ravel(a)) # get ALL unique values testshape = list(a.shape) testshape[axis] = 1 oldmostfreq = np.zeros(testshape) oldcounts = np.zeros(testshape) for score in scores: template = np.zeros(a.shape) ind = a == score template[ind] = w[ind] counts = np.expand_dims(np.sum(template, axis), axis) mostfrequent = np.where(counts > oldcounts, score, oldmostfreq) oldcounts = np.maximum(counts, oldcounts) oldmostfreq = mostfrequent return mostfrequent, oldcounts def cartesian(arrays, out=None): """Generate a cartesian product of input arrays. Parameters ---------- arrays : list of array-like 1-D arrays to form the cartesian product of. out : ndarray of shape (M, len(arrays)), default=None Array to place the cartesian product in. Returns ------- out : ndarray of shape (M, len(arrays)) Array containing the cartesian products formed of input arrays. If not provided, the `dtype` of the output array is set to the most permissive `dtype` of the input arrays, according to NumPy type promotion. .. versionadded:: 1.2 Add support for arrays of different types. Notes ----- This function may not be used on more than 32 arrays because the underlying numpy functions do not support it. Examples -------- >>> from sklearn.utils.extmath import cartesian >>> cartesian(([1, 2, 3], [4, 5], [6, 7])) array([[1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7], [3, 4, 6], [3, 4, 7], [3, 5, 6], [3, 5, 7]]) """ arrays = [np.asarray(x) for x in arrays] shape = (len(x) for x in arrays) ix = np.indices(shape) ix = ix.reshape(len(arrays), -1).T if out is None: dtype = np.result_type(*arrays) # find the most permissive dtype out = np.empty_like(ix, dtype=dtype) for n, arr in enumerate(arrays): out[:, n] = arrays[n][ix[:, n]] return out def svd_flip(u, v, u_based_decision=True): """Sign correction to ensure deterministic output from SVD. Adjusts the columns of u and the rows of v such that the loadings in the columns in u that are largest in absolute value are always positive. Parameters ---------- u : ndarray Parameters u and v are the output of `linalg.svd` or :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner dimensions so one can compute `np.dot(u * s, v)`. v : ndarray Parameters u and v are the output of `linalg.svd` or :func:`~sklearn.utils.extmath.randomized_svd`, with matching inner dimensions so one can compute `np.dot(u * s, v)`. The input v should really be called vt to be consistent with scipy's output. u_based_decision : bool, default=True If True, use the columns of u as the basis for sign flipping. Otherwise, use the rows of v. The choice of which variable to base the decision on is generally algorithm dependent. Returns ------- u_adjusted : ndarray Array u with adjusted columns and the same dimensions as u. v_adjusted : ndarray Array v with adjusted rows and the same dimensions as v. """ if u_based_decision: # columns of u, rows of v max_abs_cols = np.argmax(np.abs(u), axis=0) signs = np.sign(u[max_abs_cols, range(u.shape[1])]) u *= signs v *= signs[:, np.newaxis] else: # rows of v, columns of u max_abs_rows = np.argmax(np.abs(v), axis=1) signs = np.sign(v[range(v.shape[0]), max_abs_rows]) u *= signs v *= signs[:, np.newaxis] return u, v def log_logistic(X, out=None): """Compute the log of the logistic function, ``log(1 / (1 + e ** -x))``. This implementation is numerically stable because it splits positive and negative values:: -log(1 + exp(-x_i)) if x_i > 0 x_i - log(1 + exp(x_i)) if x_i <= 0 For the ordinary logistic function, use ``scipy.special.expit``. Parameters ---------- X : array-like of shape (M, N) or (M,) Argument to the logistic function. out : array-like of shape (M, N) or (M,), default=None Preallocated output array. Returns ------- out : ndarray of shape (M, N) or (M,) Log of the logistic function evaluated at every point in x. Notes ----- See the blog post describing this implementation: http://fa.bianp.net/blog/2013/numerical-optimizers-for-logistic-regression/ """ is_1d = X.ndim == 1 X = np.atleast_2d(X) X = check_array(X, dtype=np.float64) n_samples, n_features = X.shape if out is None: out = np.empty_like(X) _log_logistic_sigmoid(n_samples, n_features, X, out) if is_1d: return np.squeeze(out) return out def softmax(X, copy=True): """ Calculate the softmax function. The softmax function is calculated by np.exp(X) / np.sum(np.exp(X), axis=1) This will cause overflow when large values are exponentiated. Hence the largest value in each row is subtracted from each data point to prevent this. Parameters ---------- X : array-like of float of shape (M, N) Argument to the logistic function. copy : bool, default=True Copy X or not. Returns ------- out : ndarray of shape (M, N) Softmax function evaluated at every point in x. """ xp, is_array_api_compliant = get_namespace(X) if copy: X = xp.asarray(X, copy=True) max_prob = xp.reshape(xp.max(X, axis=1), (-1, 1)) X -= max_prob
if _is_numpy_namespace(xp):
1
2023-10-07 13:19:48+00:00
8k
brevia-ai/brevia
brevia/routers/qa_router.py
[ { "identifier": "chat_history", "path": "brevia/chat_history.py", "snippet": "class ChatHistoryStore(BaseModel):\nclass ChatHistoryFilter(PydanticModel):\ndef history(chat_history: list, session: str = None):\ndef is_related(chat_history: list, question: str):\ndef dot_product(v1_list, v2_list):\ndef hi...
from typing import Annotated from langchain.callbacks import AsyncIteratorCallbackHandler from langchain.chains.base import Chain from fastapi import APIRouter, Header from fastapi.responses import StreamingResponse from brevia import chat_history from brevia.dependencies import ( get_dependencies, check_collection_name, ) from brevia.callback import ( ConversationCallbackHandler, token_usage_callback, token_usage, TokensCallbackHandler, ) from brevia.language import Detector from brevia.query import SearchQuery, ChatParams, conversation_chain, search_vector_qa from brevia.models import test_models_in_use import asyncio
3,861
class ChatBody(ChatParams): """ /chat request body """ question: str collection: str chat_history: list = [] chat_lang: str | None = None token_data: bool = False @router.post('/prompt', dependencies=get_dependencies(), deprecated=True, tags=['Chat']) @router.post('/chat', dependencies=get_dependencies(), tags=['Chat']) async def chat_action( chat_body: ChatBody, x_chat_session: Annotated[str | None, Header()] = None, ): """ /chat endpoint, ask chatbot about a collection of documents """ collection = check_collection_name(chat_body.collection) if not collection.cmetadata: collection.cmetadata = {} lang = chat_language(chat_body=chat_body, cmetadata=collection.cmetadata) conversation_handler = ConversationCallbackHandler() stream_handler = AsyncIteratorCallbackHandler() chain = conversation_chain( collection=collection, chat_params=ChatParams(**chat_body.model_dump()), answer_callbacks=[stream_handler] if chat_body.streaming else [], conversation_callbacks=[conversation_handler] ) if not chat_body.streaming or test_models_in_use(): return await run_chain( chain=chain, chat_body=chat_body, lang=lang, x_chat_session=x_chat_session, ) asyncio.create_task(run_chain( chain=chain, chat_body=chat_body, lang=lang, x_chat_session=x_chat_session, )) async def event_generator( stream_callback: AsyncIteratorCallbackHandler, conversation_callback: ConversationCallbackHandler, source_docs: bool = False, ): ait = stream_callback.aiter() async for token in ait: yield token if not source_docs: yield '' else: await conversation_callback.wait_conversation_done() yield conversation_callback.chain_result() return StreamingResponse(event_generator( stream_callback=stream_handler, conversation_callback=conversation_handler, source_docs=chat_body.source_docs, )) def chat_language(chat_body: ChatBody, cmetadata: dict) -> str: """Retrieve the language to be used in Q/A response""" chat_lang = chat_body.chat_lang or cmetadata.get('chat_lang') if chat_lang: return chat_lang return Detector().detect(chat_body.question) def retrieve_chat_history(history: list, question: str, session: str = None) -> list: """Retrieve chat history to be used in final prompt creation""" chat_hist = chat_history.history( chat_history=history, session=session, ) if chat_hist and not chat_history.is_related(chat_hist, question): chat_hist = [] return chat_hist async def run_chain( chain: Chain, chat_body: ChatBody, lang: str, x_chat_session: str, ): """Run chain usign async methods and return result""" with token_usage_callback() as callb: result = await chain.acall({ 'question': chat_body.question, 'chat_history': retrieve_chat_history( history=chat_body.chat_history, question=chat_body.question, session=x_chat_session, ), 'lang': lang, }) return chat_result( result=result, callb=callb, chat_body=chat_body, x_chat_session=x_chat_session ) def chat_result( result: dict,
"""API endpoints for question answering and search""" router = APIRouter() class ChatBody(ChatParams): """ /chat request body """ question: str collection: str chat_history: list = [] chat_lang: str | None = None token_data: bool = False @router.post('/prompt', dependencies=get_dependencies(), deprecated=True, tags=['Chat']) @router.post('/chat', dependencies=get_dependencies(), tags=['Chat']) async def chat_action( chat_body: ChatBody, x_chat_session: Annotated[str | None, Header()] = None, ): """ /chat endpoint, ask chatbot about a collection of documents """ collection = check_collection_name(chat_body.collection) if not collection.cmetadata: collection.cmetadata = {} lang = chat_language(chat_body=chat_body, cmetadata=collection.cmetadata) conversation_handler = ConversationCallbackHandler() stream_handler = AsyncIteratorCallbackHandler() chain = conversation_chain( collection=collection, chat_params=ChatParams(**chat_body.model_dump()), answer_callbacks=[stream_handler] if chat_body.streaming else [], conversation_callbacks=[conversation_handler] ) if not chat_body.streaming or test_models_in_use(): return await run_chain( chain=chain, chat_body=chat_body, lang=lang, x_chat_session=x_chat_session, ) asyncio.create_task(run_chain( chain=chain, chat_body=chat_body, lang=lang, x_chat_session=x_chat_session, )) async def event_generator( stream_callback: AsyncIteratorCallbackHandler, conversation_callback: ConversationCallbackHandler, source_docs: bool = False, ): ait = stream_callback.aiter() async for token in ait: yield token if not source_docs: yield '' else: await conversation_callback.wait_conversation_done() yield conversation_callback.chain_result() return StreamingResponse(event_generator( stream_callback=stream_handler, conversation_callback=conversation_handler, source_docs=chat_body.source_docs, )) def chat_language(chat_body: ChatBody, cmetadata: dict) -> str: """Retrieve the language to be used in Q/A response""" chat_lang = chat_body.chat_lang or cmetadata.get('chat_lang') if chat_lang: return chat_lang return Detector().detect(chat_body.question) def retrieve_chat_history(history: list, question: str, session: str = None) -> list: """Retrieve chat history to be used in final prompt creation""" chat_hist = chat_history.history( chat_history=history, session=session, ) if chat_hist and not chat_history.is_related(chat_hist, question): chat_hist = [] return chat_hist async def run_chain( chain: Chain, chat_body: ChatBody, lang: str, x_chat_session: str, ): """Run chain usign async methods and return result""" with token_usage_callback() as callb: result = await chain.acall({ 'question': chat_body.question, 'chat_history': retrieve_chat_history( history=chat_body.chat_history, question=chat_body.question, session=x_chat_session, ), 'lang': lang, }) return chat_result( result=result, callb=callb, chat_body=chat_body, x_chat_session=x_chat_session ) def chat_result( result: dict,
callb: TokensCallbackHandler,
3
2023-10-10 15:54:55+00:00
8k
arifogluisa/django-dockerizer
django_dockerizer/dockerizer.py
[ { "identifier": "CELERY", "path": "django_dockerizer/contents.py", "snippet": "CELERY = f\"\"\"from __future__ import absolute_import, unicode_literals\n\nimport logging\nimport os\n\nfrom django.conf import settings\nfrom celery import Celery\n\nlogger = logging.getLogger(\"Celery\")\n\nos.environ.setd...
import argparse import os import subprocess from .contents import ( CELERY, DEV_ENV, DEV_ENV_WITH_CELERY, DOCKER_COMPOSE_DEV, DOCKER_COMPOSE_PROD, DOCKER_COMPOSE_WITH_CELERY_DEV, DOCKER_COMPOSE_WITH_CELERY_PROD, DOCKERFILE_DEV, DOCKERFILE_PROD, ENV_TYPES, NGINX_CONF, PROD_ENV, PROD_ENV_WITH_CELERY, REDIS_DOCKERFILE, SINGLE_FILES, ) from .utils import BASE_DIR, create_celery_file
3,686
def parse_arguments(): parser = argparse.ArgumentParser(description="Django Dockerizer Tool") parser.add_argument( "--celery", help="Include Celery configurations", action="store_true" ) # parser.add_argument("--redis", help="Include Redis configurations", action="store_true") return parser.parse_args() args = parse_arguments() def create_directory_structure(): os.makedirs(os.path.join(BASE_DIR, "bin/dev"), exist_ok=True) os.makedirs(os.path.join(BASE_DIR, "bin/prod"), exist_ok=True) def generate_docker_files(env_type): content = DOCKERFILE_DEV if env_type == "dev" else DOCKERFILE_PROD with open(os.path.join(BASE_DIR, "bin", env_type, "Dockerfile"), "w") as file: file.write(content) if args.celery and env_type == "prod": with open( os.path.join(BASE_DIR, "bin", env_type, "redis.dockerfile"), "w" ) as file: file.write(REDIS_DOCKERFILE) def generate_single_files(): """ Generating uwsgi.ini, mime.types and nginx.conf files """ for file_name, content in SINGLE_FILES: with open(os.path.join(BASE_DIR, "bin", "prod", file_name), "w") as file: file.write(content) with open(os.path.join(BASE_DIR, "bin", "nginx.conf"), "w") as file: file.write(NGINX_CONF) def generate_env_files(env_type): if args.celery: content = DEV_ENV_WITH_CELERY if env_type == "dev" else PROD_ENV_WITH_CELERY else: content = DEV_ENV if env_type == "dev" else PROD_ENV with open(os.path.join(BASE_DIR, "bin", env_type, ".env"), "w") as file: file.write(content) def generate_docker_compose_files(env_type): if args.celery: content = ( DOCKER_COMPOSE_WITH_CELERY_DEV if env_type == "dev"
def parse_arguments(): parser = argparse.ArgumentParser(description="Django Dockerizer Tool") parser.add_argument( "--celery", help="Include Celery configurations", action="store_true" ) # parser.add_argument("--redis", help="Include Redis configurations", action="store_true") return parser.parse_args() args = parse_arguments() def create_directory_structure(): os.makedirs(os.path.join(BASE_DIR, "bin/dev"), exist_ok=True) os.makedirs(os.path.join(BASE_DIR, "bin/prod"), exist_ok=True) def generate_docker_files(env_type): content = DOCKERFILE_DEV if env_type == "dev" else DOCKERFILE_PROD with open(os.path.join(BASE_DIR, "bin", env_type, "Dockerfile"), "w") as file: file.write(content) if args.celery and env_type == "prod": with open( os.path.join(BASE_DIR, "bin", env_type, "redis.dockerfile"), "w" ) as file: file.write(REDIS_DOCKERFILE) def generate_single_files(): """ Generating uwsgi.ini, mime.types and nginx.conf files """ for file_name, content in SINGLE_FILES: with open(os.path.join(BASE_DIR, "bin", "prod", file_name), "w") as file: file.write(content) with open(os.path.join(BASE_DIR, "bin", "nginx.conf"), "w") as file: file.write(NGINX_CONF) def generate_env_files(env_type): if args.celery: content = DEV_ENV_WITH_CELERY if env_type == "dev" else PROD_ENV_WITH_CELERY else: content = DEV_ENV if env_type == "dev" else PROD_ENV with open(os.path.join(BASE_DIR, "bin", env_type, ".env"), "w") as file: file.write(content) def generate_docker_compose_files(env_type): if args.celery: content = ( DOCKER_COMPOSE_WITH_CELERY_DEV if env_type == "dev"
else DOCKER_COMPOSE_WITH_CELERY_PROD
6
2023-10-09 10:41:22+00:00
8k
HICAI-ZJU/iMoLD
run.py
[ { "identifier": "args_parser", "path": "args_parse.py", "snippet": "def args_parser():\n parser = argparse.ArgumentParser()\n # exp\n parser.add_argument(\"--exp_name\", default=\"run\", type=str,\n help=\"Experiment name\")\n parser.add_argument(\"--dump_path\", defau...
import os import logging import torch import torch.nn.functional as F import numpy as np from tqdm import tqdm from munch import Munch, munchify from torch.utils.tensorboard import SummaryWriter from torch_geometric.loader import DataLoader from GOOD import register from GOOD.utils.config_reader import load_config from GOOD.utils.metric import Metric from GOOD.data.dataset_manager import read_meta_info from GOOD.utils.evaluation import eval_data_preprocess, eval_score from GOOD.utils.train import nan2zero_get_mask from args_parse import args_parser from exputils import initialize_exp, set_seed, get_dump_path, describe_model, save_model, load_model from models import MyModel from dataset import DrugOODDataset
4,533
self.metric = Metric() self.metric.set_score_func(dataset['metric'] if type(dataset) is dict else getattr(dataset, 'metric')) self.metric.set_loss_func(dataset['task'] if type(dataset) is dict else getattr(dataset, 'task')) cfg.metric = self.metric else: # DrugOOD dataset = DrugOODDataset(name=args.dataset, root=args.data_root) self.train_set = dataset[dataset.train_index] self.valid_set = dataset[dataset.valid_index] self.test_set = dataset[dataset.test_index] self.train_loader = DataLoader(self.train_set, batch_size=args.bs, shuffle=True, drop_last=True) self.valid_loader = DataLoader(self.valid_set, batch_size=args.bs, shuffle=False) self.test_loader = DataLoader(self.test_set, batch_size=args.bs, shuffle=False) self.metric = Metric() self.metric.set_loss_func(task_name='Binary classification') self.metric.set_score_func(metric_name='ROC-AUC') cfg = Munch() cfg.metric = self.metric cfg.model = Munch() cfg.model.model_level = 'graph' self.model = MyModel(args=args, config=cfg).to(self.device) self.opt = torch.optim.Adam(self.model.parameters(), lr=args.lr) self.total_step = 0 self.writer = writer describe_model(self.model, path=logger_path) self.logger_path = logger_path self.cfg = cfg def run(self): if self.metric.lower_better == 1: best_valid_score, best_test_score = float('inf'), float('inf') else: best_valid_score, best_test_score = -1, -1 for e in range(self.args.epoch): self.train_step(e) valid_score = self.test_step(self.valid_loader) logger.info(f"E={e}, valid={valid_score:.5f}, test-score={best_test_score:.5f}") # if valid_score > best_valid_score: if (valid_score > best_valid_score and self.metric.lower_better == -1) or \ (valid_score < best_valid_score and self.metric.lower_better == 1): test_score = self.test_step(self.test_loader) best_valid_score = valid_score best_test_score = test_score logger.info(f"UPDATE test-score={best_test_score:.5f}") logger.info(f"test-score={best_test_score:.5f}") def train_step(self, epoch): self.model.train() if epoch % 4 in range(1): # train separator set_requires_grad([self.model.separator], requires_grad=True) set_requires_grad([self.model.encoder], requires_grad=False) else: # train classifier set_requires_grad([self.model.separator], requires_grad=False) set_requires_grad([self.model.encoder], requires_grad=True) pbar = tqdm(self.train_loader, desc=f"E [{epoch}]") for data in pbar: data = data.to(self.device) c_logit, c_f, s_f, cmt_loss, reg_loss = self.model(data) # classification loss on c mask, target = nan2zero_get_mask(data, 'None', self.cfg) cls_loss = self.metric.loss_func(c_logit, target.float(), reduction='none') * mask cls_loss = cls_loss.sum() / mask.sum() mix_f = self.model.mix_cs_proj(c_f, s_f) inv_loss = self.simsiam_loss(c_f, mix_f) # inv_w: lambda_1 # reg_w: lambda_2 loss = cls_loss + cmt_loss + self.args.inv_w * inv_loss + self.args.reg_w * reg_loss self.opt.zero_grad() loss.backward() torch.nn.utils.clip_grad_norm_(self.model.parameters(), 5) self.opt.step() pbar.set_postfix_str(f"loss={loss.item():.4f}") self.writer.add_scalar('loss', loss.item(), self.total_step) self.writer.add_scalar('cls-loss', cls_loss.item(), self.total_step) self.writer.add_scalar('cmt-loss', cmt_loss.item(), self.total_step) self.writer.add_scalar('reg-loss', reg_loss.item(), self.total_step) self.total_step += 1 @torch.no_grad() def test_step(self, loader): self.model.eval() y_pred, y_gt = [], [] for data in loader: data = data.to(self.device) logit, _, _, _, _ = self.model(data) mask, _ = nan2zero_get_mask(data, 'None', self.cfg) pred, target = eval_data_preprocess(data.y, logit, mask, self.cfg) y_pred.append(pred) y_gt.append(target) score = eval_score(y_pred, y_gt, self.cfg) return score def simsiam_loss(self, causal_rep, mix_rep): causal_rep = causal_rep.detach() causal_rep = F.normalize(causal_rep, dim=1) mix_rep = F.normalize(mix_rep, dim=1) return -(causal_rep * mix_rep).sum(dim=1).mean() def main():
logger = logging.getLogger() def set_requires_grad(nets, requires_grad=False): """Set requies_grad=Fasle for all the networks to avoid unnecessary computations Parameters: nets (network list) -- a list of networks requires_grad (bool) -- whether the networks require gradients or not """ if not isinstance(nets, list): nets = [nets] for net in nets: if net is not None: for param in net.parameters(): param.requires_grad = requires_grad class Runner: def __init__(self, args, writer, logger_path): self.args = args self.device = torch.device(f'cuda') if args.dataset.startswith('GOOD'): # for GOOD, load Config cfg_path = os.path.join(args.config_path, args.dataset, args.domain, args.shift, 'base.yaml') cfg, _, _ = load_config(path=cfg_path) cfg = munchify(cfg) cfg.device = self.device dataset, meta_info = register.datasets[cfg.dataset.dataset_name].load(dataset_root=args.data_root, domain=cfg.dataset.domain, shift=cfg.dataset.shift_type, generate=cfg.dataset.generate) read_meta_info(meta_info, cfg) # cfg.dropout # cfg.bs # update dropout & bs cfg.model.dropout_rate = args.dropout cfg.train.train_bs = args.bs cfg.random_seed = args.random_seed loader = register.dataloader[cfg.dataset.dataloader_name].setup(dataset, cfg) self.train_loader = loader['train'] self.valid_loader = loader['val'] self.test_loader = loader['test'] self.metric = Metric() self.metric.set_score_func(dataset['metric'] if type(dataset) is dict else getattr(dataset, 'metric')) self.metric.set_loss_func(dataset['task'] if type(dataset) is dict else getattr(dataset, 'task')) cfg.metric = self.metric else: # DrugOOD dataset = DrugOODDataset(name=args.dataset, root=args.data_root) self.train_set = dataset[dataset.train_index] self.valid_set = dataset[dataset.valid_index] self.test_set = dataset[dataset.test_index] self.train_loader = DataLoader(self.train_set, batch_size=args.bs, shuffle=True, drop_last=True) self.valid_loader = DataLoader(self.valid_set, batch_size=args.bs, shuffle=False) self.test_loader = DataLoader(self.test_set, batch_size=args.bs, shuffle=False) self.metric = Metric() self.metric.set_loss_func(task_name='Binary classification') self.metric.set_score_func(metric_name='ROC-AUC') cfg = Munch() cfg.metric = self.metric cfg.model = Munch() cfg.model.model_level = 'graph' self.model = MyModel(args=args, config=cfg).to(self.device) self.opt = torch.optim.Adam(self.model.parameters(), lr=args.lr) self.total_step = 0 self.writer = writer describe_model(self.model, path=logger_path) self.logger_path = logger_path self.cfg = cfg def run(self): if self.metric.lower_better == 1: best_valid_score, best_test_score = float('inf'), float('inf') else: best_valid_score, best_test_score = -1, -1 for e in range(self.args.epoch): self.train_step(e) valid_score = self.test_step(self.valid_loader) logger.info(f"E={e}, valid={valid_score:.5f}, test-score={best_test_score:.5f}") # if valid_score > best_valid_score: if (valid_score > best_valid_score and self.metric.lower_better == -1) or \ (valid_score < best_valid_score and self.metric.lower_better == 1): test_score = self.test_step(self.test_loader) best_valid_score = valid_score best_test_score = test_score logger.info(f"UPDATE test-score={best_test_score:.5f}") logger.info(f"test-score={best_test_score:.5f}") def train_step(self, epoch): self.model.train() if epoch % 4 in range(1): # train separator set_requires_grad([self.model.separator], requires_grad=True) set_requires_grad([self.model.encoder], requires_grad=False) else: # train classifier set_requires_grad([self.model.separator], requires_grad=False) set_requires_grad([self.model.encoder], requires_grad=True) pbar = tqdm(self.train_loader, desc=f"E [{epoch}]") for data in pbar: data = data.to(self.device) c_logit, c_f, s_f, cmt_loss, reg_loss = self.model(data) # classification loss on c mask, target = nan2zero_get_mask(data, 'None', self.cfg) cls_loss = self.metric.loss_func(c_logit, target.float(), reduction='none') * mask cls_loss = cls_loss.sum() / mask.sum() mix_f = self.model.mix_cs_proj(c_f, s_f) inv_loss = self.simsiam_loss(c_f, mix_f) # inv_w: lambda_1 # reg_w: lambda_2 loss = cls_loss + cmt_loss + self.args.inv_w * inv_loss + self.args.reg_w * reg_loss self.opt.zero_grad() loss.backward() torch.nn.utils.clip_grad_norm_(self.model.parameters(), 5) self.opt.step() pbar.set_postfix_str(f"loss={loss.item():.4f}") self.writer.add_scalar('loss', loss.item(), self.total_step) self.writer.add_scalar('cls-loss', cls_loss.item(), self.total_step) self.writer.add_scalar('cmt-loss', cmt_loss.item(), self.total_step) self.writer.add_scalar('reg-loss', reg_loss.item(), self.total_step) self.total_step += 1 @torch.no_grad() def test_step(self, loader): self.model.eval() y_pred, y_gt = [], [] for data in loader: data = data.to(self.device) logit, _, _, _, _ = self.model(data) mask, _ = nan2zero_get_mask(data, 'None', self.cfg) pred, target = eval_data_preprocess(data.y, logit, mask, self.cfg) y_pred.append(pred) y_gt.append(target) score = eval_score(y_pred, y_gt, self.cfg) return score def simsiam_loss(self, causal_rep, mix_rep): causal_rep = causal_rep.detach() causal_rep = F.normalize(causal_rep, dim=1) mix_rep = F.normalize(mix_rep, dim=1) return -(causal_rep * mix_rep).sum(dim=1).mean() def main():
args = args_parser()
0
2023-10-09 11:24:46+00:00
8k
zbzhu99/madiff
diffuser/utils/pybullet_utils.py
[ { "identifier": "euler_from_quaternion", "path": "diffuser/utils/transformations.py", "snippet": "def euler_from_quaternion(quaternion, axes=\"sxyz\"):\n \"\"\"Return Euler angles from quaternion for specified axis sequence.\n >>> angles = euler_from_quaternion([0.06146124, 0, 0, 0.99810947])\n ...
import collections import colorsys import cProfile import datetime import inspect import json import math import os import pickle import platform import pstats import random import shutil import signal import sys import time import numpy as np import pybullet as p import yaml import psutil import logging import threading import pybullet_data import imageio import ghalton import ghalton import scipy from collections import defaultdict, deque, namedtuple from contextlib import contextmanager from itertools import combinations, count, cycle, islice, product from multiprocessing import TimeoutError from .transformations import ( euler_from_quaternion, quaternion_from_matrix, quaternion_slerp, unit_vector, ) from functools import wraps from PIL import Image, ImageDraw from PIL import Image, ImageDraw from motion_planners.lazy_prm import lazy_prm from bisect import bisect from scipy.spatial import ConvexHull
4,004
# Pose = namedtuple('Pose', ['position', 'orientation']) def Point(x=0.0, y=0.0, z=0.0): return np.array([x, y, z]) def Euler(roll=0.0, pitch=0.0, yaw=0.0): return np.array([roll, pitch, yaw]) def Pose(point=None, euler=None): point = Point() if point is None else point euler = Euler() if euler is None else euler return point, quat_from_euler(euler) def Pose2d(x=0.0, y=0.0, yaw=0.0): return np.array([x, y, yaw]) def invert(pose): point, quat = pose return p.invertTransform(point, quat) def multiply(*poses): pose = poses[0] for next_pose in poses[1:]: pose = p.multiplyTransforms(pose[0], pose[1], *next_pose) return pose def invert_quat(quat): pose = (unit_point(), quat) return quat_from_pose(invert(pose)) def multiply_quats(*quats): return quat_from_pose(multiply(*[(unit_point(), quat) for quat in quats])) def unit_from_theta(theta): return np.array([np.cos(theta), np.sin(theta)]) def quat_from_euler(euler): return p.getQuaternionFromEuler( euler ) # TODO: extrinsic (static) vs intrinsic (rotating) def euler_from_quat(quat): return p.getEulerFromQuaternion(quat) # rotation around fixed axis def intrinsic_euler_from_quat(quat): # axes = 'sxyz' if static else 'rxyz' return euler_from_quaternion(quat, axes="rxyz") def unit_point(): return (0.0, 0.0, 0.0) def unit_quat(): return quat_from_euler([0, 0, 0]) # [X,Y,Z,W] def quat_from_axis_angle(axis, angle): # axis-angle # return get_unit_vector(np.append(vec, [angle])) return np.append(math.sin(angle / 2) * get_unit_vector(axis), [math.cos(angle / 2)]) def unit_pose(): return (unit_point(), unit_quat()) def get_length(vec, norm=2): return np.linalg.norm(vec, ord=norm) def get_difference(p1, p2): assert len(p1) == len(p2) return np.array(p2) - np.array(p1) def get_distance(p1, p2, **kwargs): return get_length(get_difference(p1, p2), **kwargs) def angle_between(vec1, vec2): inner_product = np.dot(vec1, vec2) / (get_length(vec1) * get_length(vec2)) return math.acos(clip(inner_product, min_value=-1.0, max_value=+1.0)) def get_angle(q1, q2): return get_yaw(np.array(q2) - np.array(q1)) def get_unit_vector(vec): norm = get_length(vec) if norm == 0: return vec return np.array(vec) / norm def z_rotation(theta): return quat_from_euler([0, 0, theta]) def matrix_from_quat(quat): return np.array(p.getMatrixFromQuaternion(quat, physicsClientId=CLIENT)).reshape( 3, 3 ) def quat_from_matrix(rot): matrix = np.eye(4) matrix[:3, :3] = rot[:3, :3]
from __future__ import print_function directory = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(directory, "../motion")) # from ..motion.motion_planners.rrt_connect import birrt, direct_path # from future_builtins import map, filter # from builtins import input # TODO - use future try: user_input = raw_input except NameError: user_input = input INF = np.inf PI = np.pi EPSILON = 1e-6 DEFAULT_TIME_STEP = 1.0 / 240.0 # seconds Interval = namedtuple("Interval", ["lower", "upper"]) # AABB UNIT_LIMITS = Interval(0.0, 1.0) CIRCULAR_LIMITS = Interval(-PI, PI) UNBOUNDED_LIMITS = Interval(-INF, INF) # Resources # https://docs.google.com/document/d/10sXEhzFRSnvFcl3XxNGhnD4N2SedqwdAvK3dsihxVUA/edit # http://www.cs.kent.edu/~ruttan/GameEngines/lectures/Bullet_User_Manual ##################################### DRAKE_PATH = "models/drake/" # Models # Robots # MODEL_DIRECTORY = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'models/')) MODEL_DIRECTORY = "/home/janner/mount/blujoco/external/kuka" ROOMBA_URDF = "models/turtlebot/roomba.urdf" TURTLEBOT_URDF = "models/turtlebot/turtlebot_holonomic.urdf" DRAKE_IIWA_URDF = "models/drake/iiwa_description/urdf/iiwa14_polytope_collision.urdf" WSG_50_URDF = "models/drake/wsg_50_description/urdf/wsg_50_mesh_visual.urdf" # wsg_50 | wsg_50_mesh_visual | wsg_50_mesh_collision # SCHUNK_URDF = 'models/drake/wsg_50_description/sdf/schunk_wsg_50.sdf' PANDA_HAND_URDF = "models/franka_description/robots/hand.urdf" PANDA_ARM_URDF = "models/franka_description/robots/panda_arm_hand.urdf" # PyBullet Robots # PYBULLET_DIRECTORY = add_data_path() KUKA_IIWA_URDF = "kuka_iiwa/model.urdf" KUKA_IIWA_GRIPPER_SDF = "kuka_iiwa/kuka_with_gripper.sdf" R2D2_URDF = "r2d2.urdf" MINITAUR_URDF = "quadruped/minitaur.urdf" HUMANOID_MJCF = "mjcf/humanoid.xml" HUSKY_URDF = "husky/husky.urdf" RACECAR_URDF = "racecar/racecar.urdf" # racecar_differential.urdf PR2_GRIPPER = "pr2_gripper.urdf" PANDA_URDF = "franka_panda/panda.urdf" # PyBullet wsg50 robots # wsg50_one_motor_gripper.sdf - no visual # wsg50_one_motor_gripper_free_base.sdf - seg fault # wsg50_one_motor_gripper_left_finger.urdf - no fingers # wsg50_one_motor_gripper_new.sdf - no visual # wsg50_one_motor_gripper_new_free_base.sdf - octopus # wsg50_one_motor_gripper_no_finger.sdf - no visual # wsg50_one_motor_gripper_right_finger.urdf - no fingers WSG_GRIPPER = "gripper/wsg50_one_motor_gripper_new.sdf" # PyBullet Objects KIVA_SHELF_SDF = "kiva_shelf/model.sdf" FLOOR_URDF = "plane.urdf" TABLE_URDF = "table/table.urdf" # Objects SMALL_BLOCK_URDF = "models/drake/objects/block_for_pick_and_place.urdf" BLOCK_URDF = "models/drake/objects/block_for_pick_and_place_mid_size.urdf" SINK_URDF = "models/sink.urdf" STOVE_URDF = "models/stove.urdf" ##################################### # I/O SEPARATOR = "\n" + 50 * "-" + "\n" # def inf_generator(): # return iter(int, 1) inf_generator = count List = lambda *args: list(args) Tuple = lambda *args: tuple(args) def empty_sequence(): return iter([]) def irange(start, end=None, step=1): if end is None: end = start start = 0 n = start while n < end: yield n n += step def count_until(max_iterations=INF, max_time=INF): start_time = time.time() assert (max_iterations < INF) or (max_time < INF) for iteration in irange(max_iterations): if elapsed_time(start_time) >= max_time: break yield iteration def print_separator(n=50): print("\n" + n * "-" + "\n") def is_remote(): return "SSH_CONNECTION" in os.environ def is_darwin(): # TODO: change loading accordingly return platform.system() == "Darwin" # platform.release() # return sys.platform == 'darwin' def get_python_version(): return sys.version_info[0] def read(filename): with open(filename, "r") as f: return f.read() def write(filename, string): with open(filename, "w") as f: f.write(string) def read_pickle(filename): # Can sometimes read pickle3 from python2 by calling twice with open(filename, "rb") as f: try: return pickle.load(f) except UnicodeDecodeError as e: return pickle.load(f, encoding="latin1") def write_pickle(filename, data): # NOTE - cannot pickle lambda or nested functions with open(filename, "wb") as f: pickle.dump(data, f) def read_json(path): return json.loads(read(path)) def write_json(path, data): with open(path, "w") as f: json.dump(data, f, indent=2, sort_keys=True) def safe_remove(path): if os.path.exists(path): if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path) def ensure_dir(f): d = os.path.dirname(f) if not os.path.exists(d): os.makedirs(d) def list_paths(directory): return sorted( os.path.abspath(os.path.join(directory, filename)) for filename in os.listdir(directory) ) ################################################## def safe_zip(sequence1, sequence2): # TODO: *args sequence1, sequence2 = list(sequence1), list(sequence2) assert len(sequence1) == len(sequence2) return list(zip(sequence1, sequence2)) def get_pairs(sequence): # TODO: lazy version sequence = list(sequence) return safe_zip(sequence[:-1], sequence[1:]) def get_wrapped_pairs(sequence): # TODO: lazy version sequence = list(sequence) # zip(sequence, sequence[-1:] + sequence[:-1]) return safe_zip(sequence, sequence[1:] + sequence[:1]) def clip(value, min_value=-INF, max_value=+INF): return min(max(min_value, value), max_value) def randomize(iterable): # TODO: bisect sequence = list(iterable) random.shuffle(sequence) return sequence def get_random_seed(): return random.getstate()[1][1] def get_numpy_seed(): return np.random.get_state()[1][0] def set_random_seed(seed=None): if seed is not None: random.seed(seed) def wrap_numpy_seed(seed): return seed % (2**32) # int | hash def set_numpy_seed(seed=None): # These generators are different and independent if seed is not None: np.random.seed(wrap_numpy_seed(seed)) # print('Seed:', seed) DATE_FORMAT = "%y-%m-%d_%H-%M-%S" def get_date(): return datetime.datetime.now().strftime(DATE_FORMAT) def implies(p1, p2): return not p1 or p2 def roundrobin(*iterables): # https://docs.python.org/3.1/library/itertools.html#recipes "roundrobin('ABC', 'D', 'EF') --> A D E B F C" # Recipe credited to George Sakkis pending = len(iterables) nexts = cycle(iter(it).__next__ for it in iterables) while pending: try: for next in nexts: yield next() except StopIteration: pending -= 1 nexts = cycle(islice(nexts, pending)) def chunks(sequence, n=1): for i in range(0, len(sequence), n): yield sequence[i : i + n] def get_function_name(depth=1): return inspect.stack()[depth][3] def load_yaml(path): # grep -r --include="*.py" "yaml\." * # yaml.dump() with open(path, "r") as f: try: return yaml.safe_load(f) except yaml.YAMLError as exc: raise exc def flatten(iterable_of_iterables): return (item for iterables in iterable_of_iterables for item in iterables) def find(test, sequence): for item in sequence: if test(item): return item return None def merge_dicts(*args): result = {} for d in args: result.update(d) return result # return dict(reduce(operator.add, [d.items() for d in args])) def str_from_object(obj): # str_object if type(obj) in [list]: # , np.ndarray): return "[{}]".format(", ".join(str_from_object(item) for item in obj)) if type(obj) in [tuple]: return "({})".format(", ".join(str_from_object(item) for item in obj)) if type(obj) in [set, frozenset]: return "{{{}}}".format(", ".join(sorted(str_from_object(item) for item in obj))) if type(obj) in [dict, defaultdict]: # isinstance(obj, dict): return "{{{}}}".format( ", ".join( "{}: {}".format(*pair) for pair in sorted( tuple(map(str_from_object, pair)) for pair in obj.items() ) ) ) # if type(obj) in (float, np.float64): # obj = round(obj, 3) # if obj == 0: obj = 0 # NOTE - catches -0.0 bug # return '%.3f' % obj # if isinstance(obj, types.FunctionType): # return obj.__name__ return str(obj) # return repr(obj) def safe_sample(collection, k=1): collection = list(collection) if len(collection) <= k: return collection return random.sample(collection, k) class OrderedSet(collections.OrderedDict, collections.MutableSet): # TODO: https://stackoverflow.com/questions/1653970/does-python-have-an-ordered-set def __init__(self, seq=()): # known special case of set.__init__ # super(OrderedSet, self).__init__() self.update(seq) def update(self, *args, **kwargs): if kwargs: raise TypeError("update() takes no keyword arguments") for s in args: for e in s: self.add(e) def add(self, elem): self[elem] = None def discard(self, elem): self.pop(elem, None) def __le__(self, other): return all(e in other for e in self) def __lt__(self, other): return self <= other and self != other def __ge__(self, other): return all(e in self for e in other) def __gt__(self, other): return self >= other and self != other def __repr__(self): return "OrderedSet([%s])" % (", ".join(map(repr, self.keys()))) def __str__(self): return "{%s}" % (", ".join(map(repr, self.keys()))) difference = property(lambda self: self.__sub__) difference_update = property(lambda self: self.__isub__) intersection = property(lambda self: self.__and__) intersection_update = property(lambda self: self.__iand__) issubset = property(lambda self: self.__le__) issuperset = property(lambda self: self.__ge__) symmetric_difference = property(lambda self: self.__xor__) symmetric_difference_update = property(lambda self: self.__ixor__) union = property(lambda self: self.__or__) ################################################## BYTES_PER_KILOBYTE = math.pow(2, 10) BYTES_PER_GIGABYTE = math.pow(2, 30) KILOBYTES_PER_GIGABYTE = BYTES_PER_GIGABYTE / BYTES_PER_KILOBYTE def get_memory_in_kb(): # https://pypi.org/project/psutil/ # https://psutil.readthedocs.io/en/latest/ # rss: aka "Resident Set Size", this is the non-swapped physical memory a process has used. (bytes) # vms: aka "Virtual Memory Size", this is the total amount of virtual memory used by the process. (bytes) # shared: (Linux) memory that could be potentially shared with other processes. # text (Linux, BSD): aka TRS (text resident set) the amount of memory devoted to executable code. # data (Linux, BSD): aka DRS (data resident set) the amount of physical memory devoted to other than executable code. # lib (Linux): the memory used by shared libraries. # dirty (Linux): the number of dirty pages. # pfaults (macOS): number of page faults. # pageins (macOS): number of actual pageins. process = psutil.Process(os.getpid()) # process.pid() # process.ppid() pmem = process.memory_info() # this seems to actually get the current memory! return pmem.vms / BYTES_PER_KILOBYTE # print(process.memory_full_info()) # print(process.memory_percent()) # process.rlimit(psutil.RLIMIT_NOFILE) # set resource limits (Linux only) # print(psutil.virtual_memory()) # print(psutil.swap_memory()) # print(psutil.pids()) def raise_timeout(signum, frame): raise TimeoutError() @contextmanager def timeout(duration): # TODO: function that wraps around # https://www.jujens.eu/posts/en/2018/Jun/02/python-timeout-function/ # https://code-maven.com/python-timeout # https://pypi.org/project/func-timeout/ # https://pypi.org/project/timeout-decorator/ # https://eli.thegreenplace.net/2011/08/22/how-not-to-set-a-timeout-on-a-computation-in-python # https://docs.python.org/3/library/signal.html # https://docs.python.org/3/library/contextlib.html # https://stackoverflow.com/a/22348885 assert 0 < duration if duration == INF: yield return # Register a function to raise a TimeoutError on the signal signal.signal(signal.SIGALRM, raise_timeout) # Schedule the signal to be sent after ``duration`` signal.alarm(int(math.ceil(duration))) try: yield except TimeoutError as e: print("Timeout after {} sec".format(duration)) # traceback.print_exc() pass finally: # Unregister the signal so it won't be triggered # if the timeout is not reached signal.signal(signal.SIGALRM, signal.SIG_IGN) def log_time(method): """ A decorator for methods which will time the method and then emit a log.debug message with the method name and how long it took to execute. """ # https://github.com/mikedh/trimesh/blob/60dae2352875f48c4476e01052829e8b9166d9e5/trimesh/constants.py#L126 log = logging.getLogger() def timed(*args, **kwargs): tic = now() result = method(*args, **kwargs) log.debug("%s executed in %.4f seconds.", method.__name__, now() - tic) return result timed.__name__ = method.__name__ timed.__doc__ = method.__doc__ return timed def cached_fn(fn, cache=True, **global_kargs): # https://docs.python.org/3/library/functools.html#functools.cache def normal(*args, **local_kwargs): kwargs = dict(global_kargs) kwargs.update(local_kwargs) return fn(*args, **kwargs) if not cache: return normal # from functools import cache # # New in version 3.9 # from functools import lru_cache as cache # @cache(maxsize=None, typed=False) @cache_decorator def wrapped(*args, **local_kwargs): return normal(*args, **local_kwargs) return wrapped def cache_decorator(function): """ A decorator for class methods, replaces @property but will store and retrieve function return values in object cache. Parameters ------------ function : method This is used as a decorator: ``` @cache_decorator def foo(self, things): return 'happy days' ``` """ # https://github.com/mikedh/trimesh/blob/60dae2352875f48c4476e01052829e8b9166d9e5/trimesh/caching.py#L64 # from functools import cached_property # TODO: New in version 3.8 # use wraps to preserve docstring @wraps(function) def get_cached(*args, **kwargs): """ Only execute the function if its value isn't stored in cache already. """ self = args[0] # use function name as key in cache name = function.__name__ # do the dump logic ourselves to avoid # verifying cache twice per call self._cache.verify() # access cache dict to avoid automatic validation # since we already called cache.verify manually if name in self._cache.cache: # already stored so return value return self._cache.cache[name] # value not in cache so execute the function value = function(*args, **kwargs) # store the value if ( self._cache.force_immutable and hasattr(value, "flags") and len(value.shape) > 0 ): value.flags.writeable = False self._cache.cache[name] = value return value # all cached values are also properties # so they can be accessed like value attributes # rather than functions return property(get_cached) ##################################### class HideOutput(object): # https://stackoverflow.com/questions/5081657/how-do-i-prevent-a-c-shared-library-to-print-on-stdout-in-python # https://stackoverflow.com/questions/4178614/suppressing-output-of-module-calling-outside-library # https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python/22434262#22434262 """ A context manager that block stdout for its scope, usage: with HideOutput(): os.system('ls -l') """ DEFAULT_ENABLE = True def __init__(self, enable=None): if enable is None: enable = self.DEFAULT_ENABLE self.enable = enable if not self.enable: return sys.stdout.flush() self._origstdout = sys.stdout self._oldstdout_fno = os.dup(sys.stdout.fileno()) self._devnull = os.open(os.devnull, os.O_WRONLY) def __enter__(self): if not self.enable: return self.fd = 1 # self.fd = sys.stdout.fileno() self._newstdout = os.dup(self.fd) os.dup2(self._devnull, self.fd) os.close(self._devnull) sys.stdout = os.fdopen(self._newstdout, "w") def __exit__(self, exc_type, exc_val, exc_tb): if not self.enable: return sys.stdout.close() sys.stdout = self._origstdout sys.stdout.flush() os.dup2(self._oldstdout_fno, self.fd) os.close(self._oldstdout_fno) # Added ##################################### # Colors RGB = namedtuple("RGB", ["red", "green", "blue"]) RGBA = namedtuple("RGBA", ["red", "green", "blue", "alpha"]) MAX_RGB = 2**8 - 1 RED = RGBA(1, 0, 0, 1) GREEN = RGBA(0, 1, 0, 1) BLUE = RGBA(0, 0, 1, 1) BLACK = RGBA(0, 0, 0, 1) WHITE = RGBA(1, 1, 1, 1) BROWN = RGBA(0.396, 0.263, 0.129, 1) TAN = RGBA(0.824, 0.706, 0.549, 1) GREY = RGBA(0.5, 0.5, 0.5, 1) YELLOW = RGBA(1, 1, 0, 1) TRANSPARENT = RGBA(0, 0, 0, 0) ACHROMATIC_COLORS = { "white": WHITE, "grey": GREY, "black": BLACK, } CHROMATIC_COLORS = { "red": RED, "green": GREEN, "blue": BLUE, } COLOR_FROM_NAME = merge_dicts(ACHROMATIC_COLORS, CHROMATIC_COLORS) def remove_alpha(color): return RGB(*color[:3]) def apply_alpha(color, alpha=1.0): if color is None: return None red, green, blue = color[:3] return RGBA(red, green, blue, alpha) def spaced_colors(n, s=1, v=1): return [ RGB(*colorsys.hsv_to_rgb(h, s, v)) for h in np.linspace(0, 1, n, endpoint=False) ] ##################################### # Savers class Saver(object): # TODO: contextlib def save(self): pass def restore(self): raise NotImplementedError() def __enter__(self): # TODO: move the saving to enter? self.save() # return self def __exit__(self, type, value, traceback): self.restore() class ClientSaver(Saver): def __init__(self, new_client=None): self.client = CLIENT if new_client is not None: set_client(new_client) def restore(self): set_client(self.client) def __repr__(self): return "{}({})".format(self.__class__.__name__, self.client) class VideoSaver(Saver): def __init__(self, path): self.path = path if path is None: self.log_id = None else: name, ext = os.path.splitext(path) assert ext == ".mp4" # STATE_LOGGING_PROFILE_TIMINGS, STATE_LOGGING_ALL_COMMANDS # p.submitProfileTiming('pythontest") self.log_id = p.startStateLogging( p.STATE_LOGGING_VIDEO_MP4, fileName=path, physicsClientId=CLIENT ) def restore(self): if self.log_id is not None: p.stopStateLogging(self.log_id) print("Saved", self.path) class Profiler(Saver): fields = ["tottime", "cumtime", None] def __init__(self, field="tottime", num=10): assert field in self.fields self.field = field self.num = num if field is None: return self.pr = cProfile.Profile() def save(self): if self.field is None: return self.pr.enable() return self.pr def restore(self): if self.field is None: return self.pr.disable() stream = None # stream = io.StringIO() stats = pstats.Stats(self.pr, stream=stream).sort_stats( self.field ) # TODO: print multiple stats.print_stats(self.num) return stats ##################################### class PoseSaver(Saver): def __init__(self, body, pose=None): self.body = body if pose is None: pose = get_pose(self.body) self.pose = pose self.velocity = get_velocity(self.body) def apply_mapping(self, mapping): self.body = mapping.get(self.body, self.body) def restore(self): set_pose(self.body, self.pose) set_velocity(self.body, *self.velocity) def __repr__(self): return "{}({})".format(self.__class__.__name__, self.body) class ConfSaver(Saver): def __init__(self, body, joints=None, positions=None): self.body = body if joints is None: joints = get_movable_joints(self.body) self.joints = joints if positions is None: positions = get_joint_positions(self.body, self.joints) self.positions = positions self.velocities = get_joint_velocities(self.body, self.joints) @property def conf(self): return self.positions def apply_mapping(self, mapping): self.body = mapping.get(self.body, self.body) def restore(self): # set_configuration(self.body, self.conf) # set_joint_positions(self.body, self.joints, self.positions) set_joint_states(self.body, self.joints, self.positions, self.velocities) # set_joint_velocities(self.body, self.joints, self.velocities) def __repr__(self): return "{}({})".format(self.__class__.__name__, self.body) class BodySaver(Saver): def __init__(self, body, **kwargs): # , pose=None): # if pose is None: # pose = get_pose(body) self.body = body self.pose_saver = PoseSaver(body) self.conf_saver = ConfSaver(body, **kwargs) self.savers = [self.pose_saver, self.conf_saver] def apply_mapping(self, mapping): for saver in self.savers: saver.apply_mapping(mapping) def restore(self): for saver in self.savers: saver.restore() def __repr__(self): return "{}({})".format(self.__class__.__name__, self.body) class WorldSaver(Saver): def __init__(self, bodies=None): if bodies is None: bodies = get_bodies() self.bodies = bodies self.body_savers = [BodySaver(body) for body in self.bodies] # TODO: add/remove new bodies # TODO: save the camera pose def restore(self): for body_saver in self.body_savers: body_saver.restore() ##################################### # Simulation CLIENTS = {} # TODO: rename to include locked CLIENT = 0 def get_client(client=None): if client is None: return CLIENT return client def set_client(client): global CLIENT CLIENT = client ModelInfo = namedtuple("URDFInfo", ["name", "path", "fixed_base", "scale"]) INFO_FROM_BODY = {} def get_model_info(body): key = (CLIENT, body) return INFO_FROM_BODY.get(key, None) def get_urdf_flags(cache=False, cylinder=False): # by default, Bullet disables self-collision # URDF_INITIALIZE_SAT_FEATURES # URDF_ENABLE_CACHED_GRAPHICS_SHAPES seems to help # but URDF_INITIALIZE_SAT_FEATURES does not (might need to be provided a mesh) # flags = p.URDF_INITIALIZE_SAT_FEATURES | p.URDF_ENABLE_CACHED_GRAPHICS_SHAPES flags = 0 if cache: flags |= p.URDF_ENABLE_CACHED_GRAPHICS_SHAPES if cylinder: flags |= p.URDF_USE_IMPLICIT_CYLINDER return flags def load_pybullet(filename, fixed_base=False, scale=1.0, **kwargs): # fixed_base=False implies infinite base mass with LockRenderer(): if filename.endswith(".urdf"): flags = get_urdf_flags(**kwargs) body = p.loadURDF( filename, useFixedBase=fixed_base, flags=flags, globalScaling=scale, physicsClientId=CLIENT, ) elif filename.endswith(".sdf"): body = p.loadSDF(filename, physicsClientId=CLIENT) elif filename.endswith(".xml"): body = p.loadMJCF(filename, physicsClientId=CLIENT) elif filename.endswith(".bullet"): body = p.loadBullet(filename, physicsClientId=CLIENT) elif filename.endswith(".obj"): # TODO: fixed_base => mass = 0? body = create_obj(filename, scale=scale, **kwargs) else: raise ValueError(filename) INFO_FROM_BODY[CLIENT, body] = ModelInfo(None, filename, fixed_base, scale) return body def set_caching(cache): p.setPhysicsEngineParameter(enableFileCaching=int(cache), physicsClientId=CLIENT) def load_model_info(info): # TODO: disable file caching to reuse old filenames # p.setPhysicsEngineParameter(enableFileCaching=0, physicsClientId=CLIENT) if info.path.endswith(".urdf"): return load_pybullet(info.path, fixed_base=info.fixed_base, scale=info.scale) if info.path.endswith(".obj"): mass = STATIC_MASS if info.fixed_base else 1.0 return create_obj(info.path, mass=mass, scale=info.scale) raise NotImplementedError(info.path) URDF_FLAGS = [ p.URDF_USE_INERTIA_FROM_FILE, p.URDF_USE_SELF_COLLISION, p.URDF_USE_SELF_COLLISION_EXCLUDE_PARENT, p.URDF_USE_SELF_COLLISION_EXCLUDE_ALL_PARENTS, ] def get_model_path(rel_path): # TODO: add to search path directory = os.path.dirname(os.path.abspath(__file__)) return os.path.join(directory, rel_path) def load_model(rel_path, pose=None, **kwargs): # TODO: error with loadURDF when loading MESH visual and CYLINDER collision # abs_path = get_model_path(rel_path) abs_path = os.path.join(MODEL_DIRECTORY, rel_path) add_data_path() # with LockRenderer(): body = load_pybullet(abs_path, **kwargs) if pose is not None: set_pose(body, pose) return body # TOOLS_VERSION = date.date() def get_version(): # year-month-0-day format s = str(p.getAPIVersion(physicsClientId=CLIENT)) return datetime.date(year=int(s[:4]), month=int(s[4:6]), day=int(s[7:9])) ##################################### # class World(object): # def __init__(self, client): # self.client = client # self.bodies = {} # def activate(self): # set_client(self.client) # def load(self, path, name=None, fixed_base=False, scale=1.): # body = p.loadURDF(path, useFixedBase=fixed_base, physicsClientId=self.client) # self.bodies[body] = URDFInfo(name, path, fixed_base, scale) # return body # def remove(self, body): # del self.bodies[body] # return p.removeBody(body, physicsClientId=self.client) # def reset(self): # p.resetSimulation(physicsClientId=self.client) # self.bodies = {} # # TODO: with statement # def copy(self): # raise NotImplementedError() # def __repr__(self): # return '{}({})'.format(self.__class__.__name__, len(self.bodies)) ##################################### now = time.time def elapsed_time(start_time): return time.time() - start_time MouseEvent = namedtuple( "MouseEvent", ["eventType", "mousePosX", "mousePosY", "buttonIndex", "buttonState"] ) def get_mouse_events(): return list( MouseEvent(*event) for event in p.getMouseEvents(physicsClientId=CLIENT) ) def update_viewer(): # https://docs.python.org/2/library/select.html # events = p.getKeyboardEvents() # TODO: only works when the viewer is in focus get_mouse_events() # for k, v in keys.items(): # #p.KEY_IS_DOWN, p.KEY_WAS_RELEASED, p.KEY_WAS_TRIGGERED # if (k == p.B3G_RETURN) and (v & p.KEY_WAS_TRIGGERED): # return # time.sleep(1e-3) # Doesn't work # disable_gravity() def wait_for_duration(duration): # , dt=0): t0 = time.time() while elapsed_time(t0) <= duration: update_viewer() def simulate_for_duration(duration): dt = get_time_step() for i in range(int(duration / dt)): step_simulation() def get_time_step(): # {'gravityAccelerationX', 'useRealTimeSimulation', 'gravityAccelerationZ', 'numSolverIterations', # 'gravityAccelerationY', 'numSubSteps', 'fixedTimeStep'} return p.getPhysicsEngineParameters(physicsClientId=CLIENT)["fixedTimeStep"] def enable_separating_axis_test(): p.setPhysicsEngineParameter(enableSAT=1, physicsClientId=CLIENT) # p.setCollisionFilterPair() # p.setCollisionFilterGroupMask() # p.setInternalSimFlags() # enableFileCaching: Set to 0 to disable file caching, such as .obj wavefront file loading # p.getAPIVersion() # TODO: check that API is up-to-date def simulate_for_sim_duration(sim_duration, real_dt=0, frequency=INF): t0 = time.time() sim_dt = get_time_step() sim_time = 0 last_print = 0 while sim_time < sim_duration: if frequency < (sim_time - last_print): print( "Sim time: {:.3f} | Real time: {:.3f}".format( sim_time, elapsed_time(t0) ) ) last_print = sim_time step_simulation() sim_time += sim_dt time.sleep(real_dt) def wait_for_user(message="Press enter to continue"): if has_gui() and is_darwin(): # OS X doesn't multi-thread the OpenGL visualizer # wait_for_interrupt() return threaded_input(message) return user_input(message) def wait_if_gui(*args, **kwargs): if has_gui(): wait_for_user(*args, **kwargs) def is_unlocked(): return CLIENTS[CLIENT] is True def wait_if_unlocked(*args, **kwargs): if is_unlocked(): wait_for_user(*args, **kwargs) def wait_for_interrupt(max_time=np.inf): """ Hold Ctrl to move the camera as well as zoom """ print("Press Ctrl-C to continue") try: wait_for_duration(max_time) except KeyboardInterrupt: pass finally: print() def set_preview(enable): # lightPosition, shadowMapResolution, shadowMapWorldSize p.configureDebugVisualizer(p.COV_ENABLE_GUI, enable, physicsClientId=CLIENT) p.configureDebugVisualizer( p.COV_ENABLE_RGB_BUFFER_PREVIEW, enable, physicsClientId=CLIENT ) p.configureDebugVisualizer( p.COV_ENABLE_DEPTH_BUFFER_PREVIEW, enable, physicsClientId=CLIENT ) p.configureDebugVisualizer( p.COV_ENABLE_SEGMENTATION_MARK_PREVIEW, enable, physicsClientId=CLIENT ) # p.configureDebugVisualizer(p.COV_ENABLE_SINGLE_STEP_RENDERING, True, physicsClientId=CLIENT) # p.configureDebugVisualizer(p.COV_ENABLE_WIREFRAME, True, physicsClientId=CLIENT) def enable_preview(): set_preview(enable=True) def disable_preview(): set_preview(enable=False) def set_renderer(enable): client = CLIENT if not has_gui(client): return CLIENTS[client] = enable p.configureDebugVisualizer( p.COV_ENABLE_RENDERING, int(enable), physicsClientId=client ) class LockRenderer(Saver): # disabling rendering temporary makes adding objects faster def __init__(self, lock=True): self.client = CLIENT self.state = CLIENTS[self.client] # skip if the visualizer isn't active if has_gui(self.client) and lock: set_renderer(enable=False) def restore(self): if not has_gui(self.client): return assert self.state is not None if self.state != CLIENTS[self.client]: set_renderer(enable=self.state) def connect(use_gui=True, shadows=True, color=None, width=None, height=None): # Shared Memory: execute the physics simulation and rendering in a separate process # https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/examples/vrminitaur.py#L7 # make sure to compile pybullet with PYBULLET_USE_NUMPY enabled if use_gui and not is_darwin() and ("DISPLAY" not in os.environ): use_gui = False print("No display detected!") method = p.GUI if use_gui else p.DIRECT with HideOutput(): # --window_backend=2 --render_device=0' # options="--mp4=\"test.mp4\' --mp4fps=240" options = "" if color is not None: options += "--background_color_red={} --background_color_green={} --background_color_blue={}".format( *color ) if width is not None: options += "--width={}".format(width) if height is not None: options += "--height={}".format(height) sim_id = p.connect(method, options=options) # key=None, # sim_id = p.connect(p.GUI, options='--opengl2') if use_gui else p.connect(p.DIRECT) assert 0 <= sim_id # sim_id2 = p.connect(p.SHARED_MEMORY) # print(sim_id, sim_id2) CLIENTS[sim_id] = True if use_gui else None if use_gui: # p.COV_ENABLE_PLANAR_REFLECTION # p.COV_ENABLE_SINGLE_STEP_RENDERING disable_preview() p.configureDebugVisualizer( p.COV_ENABLE_TINY_RENDERER, False, physicsClientId=sim_id ) # TODO: does this matter? p.configureDebugVisualizer( p.COV_ENABLE_SHADOWS, shadows, physicsClientId=sim_id ) p.configureDebugVisualizer( p.COV_ENABLE_MOUSE_PICKING, False, physicsClientId=sim_id ) # mouse moves meshes p.configureDebugVisualizer( p.COV_ENABLE_KEYBOARD_SHORTCUTS, False, physicsClientId=sim_id ) # you can also use GUI mode, for faster OpenGL rendering (instead of TinyRender CPU) # visualizer_options = { # p.COV_ENABLE_WIREFRAME: 1, # p.COV_ENABLE_SHADOWS: 0, # p.COV_ENABLE_RENDERING: 0, # p.COV_ENABLE_TINY_RENDERER: 1, # p.COV_ENABLE_RGB_BUFFER_PREVIEW: 0, # p.COV_ENABLE_DEPTH_BUFFER_PREVIEW: 0, # p.COV_ENABLE_SEGMENTATION_MARK_PREVIEW: 0, # p.COV_ENABLE_VR_RENDER_CONTROLLERS: 0, # p.COV_ENABLE_VR_PICKING: 0, # p.COV_ENABLE_VR_TELEPORTING: 0, # } # for pair in visualizer_options.items(): # p.configureDebugVisualizer(*pair) return sim_id def threaded_input(*args, **kwargs): # OS X doesn't multi-thread the OpenGL visualizer # http://openrave.org/docs/0.8.2/_modules/openravepy/misc/#SetViewerUserThread # https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/examples/userData.py # https://github.com/bulletphysics/bullet3/tree/master/examples/ExampleBrowser # from pybullet_utils import bullet_client # from pybullet_utils.bullet_client import BulletClient # server = bullet_client.BulletClient(connection_mode=p.SHARED_MEMORY_SERVER) # GUI_SERVER # sim_id = p.connect(p.GUI) # print(dir(server)) # client = bullet_client.BulletClient(connection_mode=p.SHARED_MEMORY) # sim_id = p.connect(p.SHARED_MEMORY) # threading = __import__('threading') data = [] thread = threading.Thread( target=lambda: data.append(user_input(*args, **kwargs)), args=[] ) thread.start() # threading.enumerate() # thread_id = 0 # for tid, tobj in threading._active.items(): # if tobj is thread: # thread_id = tid # break try: while thread.is_alive(): update_viewer() finally: thread.join() return data[-1] def disconnect(): # TODO: change CLIENT? if CLIENT in CLIENTS: del CLIENTS[CLIENT] with HideOutput(): return p.disconnect(physicsClientId=CLIENT) def is_connected(): # return p.isConnected(physicsClientId=CLIENT) return p.getConnectionInfo(physicsClientId=CLIENT)["isConnected"] def get_connection(client=None): return p.getConnectionInfo(physicsClientId=get_client(client))["connectionMethod"] def has_gui(client=None): return get_connection(get_client(client)) == p.GUI def get_data_path(): return pybullet_data.getDataPath() def add_data_path(data_path=None): if data_path is None: data_path = get_data_path() p.setAdditionalSearchPath(data_path) return data_path GRAVITY = 9.8 def enable_gravity(): p.setGravity(0, 0, -GRAVITY, physicsClientId=CLIENT) def disable_gravity(): p.setGravity(0, 0, 0, physicsClientId=CLIENT) def step_simulation(): p.stepSimulation(physicsClientId=CLIENT) def update_scene(): # TODO: https://github.com/bulletphysics/bullet3/pull/3331 p.performCollisionDetection(physicsClientId=CLIENT) def set_real_time(real_time): p.setRealTimeSimulation(int(real_time), physicsClientId=CLIENT) def enable_real_time(): set_real_time(True) def disable_real_time(): set_real_time(False) def update_state(): # TODO: this doesn't seem to automatically update still disable_gravity() # step_simulation() # for body in get_bodies(): # for link in get_links(body): # # if set to 1 (or True), the Cartesian world position/orientation # # will be recomputed using forward kinematics. # get_link_state(body, link) # for body in get_bodies(): # get_pose(body) # for joint in get_joints(body): # get_joint_position(body, joint) # p.getKeyboardEvents() # p.getMouseEvents() def reset_simulation(): # RESET_USE_SIMPLE_BROADPHASE # RESET_USE_DEFORMABLE_WORLD # RESET_USE_DISCRETE_DYNAMICS_WORLD p.resetSimulation(physicsClientId=CLIENT) ##################################### Pixel = namedtuple("Pixel", ["row", "column"]) def get_camera_matrix(width, height, fx, fy=None): if fy is None: fy = fx # cx, cy = width / 2., height / 2. cx, cy = (width - 1) / 2.0, (height - 1) / 2.0 return np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]]) def clip_pixel(pixel, width, height): x, y = pixel # TODO: row, column instead? return clip(x, 0, width - 1), clip(y, 0, height - 1) def ray_from_pixel(camera_matrix, pixel): return np.linalg.inv(camera_matrix).dot(np.append(pixel, 1)) def pixel_from_ray(camera_matrix, ray): return camera_matrix.dot(np.array(ray) / ray[2])[:2] def dimensions_from_camera_matrix(camera_matrix): cx, cy = np.array(camera_matrix)[:2, 2] width, height = (2 * cx + 1), (2 * cy + 1) return width, height def get_field_of_view(camera_matrix): dimensions = np.array(dimensions_from_camera_matrix(camera_matrix)) focal_lengths = np.array([camera_matrix[i, i] for i in range(2)]) return 2 * np.arctan(np.divide(dimensions, 2 * focal_lengths)) def get_focal_lengths(dims, fovs): return np.divide(dims, np.tan(fovs / 2)) / 2 def pixel_from_point(camera_matrix, point_camera): px, py = pixel_from_ray(camera_matrix, point_camera) width, height = dimensions_from_camera_matrix(camera_matrix) if (0 <= px < width) and (0 <= py < height): r, c = np.floor([py, px]).astype(int) return Pixel(r, c) return None def get_image_aabb(camera_matrix): upper = np.array(dimensions_from_camera_matrix(camera_matrix)) - 1 lower = np.zeros(upper.shape) return AABB(lower, upper) def get_visible_aabb(camera_matrix, rays): image_aabb = get_image_aabb(camera_matrix) rays_aabb = aabb_from_points([pixel_from_ray(camera_matrix, ray) for ray in rays]) intersection = aabb_intersection(image_aabb, rays_aabb) if intersection is None: return intersection return AABB(*np.array(intersection).astype(int)) def draw_lines_on_image(img_array, points, color="red", **kwargs): source_img = Image.fromarray(img_array) draw = ImageDraw.Draw(source_img) draw.line(list(map(tuple, points)), fill=color, **kwargs) return np.array(source_img) def draw_box_on_image(img_array, aabb, color="red", **kwargs): # https://github.com/caelan/ROS-Labeler/blob/master/main.py # https://github.mit.edu/caelan/rl-plan/blob/master/planar_ml/rect_cnn.py # https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html # TODO: annotate boxes with text source_img = Image.fromarray(img_array) draw = ImageDraw.Draw(source_img) # box = list(np.array(aabb).astype(int).flatten()) box = list(map(tuple, aabb)) draw.rectangle(box, fill=None, outline=color, **kwargs) return np.array(source_img) def extract_box_from_image(img_array, box): (x1, y1), (x2, y2) = np.array(box).astype(int) return img_array[y1 : y2 + 1, x1 : x2 + 1, ...] ##################################### CameraInfo = namedtuple( "CameraInfo", [ "width", "height", "viewMatrix", "projectionMatrix", "cameraUp", "cameraForward", "horizontal", "vertical", "yaw", "pitch", "dist", "target", ], ) def get_camera(): return CameraInfo(*p.getDebugVisualizerCamera(physicsClientId=CLIENT)) def set_camera(yaw, pitch, distance, target_position=np.zeros(3)): # TODO: in degrees p.resetDebugVisualizerCamera( distance, yaw, pitch, target_position, physicsClientId=CLIENT ) def get_pitch(point): dx, dy, dz = point return np.math.atan2(dz, np.sqrt(dx**2 + dy**2)) def get_yaw(point): dx, dy = point[:2] return np.math.atan2(dy, dx) def set_camera_pose(camera_point, target_point=np.zeros(3)): delta_point = np.array(target_point) - np.array(camera_point) distance = np.linalg.norm(delta_point) yaw = get_yaw(delta_point) - np.pi / 2 # TODO: hack pitch = get_pitch(delta_point) p.resetDebugVisualizerCamera( distance, math.degrees(yaw), math.degrees(pitch), target_point, physicsClientId=CLIENT, ) def set_camera_pose2(world_from_camera, distance=2): target_camera = np.array([0, 0, distance]) target_world = tform_point(world_from_camera, target_camera) camera_world = point_from_pose(world_from_camera) set_camera_pose(camera_world, target_world) # roll, pitch, yaw = euler_from_quat(quat_from_pose(world_from_camera)) # TODO: assert that roll is about zero? # p.resetDebugVisualizerCamera(cameraDistance=distance, cameraYaw=math.degrees(yaw), cameraPitch=math.degrees(-pitch), # cameraTargetPosition=target_world, physicsClientId=CLIENT) CameraImage = namedtuple( "CameraImage", [ "rgbPixels", "depthPixels", "segmentationMaskBuffer", "camera_pose", "camera_matrix", ], ) # CameraImage = namedtuple('CameraImage', ['rgb', 'depth', 'segmentation', 'camera_pose']) def demask_pixel(pixel): # https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/examples/segmask_linkindex.py # Not needed when p.ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX is not enabled # if 0 <= pixel: # return None # Returns a large value when undefined body = pixel & ((1 << 24) - 1) link = (pixel >> 24) - 1 return body, link def save_image(filename, rgba): imageio.imwrite(filename, rgba) # import scipy.misc # if filename.endswith('.jpg'): # scipy.misc.imsave(filename, rgba[:, :, :3]) # elif filename.endswith('.png'): # scipy.misc.imsave(filename, rgba) # (480, 640, 4) # # scipy.misc.toimage(image_array, cmin=0.0, cmax=...).save('outfile.jpg') # else: # raise ValueError(filename) print("Saved image at {}".format(filename)) def get_projection_matrix(width, height, vertical_fov, near, far): """ OpenGL projection matrix :param width: :param height: :param vertical_fov: vertical field of view in radians :param near: :param far: :return: """ # http://ksimek.github.io/2013/08/13/intrinsic/ # http://www.songho.ca/opengl/gl_projectionmatrix.html # http://www.songho.ca/opengl/gl_transform.html#matrix # https://www.edmundoptics.fr/resources/application-notes/imaging/understanding-focal-length-and-field-of-view/ # gluPerspective() requires only 4 parameters; vertical field of view (FOV), # the aspect ratio of width to height and the distances to near and far clipping planes. aspect = float(width) / height fov_degrees = math.degrees(vertical_fov) projection_matrix = p.computeProjectionMatrixFOV( fov=fov_degrees, aspect=aspect, nearVal=near, farVal=far, physicsClientId=CLIENT ) # projection_matrix = p.computeProjectionMatrix(left=0, right=width, top=height, bottom=0, # near=near, far=far, physicsClientId=CLIENT) return projection_matrix # return np.reshape(projection_matrix, [4, 4]) def image_from_segmented(segmented, color_from_body=None): if color_from_body is None: bodies = get_bodies() color_from_body = dict(zip(bodies, spaced_colors(len(bodies)))) image = np.zeros(segmented.shape[:2] + (3,)) for r in range(segmented.shape[0]): for c in range(segmented.shape[1]): body, link = segmented[r, c, :] image[r, c, :] = color_from_body.get(body, BLACK)[:3] # TODO: alpha return image def get_image_flags(segment=False, segment_links=False): if segment: if segment_links: return p.ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX return 0 # TODO: adjust output dimension when not segmenting links return p.ER_NO_SEGMENTATION_MASK def extract_segmented(seg_image): segmented = np.zeros(seg_image.shape + (2,)) for r in range(segmented.shape[0]): for c in range(segmented.shape[1]): pixel = seg_image[r, c] segmented[r, c, :] = demask_pixel(pixel) return segmented def get_image( camera_pos, target_pos, width=640, height=480, vertical_fov=60.0, near=0.02, far=5.0, tiny=False, segment=False, **kwargs ): # computeViewMatrixFromYawPitchRoll up_vector = [0, 0, 1] # up vector of the camera, in Cartesian world coordinates view_matrix = p.computeViewMatrix( cameraEyePosition=camera_pos, cameraTargetPosition=target_pos, cameraUpVector=up_vector, physicsClientId=CLIENT, ) projection_matrix = get_projection_matrix(width, height, vertical_fov, near, far) # p.isNumpyEnabled() # copying pixels from C/C++ to Python can be really slow for large images, unless you compile PyBullet using NumPy flags = get_image_flags(segment=segment, **kwargs) # DIRECT mode has no OpenGL, so it requires ER_TINY_RENDERER renderer = p.ER_TINY_RENDERER if tiny else p.ER_BULLET_HARDWARE_OPENGL rgb, d, seg = p.getCameraImage( width, height, viewMatrix=view_matrix, projectionMatrix=projection_matrix, shadow=False, # only applies to ER_TINY_RENDERER flags=flags, renderer=renderer, physicsClientId=CLIENT, )[2:] depth = far * near / (far - (far - near) * d) # https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/examples/pointCloudFromCameraImage.py # https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/examples/getCameraImageTest.py segmented = None if segment: segmented = extract_segmented(seg) camera_tform = np.reshape(view_matrix, [4, 4]) camera_tform[:3, 3] = camera_pos view_pose = multiply(pose_from_tform(camera_tform), Pose(euler=Euler(roll=PI))) focal_length = get_focal_lengths(height, vertical_fov) # TODO: horizontal_fov camera_matrix = get_camera_matrix(width, height, focal_length) return CameraImage(rgb, depth, segmented, view_pose, camera_matrix) def get_image_at_pose(camera_pose, camera_matrix, far=5.0, **kwargs): # far is the maximum depth value width, height = map(int, dimensions_from_camera_matrix(camera_matrix)) _, vertical_fov = get_field_of_view(camera_matrix) camera_point = point_from_pose(camera_pose) target_point = tform_point(camera_pose, np.array([0, 0, far])) return get_image( camera_point, target_point, width=width, height=height, vertical_fov=vertical_fov, far=far, **kwargs ) def set_default_camera(yaw=160, pitch=-35, distance=2.5): # TODO: deprecate set_camera(yaw, pitch, distance, Point()) ##################################### def save_state(): return p.saveState(physicsClientId=CLIENT) def restore_state(state_id): p.restoreState(stateId=state_id, physicsClientId=CLIENT) def save_bullet(filename): p.saveBullet(filename, physicsClientId=CLIENT) def restore_bullet(filename): p.restoreState(fileName=filename, physicsClientId=CLIENT) ##################################### # Geometry # Pose = namedtuple('Pose', ['position', 'orientation']) def Point(x=0.0, y=0.0, z=0.0): return np.array([x, y, z]) def Euler(roll=0.0, pitch=0.0, yaw=0.0): return np.array([roll, pitch, yaw]) def Pose(point=None, euler=None): point = Point() if point is None else point euler = Euler() if euler is None else euler return point, quat_from_euler(euler) def Pose2d(x=0.0, y=0.0, yaw=0.0): return np.array([x, y, yaw]) def invert(pose): point, quat = pose return p.invertTransform(point, quat) def multiply(*poses): pose = poses[0] for next_pose in poses[1:]: pose = p.multiplyTransforms(pose[0], pose[1], *next_pose) return pose def invert_quat(quat): pose = (unit_point(), quat) return quat_from_pose(invert(pose)) def multiply_quats(*quats): return quat_from_pose(multiply(*[(unit_point(), quat) for quat in quats])) def unit_from_theta(theta): return np.array([np.cos(theta), np.sin(theta)]) def quat_from_euler(euler): return p.getQuaternionFromEuler( euler ) # TODO: extrinsic (static) vs intrinsic (rotating) def euler_from_quat(quat): return p.getEulerFromQuaternion(quat) # rotation around fixed axis def intrinsic_euler_from_quat(quat): # axes = 'sxyz' if static else 'rxyz' return euler_from_quaternion(quat, axes="rxyz") def unit_point(): return (0.0, 0.0, 0.0) def unit_quat(): return quat_from_euler([0, 0, 0]) # [X,Y,Z,W] def quat_from_axis_angle(axis, angle): # axis-angle # return get_unit_vector(np.append(vec, [angle])) return np.append(math.sin(angle / 2) * get_unit_vector(axis), [math.cos(angle / 2)]) def unit_pose(): return (unit_point(), unit_quat()) def get_length(vec, norm=2): return np.linalg.norm(vec, ord=norm) def get_difference(p1, p2): assert len(p1) == len(p2) return np.array(p2) - np.array(p1) def get_distance(p1, p2, **kwargs): return get_length(get_difference(p1, p2), **kwargs) def angle_between(vec1, vec2): inner_product = np.dot(vec1, vec2) / (get_length(vec1) * get_length(vec2)) return math.acos(clip(inner_product, min_value=-1.0, max_value=+1.0)) def get_angle(q1, q2): return get_yaw(np.array(q2) - np.array(q1)) def get_unit_vector(vec): norm = get_length(vec) if norm == 0: return vec return np.array(vec) / norm def z_rotation(theta): return quat_from_euler([0, 0, theta]) def matrix_from_quat(quat): return np.array(p.getMatrixFromQuaternion(quat, physicsClientId=CLIENT)).reshape( 3, 3 ) def quat_from_matrix(rot): matrix = np.eye(4) matrix[:3, :3] = rot[:3, :3]
return quaternion_from_matrix(matrix)
1
2023-10-13 13:03:53+00:00
8k
hellloxiaotian/KDNet
utils/datasets_yolov7.py
[ { "identifier": "check_requirements", "path": "utils/general.py", "snippet": "def check_requirements(requirements='requirements.txt', exclude=()):\n # Check installed dependencies meet requirements (pass *.txt file or list of packages)\n import pkg_resources as pkg\n prefix = colorstr('red', 'b...
import glob import logging import math import os import random import shutil import time import cv2 import numpy as np import torch import torch.nn.functional as F import pickle import pafy import albumentations as A from itertools import repeat from multiprocessing.pool import ThreadPool from pathlib import Path from threading import Thread from PIL import Image, ExifTags from torch.utils.data import Dataset from tqdm import tqdm from copy import deepcopy from torchvision.utils import save_image from torchvision.ops import roi_pool, roi_align, ps_roi_pool, ps_roi_align from utils.general import check_requirements, xyxy2xywh, xywh2xyxy, xywhn2xyxy, xyn2xy, segment2box, segments2boxes, \ resample_segments, clean_str from utils.torch_utils import torch_distributed_zero_first
5,306
f += [os.path.join(parent, x) for x in t] # local to global path # f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib) print('f:', f[0]) else: raise Exception(f'{prefix}{p} does not exist') self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats]) print('self.img_files:', self.img_files[0]) # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib assert self.img_files, f'{prefix}No images found' except Exception as e: raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {help_url}') # Check cache self.label_files = img2label_paths(self.img_files) # labels print('self.label_files', self.label_files[0]) # self.label_files = self.img_files(jpg/txt) cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels if cache_path.is_file(): # print('cache_path:', cache_path) cache, exists = torch.load(cache_path), True # load #if cache['hash'] != get_hash(self.label_files + self.img_files) or 'version' not in cache: # changed # cache, exists = self.cache_labels(cache_path, prefix), False # re-cache else: cache, exists = self.cache_labels(cache_path, prefix), False # cache # Display cache nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total if exists: d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted" tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}' # Read cache cache.pop('hash') # remove hash cache.pop('version') # remove version labels, shapes, self.segments = zip(*cache.values()) self.labels = list(labels) self.shapes = np.array(shapes, dtype=np.float64) self.img_files = list(cache.keys()) # update self.label_files = img2label_paths(cache.keys()) # update if single_cls: for x in self.labels: x[:, 0] = 0 n = len(shapes) # number of images bi = np.floor(np.arange(n) / batch_size).astype(int) # batch index nb = bi[-1] + 1 # number of batches self.batch = bi # batch index of image self.n = n self.indices = range(n) # Rectangular Training if self.rect: # Sort by aspect ratio s = self.shapes # wh ar = s[:, 1] / s[:, 0] # aspect ratio irect = ar.argsort() self.img_files = [self.img_files[i] for i in irect] self.label_files = [self.label_files[i] for i in irect] self.labels = [self.labels[i] for i in irect] self.shapes = s[irect] # wh ar = ar[irect] # Set training image shapes shapes = [[1, 1]] * nb for i in range(nb): ari = ar[bi == i] mini, maxi = ari.min(), ari.max() if maxi < 1: shapes[i] = [maxi, 1] elif mini > 1: shapes[i] = [1, 1 / mini] self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(int) * stride # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM) self.imgs = [None] * n if cache_images: if cache_images == 'disk': self.im_cache_dir = Path(Path(self.img_files[0]).parent.as_posix() + '_npy') self.img_npy = [self.im_cache_dir / Path(f).with_suffix('.npy').name for f in self.img_files] self.im_cache_dir.mkdir(parents=True, exist_ok=True) gb = 0 # Gigabytes of cached images self.img_hw0, self.img_hw = [None] * n, [None] * n results = ThreadPool(8).imap(lambda x: load_image(*x), zip(repeat(self), range(n))) pbar = tqdm(enumerate(results), total=n) for i, x in pbar: if cache_images == 'disk': if not self.img_npy[i].exists(): np.save(self.img_npy[i].as_posix(), x[0]) gb += self.img_npy[i].stat().st_size else: self.imgs[i], self.img_hw0[i], self.img_hw[i] = x gb += self.imgs[i].nbytes pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)' pbar.close() def cache_labels(self, path=Path('./labels.cache'), prefix=''): # Cache dataset labels, check images and read shapes x = {} # dict nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, duplicate pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files)) for i, (im_file, lb_file) in enumerate(pbar): try: # verify images im = Image.open(im_file) im.verify() # PIL verify shape = exif_size(im) # image size segments = [] # instance segments assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels' assert im.format.lower() in img_formats, f'invalid image format {im.format}' # verify labels if os.path.isfile(lb_file): nf += 1 # label found with open(lb_file, 'r') as f: l = [x.split() for x in f.read().strip().splitlines()] if any([len(x) > 8 for x in l]): # is segment classes = np.array([x[0] for x in l], dtype=np.float32) segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
# Dataset utils and dataloaders #from pycocotools import mask as maskUtils # Parameters help_url = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data' img_formats = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes vid_formats = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes logger = logging.getLogger(__name__) # Get orientation exif tag for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break def get_hash(files): # Returns a single hash value of a list of files return sum(os.path.getsize(f) for f in files if os.path.isfile(f)) def exif_size(img): # Returns exif-corrected PIL size s = img.size # (width, height) try: rotation = dict(img._getexif().items())[orientation] if rotation == 6: # rotation 270 s = (s[1], s[0]) elif rotation == 8: # rotation 90 s = (s[1], s[0]) except: pass return s def create_dataloader(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False, rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''): # Make sure only the first process in DDP process the dataset first, and the following others can use the cache with torch_distributed_zero_first(rank): dataset = LoadImagesAndLabels(path, imgsz, batch_size, augment=augment, # augment images hyp=hyp, # augmentation hyperparameters rect=rect, # rectangular training cache_images=cache, single_cls=opt.single_cls, stride=int(stride), pad=pad, image_weights=image_weights, prefix=prefix) batch_size = min(batch_size, len(dataset)) nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers]) # number of workers sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader() dataloader = loader(dataset, batch_size=batch_size, num_workers=nw, sampler=sampler, pin_memory=True, collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn) return dataloader, dataset class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader): """ Dataloader that reuses workers Uses same syntax as vanilla DataLoader """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler)) self.iterator = super().__iter__() def __len__(self): return len(self.batch_sampler.sampler) def __iter__(self): for i in range(len(self)): yield next(self.iterator) class _RepeatSampler(object): """ Sampler that repeats forever Args: sampler (Sampler) """ def __init__(self, sampler): self.sampler = sampler def __iter__(self): while True: yield from iter(self.sampler) class LoadImages: # for inference def __init__(self, path, img_size=640, stride=32): p = str(Path(path).absolute()) # os-agnostic absolute path if '*' in p: files = sorted(glob.glob(p, recursive=True)) # glob elif os.path.isdir(p): files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir elif os.path.isfile(p): files = [p] # files else: raise Exception(f'ERROR: {p} does not exist') images = [x for x in files if x.split('.')[-1].lower() in img_formats] videos = [x for x in files if x.split('.')[-1].lower() in vid_formats] ni, nv = len(images), len(videos) self.img_size = img_size self.stride = stride self.files = images + videos self.nf = ni + nv # number of files self.video_flag = [False] * ni + [True] * nv self.mode = 'image' if any(videos): self.new_video(videos[0]) # new video else: self.cap = None assert self.nf > 0, f'No images or videos found in {p}. ' \ f'Supported formats are:\nimages: {img_formats}\nvideos: {vid_formats}' def __iter__(self): self.count = 0 return self def __next__(self): if self.count == self.nf: raise StopIteration path = self.files[self.count] if self.video_flag[self.count]: # Read video self.mode = 'video' ret_val, img0 = self.cap.read() if not ret_val: self.count += 1 self.cap.release() if self.count == self.nf: # last video raise StopIteration else: path = self.files[self.count] self.new_video(path) ret_val, img0 = self.cap.read() self.frame += 1 print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.nframes}) {path}: ', end='') else: # Read image self.count += 1 img0 = cv2.imread(path) # BGR assert img0 is not None, 'Image Not Found ' + path #print(f'image {self.count}/{self.nf} {path}: ', end='') # Padded resize img = letterbox(img0, self.img_size, stride=self.stride)[0] # Convert img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 img = np.ascontiguousarray(img) return path, img, img0, self.cap def new_video(self, path): self.frame = 0 self.cap = cv2.VideoCapture(path) self.nframes = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) def __len__(self): return self.nf # number of files class LoadWebcam: # for inference def __init__(self, pipe='0', img_size=640, stride=32): self.img_size = img_size self.stride = stride if pipe.isnumeric(): pipe = eval(pipe) # local camera # pipe = 'rtsp://192.168.1.64/1' # IP camera # pipe = 'rtsp://username:password@192.168.1.64/1' # IP camera with login # pipe = 'http://wmccpinetop.axiscam.net/mjpg/video.mjpg' # IP golf camera self.pipe = pipe self.cap = cv2.VideoCapture(pipe) # video capture object self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size def __iter__(self): self.count = -1 return self def __next__(self): self.count += 1 if cv2.waitKey(1) == ord('q'): # q to quit self.cap.release() cv2.destroyAllWindows() raise StopIteration # Read frame if self.pipe == 0: # local camera ret_val, img0 = self.cap.read() img0 = cv2.flip(img0, 1) # flip left-right else: # IP camera n = 0 while True: n += 1 self.cap.grab() if n % 30 == 0: # skip frames ret_val, img0 = self.cap.retrieve() if ret_val: break # Print assert ret_val, f'Camera Error {self.pipe}' img_path = 'webcam.jpg' print(f'webcam {self.count}: ', end='') # Padded resize img = letterbox(img0, self.img_size, stride=self.stride)[0] # Convert img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416 img = np.ascontiguousarray(img) return img_path, img, img0, None def __len__(self): return 0 class LoadStreams: # multiple IP or RTSP cameras def __init__(self, sources='streams.txt', img_size=640, stride=32): self.mode = 'stream' self.img_size = img_size self.stride = stride if os.path.isfile(sources): with open(sources, 'r') as f: sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())] else: sources = [sources] n = len(sources) self.imgs = [None] * n self.sources = [clean_str(x) for x in sources] # clean source names for later for i, s in enumerate(sources): # Start the thread to read frames from the video stream print(f'{i + 1}/{n}: {s}... ', end='') url = eval(s) if s.isnumeric() else s if 'youtube.com/' in str(url) or 'youtu.be/' in str(url): # if source is YouTube video check_requirements(('pafy', 'youtube_dl')) url = pafy.new(url).getbest(preftype="mp4").url cap = cv2.VideoCapture(url) assert cap.isOpened(), f'Failed to open {s}' w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) self.fps = cap.get(cv2.CAP_PROP_FPS) % 100 _, self.imgs[i] = cap.read() # guarantee first frame thread = Thread(target=self.update, args=([i, cap]), daemon=True) print(f' success ({w}x{h} at {self.fps:.2f} FPS).') thread.start() print('') # newline # check for common shapes s = np.stack([letterbox(x, self.img_size, stride=self.stride)[0].shape for x in self.imgs], 0) # shapes self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal if not self.rect: print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.') def update(self, index, cap): # Read next stream frame in a daemon thread n = 0 while cap.isOpened(): n += 1 # _, self.imgs[index] = cap.read() cap.grab() if n == 4: # read every 4th frame success, im = cap.retrieve() self.imgs[index] = im if success else self.imgs[index] * 0 n = 0 time.sleep(1 / self.fps) # wait time def __iter__(self): self.count = -1 return self def __next__(self): self.count += 1 img0 = self.imgs.copy() if cv2.waitKey(1) == ord('q'): # q to quit cv2.destroyAllWindows() raise StopIteration # Letterbox img = [letterbox(x, self.img_size, auto=self.rect, stride=self.stride)[0] for x in img0] # Stack img = np.stack(img, 0) # Convert img = img[:, :, :, ::-1].transpose(0, 3, 1, 2) # BGR to RGB, to bsx3x416x416 img = np.ascontiguousarray(img) return self.sources, img, img0, None def __len__(self): return 0 # 1E12 frames = 32 streams at 30 FPS for 30 years def img2label_paths(img_paths): # Define label paths as a function of image paths sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings return ['txt'.join(x.replace(sa, sb, 1).rsplit(x.split('.')[-1], 1)) for x in img_paths] class LoadImagesAndLabels(Dataset): # for training/testing def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False, cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''): self.img_size = img_size self.augment = augment self.hyp = hyp self.image_weights = image_weights self.rect = False if image_weights else rect self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training) self.mosaic_border = [-img_size // 2, -img_size // 2] self.stride = stride self.path = path print('path:', path) #self.albumentations = Albumentations() if augment else None try: f = [] # image files for p in path if isinstance(path, list) else [path]: p = Path(p) # os-agnostic if p.is_dir(): # dir f += glob.glob(str(p / '**' / '*.*'), recursive=True) # f = list(p.rglob('**/*.*')) # pathlib elif p.is_file(): # file with open(p, 'r') as t: t = t.read().strip().splitlines() # parent = str(p.parent) + os.sep parent = str(p.parent).split("/splits", -1)[0] + os.sep +'images/' # print('parent:', parent) # /data/zxy/datasets/CCPD2019/images/ f += [os.path.join(parent, x) for x in t] # local to global path # f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib) print('f:', f[0]) else: raise Exception(f'{prefix}{p} does not exist') self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in img_formats]) print('self.img_files:', self.img_files[0]) # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib assert self.img_files, f'{prefix}No images found' except Exception as e: raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {help_url}') # Check cache self.label_files = img2label_paths(self.img_files) # labels print('self.label_files', self.label_files[0]) # self.label_files = self.img_files(jpg/txt) cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels if cache_path.is_file(): # print('cache_path:', cache_path) cache, exists = torch.load(cache_path), True # load #if cache['hash'] != get_hash(self.label_files + self.img_files) or 'version' not in cache: # changed # cache, exists = self.cache_labels(cache_path, prefix), False # re-cache else: cache, exists = self.cache_labels(cache_path, prefix), False # cache # Display cache nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total if exists: d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted" tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}' # Read cache cache.pop('hash') # remove hash cache.pop('version') # remove version labels, shapes, self.segments = zip(*cache.values()) self.labels = list(labels) self.shapes = np.array(shapes, dtype=np.float64) self.img_files = list(cache.keys()) # update self.label_files = img2label_paths(cache.keys()) # update if single_cls: for x in self.labels: x[:, 0] = 0 n = len(shapes) # number of images bi = np.floor(np.arange(n) / batch_size).astype(int) # batch index nb = bi[-1] + 1 # number of batches self.batch = bi # batch index of image self.n = n self.indices = range(n) # Rectangular Training if self.rect: # Sort by aspect ratio s = self.shapes # wh ar = s[:, 1] / s[:, 0] # aspect ratio irect = ar.argsort() self.img_files = [self.img_files[i] for i in irect] self.label_files = [self.label_files[i] for i in irect] self.labels = [self.labels[i] for i in irect] self.shapes = s[irect] # wh ar = ar[irect] # Set training image shapes shapes = [[1, 1]] * nb for i in range(nb): ari = ar[bi == i] mini, maxi = ari.min(), ari.max() if maxi < 1: shapes[i] = [maxi, 1] elif mini > 1: shapes[i] = [1, 1 / mini] self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(int) * stride # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM) self.imgs = [None] * n if cache_images: if cache_images == 'disk': self.im_cache_dir = Path(Path(self.img_files[0]).parent.as_posix() + '_npy') self.img_npy = [self.im_cache_dir / Path(f).with_suffix('.npy').name for f in self.img_files] self.im_cache_dir.mkdir(parents=True, exist_ok=True) gb = 0 # Gigabytes of cached images self.img_hw0, self.img_hw = [None] * n, [None] * n results = ThreadPool(8).imap(lambda x: load_image(*x), zip(repeat(self), range(n))) pbar = tqdm(enumerate(results), total=n) for i, x in pbar: if cache_images == 'disk': if not self.img_npy[i].exists(): np.save(self.img_npy[i].as_posix(), x[0]) gb += self.img_npy[i].stat().st_size else: self.imgs[i], self.img_hw0[i], self.img_hw[i] = x gb += self.imgs[i].nbytes pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)' pbar.close() def cache_labels(self, path=Path('./labels.cache'), prefix=''): # Cache dataset labels, check images and read shapes x = {} # dict nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, duplicate pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files)) for i, (im_file, lb_file) in enumerate(pbar): try: # verify images im = Image.open(im_file) im.verify() # PIL verify shape = exif_size(im) # image size segments = [] # instance segments assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels' assert im.format.lower() in img_formats, f'invalid image format {im.format}' # verify labels if os.path.isfile(lb_file): nf += 1 # label found with open(lb_file, 'r') as f: l = [x.split() for x in f.read().strip().splitlines()] if any([len(x) > 8 for x in l]): # is segment classes = np.array([x[0] for x in l], dtype=np.float32) segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
6
2023-10-08 13:05:58+00:00
8k
OpenGVLab/perception_test_iccv2023
tsl/libs/modeling/meta_archs.py
[ { "identifier": "register_meta_arch", "path": "tsl/libs/modeling/models.py", "snippet": "def register_meta_arch(name):\n def decorator(cls):\n meta_archs[name] = cls\n return cls\n return decorator" }, { "identifier": "make_backbone", "path": "tsl/libs/modeling/models.py"...
import math import torch from torch import nn from torch.nn import functional as F from .models import register_meta_arch, make_backbone, make_neck, make_generator from .blocks import MaskedConv1D, Scale, LayerNorm from .losses import ctr_diou_loss_1d, sigmoid_focal_loss from ..utils import batched_nms
5,601
n_mha_win_size, # window size for self attention; -1 to use full seq embd_kernel_size, # kernel size of the embedding network embd_dim, # output feat channel of the embedding network embd_with_ln, # attach layernorm to embedding network fpn_dim, # feature dim on FPN fpn_with_ln, # if to apply layer norm at the end of fpn fpn_start_level, # start level of fpn head_dim, # feature dim for head regression_range, # regression range on each level of FPN head_num_layers, # number of layers in the head (including the classifier) head_kernel_size, # kernel size for reg/cls heads head_with_ln, # attache layernorm to reg/cls heads use_abs_pe, # if to use abs position encoding use_rel_pe, # if to use rel position encoding num_classes, # number of action classes train_cfg, # other cfg for training test_cfg # other cfg for testing ): super().__init__() # re-distribute params to backbone / neck / head self.fpn_strides = [scale_factor**i for i in range( fpn_start_level, backbone_arch[-1]+1 )] self.reg_range = regression_range assert len(self.fpn_strides) == len(self.reg_range) self.scale_factor = scale_factor # #classes = num_classes + 1 (background) with last category as background # e.g., num_classes = 10 -> 0, 1, ..., 9 as actions, 10 as background self.num_classes = num_classes # check the feature pyramid and local attention window size self.max_seq_len = max_seq_len if isinstance(n_mha_win_size, int): self.mha_win_size = [n_mha_win_size]*(1 + backbone_arch[-1]) else: assert len(n_mha_win_size) == (1 + backbone_arch[-1]) self.mha_win_size = n_mha_win_size max_div_factor = 1 for l, (s, w) in enumerate(zip(self.fpn_strides, self.mha_win_size)): stride = s * (w // 2) * 2 if w > 1 else s assert max_seq_len % stride == 0, "max_seq_len must be divisible by fpn stride and window size" if max_div_factor < stride: max_div_factor = stride self.max_div_factor = max_div_factor # training time config self.train_center_sample = train_cfg['center_sample'] assert self.train_center_sample in ['radius', 'none'] self.train_center_sample_radius = train_cfg['center_sample_radius'] self.train_loss_weight = train_cfg['loss_weight'] self.train_cls_prior_prob = train_cfg['cls_prior_prob'] self.train_dropout = train_cfg['dropout'] self.train_droppath = train_cfg['droppath'] self.train_label_smoothing = train_cfg['label_smoothing'] # test time config self.test_pre_nms_thresh = test_cfg['pre_nms_thresh'] self.test_pre_nms_topk = test_cfg['pre_nms_topk'] self.test_iou_threshold = test_cfg['iou_threshold'] self.test_min_score = test_cfg['min_score'] self.test_max_seg_num = test_cfg['max_seg_num'] self.test_nms_method = test_cfg['nms_method'] assert self.test_nms_method in ['soft', 'hard', 'none'] self.test_duration_thresh = test_cfg['duration_thresh'] self.test_multiclass_nms = test_cfg['multiclass_nms'] self.test_nms_sigma = test_cfg['nms_sigma'] self.test_voting_thresh = test_cfg['voting_thresh'] # we will need a better way to dispatch the params to backbones / necks # backbone network: conv + transformer assert backbone_type in ['convTransformer', 'conv'] if backbone_type == 'convTransformer': self.backbone = make_backbone( 'convTransformer', **{ 'n_in' : input_dim, 'n_embd' : embd_dim, 'n_head': n_head, 'n_embd_ks': embd_kernel_size, 'max_len': max_seq_len, 'arch' : backbone_arch, 'mha_win_size': self.mha_win_size, 'scale_factor' : scale_factor, 'with_ln' : embd_with_ln, 'attn_pdrop' : 0.0, 'proj_pdrop' : self.train_dropout, 'path_pdrop' : self.train_droppath, 'use_abs_pe' : use_abs_pe, 'use_rel_pe' : use_rel_pe } ) else: self.backbone = make_backbone( 'conv', **{ 'n_in': input_dim, 'n_embd': embd_dim, 'n_embd_ks': embd_kernel_size, 'arch': backbone_arch, 'scale_factor': scale_factor, 'with_ln' : embd_with_ln } ) if isinstance(embd_dim, (list, tuple)): embd_dim = sum(embd_dim) # fpn network: convs assert fpn_type in ['fpn', 'identity'] self.neck = make_neck( fpn_type, **{ 'in_channels' : [embd_dim] * (backbone_arch[-1] + 1), 'out_channel' : fpn_dim, 'scale_factor' : scale_factor, 'start_level' : fpn_start_level, 'with_ln' : fpn_with_ln } ) # location generator: points
class PtTransformerClsHead(nn.Module): """ 1D Conv heads for classification """ def __init__( self, input_dim, feat_dim, num_classes, prior_prob=0.01, num_layers=3, kernel_size=3, act_layer=nn.ReLU, with_ln=False, empty_cls = [] ): super().__init__() self.act = act_layer() # build the head self.head = nn.ModuleList() self.norm = nn.ModuleList() for idx in range(num_layers-1): if idx == 0: in_dim = input_dim out_dim = feat_dim else: in_dim = feat_dim out_dim = feat_dim self.head.append( MaskedConv1D( in_dim, out_dim, kernel_size, stride=1, padding=kernel_size//2, bias=(not with_ln) ) ) if with_ln: self.norm.append(LayerNorm(out_dim)) else: self.norm.append(nn.Identity()) # classifier self.cls_head = MaskedConv1D( feat_dim, num_classes, kernel_size, stride=1, padding=kernel_size//2 ) # use prior in model initialization to improve stability # this will overwrite other weight init if prior_prob > 0: bias_value = -(math.log((1 - prior_prob) / prior_prob)) torch.nn.init.constant_(self.cls_head.conv.bias, bias_value) # a quick fix to empty categories: # the weights assocaited with these categories will remain unchanged # we set their bias to a large negative value to prevent their outputs if len(empty_cls) > 0: bias_value = -(math.log((1 - 1e-6) / 1e-6)) for idx in empty_cls: torch.nn.init.constant_(self.cls_head.conv.bias[idx], bias_value) def forward(self, fpn_feats, fpn_masks): assert len(fpn_feats) == len(fpn_masks) # apply the classifier for each pyramid level out_logits = tuple() for _, (cur_feat, cur_mask) in enumerate(zip(fpn_feats, fpn_masks)): cur_out = cur_feat for idx in range(len(self.head)): cur_out, _ = self.head[idx](cur_out, cur_mask) cur_out = self.act(self.norm[idx](cur_out)) cur_logits, _ = self.cls_head(cur_out, cur_mask) out_logits += (cur_logits, ) # fpn_masks remains the same return out_logits class PtTransformerRegHead(nn.Module): """ Shared 1D Conv heads for regression Simlar logic as PtTransformerClsHead with separated implementation for clarity """ def __init__( self, input_dim, feat_dim, fpn_levels, num_layers=3, kernel_size=3, act_layer=nn.ReLU, with_ln=False ): super().__init__() self.fpn_levels = fpn_levels self.act = act_layer() # build the conv head self.head = nn.ModuleList() self.norm = nn.ModuleList() for idx in range(num_layers-1): if idx == 0: in_dim = input_dim out_dim = feat_dim else: in_dim = feat_dim out_dim = feat_dim self.head.append( MaskedConv1D( in_dim, out_dim, kernel_size, stride=1, padding=kernel_size//2, bias=(not with_ln) ) ) if with_ln: self.norm.append(LayerNorm(out_dim)) else: self.norm.append(nn.Identity()) self.scale = nn.ModuleList() for idx in range(fpn_levels): self.scale.append(Scale()) # segment regression self.offset_head = MaskedConv1D( feat_dim, 2, kernel_size, stride=1, padding=kernel_size//2 ) def forward(self, fpn_feats, fpn_masks): assert len(fpn_feats) == len(fpn_masks) assert len(fpn_feats) == self.fpn_levels # apply the classifier for each pyramid level out_offsets = tuple() for l, (cur_feat, cur_mask) in enumerate(zip(fpn_feats, fpn_masks)): cur_out = cur_feat for idx in range(len(self.head)): cur_out, _ = self.head[idx](cur_out, cur_mask) cur_out = self.act(self.norm[idx](cur_out)) cur_offsets, _ = self.offset_head(cur_out, cur_mask) out_offsets += (F.relu(self.scale[l](cur_offsets)), ) # fpn_masks remains the same return out_offsets @register_meta_arch("LocPointTransformer") class PtTransformer(nn.Module): """ Transformer based model for single stage action localization """ def __init__( self, backbone_type, # a string defines which backbone we use fpn_type, # a string defines which fpn we use backbone_arch, # a tuple defines #layers in embed / stem / branch scale_factor, # scale factor between branch layers input_dim, # input feat dim max_seq_len, # max sequence length (used for training) max_buffer_len_factor, # max buffer size (defined a factor of max_seq_len) n_head, # number of heads for self-attention in transformer n_mha_win_size, # window size for self attention; -1 to use full seq embd_kernel_size, # kernel size of the embedding network embd_dim, # output feat channel of the embedding network embd_with_ln, # attach layernorm to embedding network fpn_dim, # feature dim on FPN fpn_with_ln, # if to apply layer norm at the end of fpn fpn_start_level, # start level of fpn head_dim, # feature dim for head regression_range, # regression range on each level of FPN head_num_layers, # number of layers in the head (including the classifier) head_kernel_size, # kernel size for reg/cls heads head_with_ln, # attache layernorm to reg/cls heads use_abs_pe, # if to use abs position encoding use_rel_pe, # if to use rel position encoding num_classes, # number of action classes train_cfg, # other cfg for training test_cfg # other cfg for testing ): super().__init__() # re-distribute params to backbone / neck / head self.fpn_strides = [scale_factor**i for i in range( fpn_start_level, backbone_arch[-1]+1 )] self.reg_range = regression_range assert len(self.fpn_strides) == len(self.reg_range) self.scale_factor = scale_factor # #classes = num_classes + 1 (background) with last category as background # e.g., num_classes = 10 -> 0, 1, ..., 9 as actions, 10 as background self.num_classes = num_classes # check the feature pyramid and local attention window size self.max_seq_len = max_seq_len if isinstance(n_mha_win_size, int): self.mha_win_size = [n_mha_win_size]*(1 + backbone_arch[-1]) else: assert len(n_mha_win_size) == (1 + backbone_arch[-1]) self.mha_win_size = n_mha_win_size max_div_factor = 1 for l, (s, w) in enumerate(zip(self.fpn_strides, self.mha_win_size)): stride = s * (w // 2) * 2 if w > 1 else s assert max_seq_len % stride == 0, "max_seq_len must be divisible by fpn stride and window size" if max_div_factor < stride: max_div_factor = stride self.max_div_factor = max_div_factor # training time config self.train_center_sample = train_cfg['center_sample'] assert self.train_center_sample in ['radius', 'none'] self.train_center_sample_radius = train_cfg['center_sample_radius'] self.train_loss_weight = train_cfg['loss_weight'] self.train_cls_prior_prob = train_cfg['cls_prior_prob'] self.train_dropout = train_cfg['dropout'] self.train_droppath = train_cfg['droppath'] self.train_label_smoothing = train_cfg['label_smoothing'] # test time config self.test_pre_nms_thresh = test_cfg['pre_nms_thresh'] self.test_pre_nms_topk = test_cfg['pre_nms_topk'] self.test_iou_threshold = test_cfg['iou_threshold'] self.test_min_score = test_cfg['min_score'] self.test_max_seg_num = test_cfg['max_seg_num'] self.test_nms_method = test_cfg['nms_method'] assert self.test_nms_method in ['soft', 'hard', 'none'] self.test_duration_thresh = test_cfg['duration_thresh'] self.test_multiclass_nms = test_cfg['multiclass_nms'] self.test_nms_sigma = test_cfg['nms_sigma'] self.test_voting_thresh = test_cfg['voting_thresh'] # we will need a better way to dispatch the params to backbones / necks # backbone network: conv + transformer assert backbone_type in ['convTransformer', 'conv'] if backbone_type == 'convTransformer': self.backbone = make_backbone( 'convTransformer', **{ 'n_in' : input_dim, 'n_embd' : embd_dim, 'n_head': n_head, 'n_embd_ks': embd_kernel_size, 'max_len': max_seq_len, 'arch' : backbone_arch, 'mha_win_size': self.mha_win_size, 'scale_factor' : scale_factor, 'with_ln' : embd_with_ln, 'attn_pdrop' : 0.0, 'proj_pdrop' : self.train_dropout, 'path_pdrop' : self.train_droppath, 'use_abs_pe' : use_abs_pe, 'use_rel_pe' : use_rel_pe } ) else: self.backbone = make_backbone( 'conv', **{ 'n_in': input_dim, 'n_embd': embd_dim, 'n_embd_ks': embd_kernel_size, 'arch': backbone_arch, 'scale_factor': scale_factor, 'with_ln' : embd_with_ln } ) if isinstance(embd_dim, (list, tuple)): embd_dim = sum(embd_dim) # fpn network: convs assert fpn_type in ['fpn', 'identity'] self.neck = make_neck( fpn_type, **{ 'in_channels' : [embd_dim] * (backbone_arch[-1] + 1), 'out_channel' : fpn_dim, 'scale_factor' : scale_factor, 'start_level' : fpn_start_level, 'with_ln' : fpn_with_ln } ) # location generator: points
self.point_generator = make_generator(
3
2023-10-09 05:44:20+00:00
8k
falesiani/torch_ga
torch_ga/torch_ga.py
[ { "identifier": "get_cayley_tensor", "path": "torch_ga/cayley.py", "snippet": "def get_cayley_tensor(metric, bases, blades):\n num_blades = len(blades)\n\n t_geom = np.zeros((num_blades, num_blades, num_blades), dtype=np.int32)\n t_inner = np.zeros((num_blades, num_blades, num_blades), dtype=np...
from typing import List, Any, Union, Optional from .cayley import get_cayley_tensor, blades_from_bases from .blades import ( BladeKind, get_blade_of_kind_indices, get_blade_indices_from_names, get_blade_repr, invert_blade_indices ) from .mv_ops import mv_multiply, mv_reversion, mv_grade_automorphism, mv_conv1d, f_mv_conv1d, mv_multiply_element_wise from .mv import MultiVector import numbers import numpy as np import torch
6,819
"""Provides classes and operations for performing geometric algebra with TensorFlow. The `GeometricAlgebra` class is used to construct the algebra given a metric. It exposes methods for operating on `torch.Tensor` instances where their last axis is interpreted as blades of the algebra. """ # import einops class GeometricAlgebra: """Class used for performing geometric algebra operations on `torch.Tensor` instances. Exposes methods for operating on `torch.Tensor` instances where their last axis is interpreted as blades of the algebra. Holds the metric and other quantities derived from it. """ def __init__(self, metric: List[float]): """Creates a GeometricAlgebra object given a metric. The algebra will have as many basis vectors as there are elements in the metric. Args: metric: Metric as a list. Specifies what basis vectors square to """ self._metric = torch.tensor(metric, dtype=torch.float32) self._num_bases = len(metric) self._bases = list(map(str, range(self._num_bases))) self._blades, self._blade_degrees = blades_from_bases(self._bases) self._blade_degrees = torch.tensor(self._blade_degrees) self._num_blades = len(self._blades) self._max_degree = self._blade_degrees.max() # [Blades, Blades, Blades]
"""Provides classes and operations for performing geometric algebra with TensorFlow. The `GeometricAlgebra` class is used to construct the algebra given a metric. It exposes methods for operating on `torch.Tensor` instances where their last axis is interpreted as blades of the algebra. """ # import einops class GeometricAlgebra: """Class used for performing geometric algebra operations on `torch.Tensor` instances. Exposes methods for operating on `torch.Tensor` instances where their last axis is interpreted as blades of the algebra. Holds the metric and other quantities derived from it. """ def __init__(self, metric: List[float]): """Creates a GeometricAlgebra object given a metric. The algebra will have as many basis vectors as there are elements in the metric. Args: metric: Metric as a list. Specifies what basis vectors square to """ self._metric = torch.tensor(metric, dtype=torch.float32) self._num_bases = len(metric) self._bases = list(map(str, range(self._num_bases))) self._blades, self._blade_degrees = blades_from_bases(self._bases) self._blade_degrees = torch.tensor(self._blade_degrees) self._num_blades = len(self._blades) self._max_degree = self._blade_degrees.max() # [Blades, Blades, Blades]
_list = get_cayley_tensor(self.metric, self._bases, self._blades)
0
2023-10-07 13:34:07+00:00
8k
Graph-COM/GDL_DS
src/apis/get_baseline.py
[ { "identifier": "VREx", "path": "src/baselines/VREx.py", "snippet": "class VREx(ERM):\n \"\"\"\n Original Ppaer:\n @inproceedings{krueger2021out,\n title={Out-of-distribution generalization via risk extrapolation (rex)},\n author={Krueger, David and Caballero, Ethan and Jacobsen, Joer...
from src.baselines import ERM, DIR, MixUp, GroupDRO, LRIBern, VREx, Coral, DANN, DomainAdversarialLoss from src.utils import * import torch
6,231
def get_baseline(setting, method_name, clf, config, seed, model_dir=None): """ get baseline and optimizer for running Args: setting: No-Info, O-Feature, and Par-Label settings mentioned in our paper; method_name: We select ERM, VREx, GroupDRO, MixUp, DIR, LRI (No-Info Level); Coral, DANN (O-Feature); and TL (Par-Label) methods; clf: The used GDL model; config: config about models, algorithms ond optimizers for running; seed: random seed; model_dir: path of models to be loaded for model fine-tuning. Returns: baseline and optimizer """ metrics = config['data']['metrics'] criterion = torch.nn.BCEWithLogitsLoss(reduction="mean") if metrics != 'mae' else torch.nn.modules.loss.MSELoss() # Criterion of some algos are specified. optimizer = get_wp_optimizer(clf, config['optimizer']) # optimizer of DIR, LRI, DANN should be specified. if method_name == 'erm': if setting == "Par-Label": assert model_dir is not None clf = load_model(seed, deepcopy(clf), model_dir, metrics).to(next(clf.parameters()).device) optimizer = get_wp_optimizer(clf, config['optimizer']) baseline = ERM(clf, criterion) elif method_name == 'lri_bern': extractor = ExtractorMLP(config['model'][clf.model_name]['hidden_size'], config[method_name]).to( next(clf.parameters()).device) optimizer = get_optimizer(clf, extractor, config['optimizer']) baseline = LRIBern(clf, extractor, criterion, config['lri_bern']) elif method_name == 'mixup': baseline = MixUp(clf, criterion, config['mixup']) elif method_name == 'dir': extractor = ExtractorMLP(config['model'][clf.model_name]['hidden_size'] * 2, config[method_name]).to( next(clf.parameters()).device) baseline = DIR(clf, extractor, criterion, config['dir']) optimizer = get_dir_optimizer(clf, extractor, config['optimizer'], config['dir']) elif method_name == 'groupdro': criterion = torch.nn.BCEWithLogitsLoss(reduction="none") if metrics != 'mae' else torch.nn.modules.loss.MSELoss(reduction="none") baseline = GroupDRO(clf, criterion, config['groupdro']) elif method_name == 'VREx': criterion = torch.nn.BCEWithLogitsLoss(reduction="none") if metrics != 'mae' else torch.nn.modules.loss.MSELoss(reduction="none") baseline = VREx(clf, criterion, config['VREx']) elif method_name == 'coral': baseline = Coral(clf, criterion, config[method_name]) elif method_name == 'DANN': disc = domain_disc(config['model'][clf.model_name]['hidden_size'], config[method_name]).to( next(clf.parameters()).device) domain_adv = DomainAdversarialLoss(disc, criterion).to(next(clf.parameters()).device) optimizer = get_dann_optimizer(clf, disc, config['optimizer'])
def get_baseline(setting, method_name, clf, config, seed, model_dir=None): """ get baseline and optimizer for running Args: setting: No-Info, O-Feature, and Par-Label settings mentioned in our paper; method_name: We select ERM, VREx, GroupDRO, MixUp, DIR, LRI (No-Info Level); Coral, DANN (O-Feature); and TL (Par-Label) methods; clf: The used GDL model; config: config about models, algorithms ond optimizers for running; seed: random seed; model_dir: path of models to be loaded for model fine-tuning. Returns: baseline and optimizer """ metrics = config['data']['metrics'] criterion = torch.nn.BCEWithLogitsLoss(reduction="mean") if metrics != 'mae' else torch.nn.modules.loss.MSELoss() # Criterion of some algos are specified. optimizer = get_wp_optimizer(clf, config['optimizer']) # optimizer of DIR, LRI, DANN should be specified. if method_name == 'erm': if setting == "Par-Label": assert model_dir is not None clf = load_model(seed, deepcopy(clf), model_dir, metrics).to(next(clf.parameters()).device) optimizer = get_wp_optimizer(clf, config['optimizer']) baseline = ERM(clf, criterion) elif method_name == 'lri_bern': extractor = ExtractorMLP(config['model'][clf.model_name]['hidden_size'], config[method_name]).to( next(clf.parameters()).device) optimizer = get_optimizer(clf, extractor, config['optimizer']) baseline = LRIBern(clf, extractor, criterion, config['lri_bern']) elif method_name == 'mixup': baseline = MixUp(clf, criterion, config['mixup']) elif method_name == 'dir': extractor = ExtractorMLP(config['model'][clf.model_name]['hidden_size'] * 2, config[method_name]).to( next(clf.parameters()).device) baseline = DIR(clf, extractor, criterion, config['dir']) optimizer = get_dir_optimizer(clf, extractor, config['optimizer'], config['dir']) elif method_name == 'groupdro': criterion = torch.nn.BCEWithLogitsLoss(reduction="none") if metrics != 'mae' else torch.nn.modules.loss.MSELoss(reduction="none") baseline = GroupDRO(clf, criterion, config['groupdro']) elif method_name == 'VREx': criterion = torch.nn.BCEWithLogitsLoss(reduction="none") if metrics != 'mae' else torch.nn.modules.loss.MSELoss(reduction="none") baseline = VREx(clf, criterion, config['VREx']) elif method_name == 'coral': baseline = Coral(clf, criterion, config[method_name]) elif method_name == 'DANN': disc = domain_disc(config['model'][clf.model_name]['hidden_size'], config[method_name]).to( next(clf.parameters()).device) domain_adv = DomainAdversarialLoss(disc, criterion).to(next(clf.parameters()).device) optimizer = get_dann_optimizer(clf, disc, config['optimizer'])
baseline = DANN(clf, domain_adv, criterion, config[method_name])
7
2023-10-12 02:26:10+00:00
8k
cheginit/curviriver
curviriver/curvilinear.py
[ { "identifier": "smoothing", "path": "curviriver/smoothing.py", "snippet": " GDFTYPE = TypeVar(\"GDFTYPE\", gpd.GeoDataFrame, gpd.GeoSeries)\n CRSTYPE = Union[int, str, pyproj.CRS]\nclass Spline:\nclass GeoBSpline:\n def line(self) -> LineString:\ndef _adjust_boundaries(arr: FloatArray) -> Floa...
from typing import TYPE_CHECKING, Union, cast from scipy.spatial import Voronoi from shapely import ( LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, ops, ) from curviriver import smoothing from curviriver.exceptions import ( InputRangeError, InputTypeError, LineIntersectionError, NoIntersectionError, NoMainCenterlineError, TooFewRidgesError, ) import geopandas as gpd import networkx as nx import numpy as np import numpy.typing as npt import pandas as pd import pyproj import shapely
3,745
------- shapely.LineString Centerline of the input geometry """ centerlines = [] centerline = None for c in np.linspace(0.1, 1, 10): centerline_interp = geometry.area / geometry.length * c centerlines.append( _poly_centerline(geometry, centerline_interp).simplify(centerline_interp) ) if isinstance(centerlines[-1], LineString): centerline = centerlines[-1] break if centerline is None: centerline = _longest_path(centerlines[-1]) return line_extension(centerline, geometry) def __get_idx(d_sp: npt.NDArray[np.float64], distance: float) -> npt.NDArray[np.int64]: """Get the index of the closest points based on a given distance.""" dis = pd.DataFrame(d_sp, columns=["distance"]).reset_index() bins = np.arange(0, dis["distance"].max() + distance, distance) grouper = pd.cut(dis["distance"], bins) idx = dis.groupby(grouper, observed=True).last()["index"].to_numpy("int64") return np.append(0, idx) def __get_spline_params( line: LineString, n_seg: int, distance: float, crs: CRSTYPE ) -> tuple[ npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.float64], ]: """Get Spline parameters (x, y, phi).""" _n_seg = n_seg spline = smoothing.smooth_linestring(line, crs, _n_seg, degree=5) idx = __get_idx(spline.distance, distance) while np.isnan(idx).any(): _n_seg *= 2 spline = smoothing.smooth_linestring(line, crs, _n_seg, degree=5) idx = __get_idx(spline.distance, distance) return spline.x[idx], spline.y[idx], spline.phi[idx], spline.distance[idx] def __get_perpendicular( line: LineString, n_seg: int, distance: float, half_width: float, crs: str | int | pyproj.CRS ) -> list[LineString]: """Get perpendiculars to a line.""" x, y, phi, dis = __get_spline_params(line, n_seg, distance, crs) x_l = x - half_width * np.sin(phi) x_r = x + half_width * np.sin(phi) y_l = y + half_width * np.cos(phi) y_r = y - half_width * np.cos(phi) if np.diff(dis)[-1] < 0.25 * distance: x_l = np.delete(x_l, -2) x_r = np.delete(x_r, -2) y_l = np.delete(y_l, -2) y_r = np.delete(y_r, -2) return [LineString([(x1, y1), (x2, y2)]) for x1, y1, x2, y2 in zip(x_l, y_l, x_r, y_r)] def line_xsection(line: LineString, distance: float, width: float, crs: CRSTYPE) -> gpd.GeoSeries: """Get cross-sections along the line at a given spacing. Parameters ---------- line : shapely.LineString A line along which the cross-sections will be generated. distance : float The distance between two consecutive cross-sections. width : float The width of the cross-section. crs : str or int or pyproj.CRS The CRS of the input line. Using projected CRS is highly recommended. Returns ------- geopandas.GeoSeries Cross-sections along the line, sorted by line direction. """ n_seg = int(np.ceil(line.length / distance)) * 100 half_width = width * 0.5 main_split = __get_perpendicular(line, n_seg, distance, half_width, crs) return gpd.GeoSeries(main_split, crs=pyproj.CRS(crs)) def poly_segmentize( poly: shapely.Polygon, crs: CRSTYPE, spacing_streamwise: float, xs_npts: int, ) -> gpd.GeoSeries: """Segmentize a polygon into a curvilinear grid. Parameters ---------- poly : shapely.Polygon Polygon to convert to a grid of transects. crs : int, str, or pyproj.CRS Coordinate reference system of the polygon. Using projected CRS is highly recommended. spacing_streamwise : float Spacing between cross-sections along the polygon's centerline. xs_npts : int Number of points along each cross-section. Returns ------- gpd.GeoSeries Cross-sections as a GeoSeries of LineStrings. """ if not isinstance(poly, Polygon): raise InputTypeError("poly", "Polygon") centerline = poly_centerline(poly) if spacing_streamwise > centerline.length:
"""Generate curvilinear mesh from a polygon.""" from __future__ import annotations if TYPE_CHECKING: CRSTYPE = Union[int, str, pyproj.CRS] __all__ = ["poly_centerline", "line_extension", "line_xsection", "poly_segmentize"] def _interpolate_line( line: LinearRing, x_min: float, y_min: float, interpolation_distance: float ) -> list[tuple[float, float]]: first_point = (line.xy[0][0] - x_min, line.xy[1][0] - y_min) last_point = (line.xy[0][-1] - x_min, line.xy[1][-1] - y_min) intermediate_points = [] length_tot = line.length distance = interpolation_distance while distance < length_tot: point = line.interpolate(distance) intermediate_points.append((point.x - x_min, point.y - y_min)) distance += interpolation_distance return [first_point, *intermediate_points, last_point] def _poly_centerline( geometry: Polygon | MultiPolygon, interpolation_distance: float ) -> MultiLineString: """Create centerline from a polygon. This function is based on the `Centerline <https://github.com/fitodic/centerline>`__ package (MIT License). Parameters ---------- geometry : shapely.Polygon or shapely.MultiPolygon Input geometry which can be either ``Polygon``` or ``MultiPolygon``. interpolation_distance : float Densify the input geometry's border by placing additional points at this distance. Returns ------- shapely.MultiLineString Centerline of the input geometry """ if not isinstance(geometry, (Polygon, MultiPolygon)): raise InputTypeError("line", "Polygon or MultiPolygon") x_min = np.floor(min(geometry.envelope.exterior.xy[0])) y_min = np.floor(min(geometry.envelope.exterior.xy[1])) polygons = geometry.geoms if isinstance(geometry, MultiPolygon) else [geometry] points = [] for poly in polygons: points.extend(_interpolate_line(poly.exterior, x_min, y_min, interpolation_distance)) if poly.interiors: points.extend( _interpolate_line(pts, x_min, y_min, interpolation_distance) for pts in poly.interiors ) voronoi_diagram = Voronoi(np.array(points, "f8")) vertices = voronoi_diagram.vertices ridges = voronoi_diagram.ridge_vertices c_min = np.array([x_min, y_min]) linestrings = [] for ridge in ridges: # Check if the ridge is finite if -1 not in ridge: line = LineString((vertices[ridge[0]] + c_min, vertices[ridge[1]] + c_min)) if line.within(geometry) and line.coords[0]: linestrings.append(line) if len(linestrings) < 2: raise TooFewRidgesError return shapely.line_merge(shapely.unary_union(linestrings)) def _extraplolation(p1: tuple[float, float], p2: tuple[float, float]) -> LineString: """Create a line extrapolated in p1 -> p2 direction.""" ratio = 2 a = p1 b = (p1[0] + ratio * (p2[0] - p1[0]), p1[1] + ratio * (p2[1] - p1[1])) return LineString([a, b]) def line_extension( line: LineString, poly: Polygon | MultiPolygon, both_ends: bool = True ) -> LineString: """Extend a line to the boundary of a (multi)polygon. Parameters ---------- line : shapely.LineString Line to be extended. poly : shapely.Polygon or shapely.MultiPolygon Polygon to which the line will be extended. both_ends : bool, optional Whether to extend both ends of the line, defaults to ``True``. Returns ------- shapely.LineString Extended line. """ if not isinstance(line, LineString): raise InputTypeError("line", "LineString") if not isinstance(poly, (Polygon, MultiPolygon)): raise InputTypeError("poly", "Polygon or MultiPolygon") if not line.intersects(poly): raise InputTypeError("line", "LineString that intersects with ``poly``") # Only need the boundary intersection p_exterior = LinearRing(poly.exterior.coords) if isinstance(line.intersects(p_exterior), LineString): raise LineIntersectionError l_coords = list(line.coords) l_coords = cast("list[tuple[float, float]]", l_coords) while True: # Only use the last two points l_extraploated = _extraplolation(*l_coords[-2:]) intersection_points = p_exterior.intersection(l_extraploated) if not isinstance(intersection_points, (Point, MultiPoint)): new_point_coords = cast("tuple[float, float]", l_extraploated.coords[1]) l_coords.append(new_point_coords) continue if isinstance(intersection_points, Point): new_point_coords = next(iter(intersection_points.coords)) elif isinstance(intersection_points, MultiPoint): # Use the point closest to the last point last_point = Point(l_coords[-1]) distances = [last_point.distance(point) for point in intersection_points.geoms] new_point_coords = list(intersection_points)[distances.index(min(distances))].coords[0] else: raise NoIntersectionError new_point_coords = cast("tuple[float, float]", new_point_coords) l_coords.append(new_point_coords) break line_extended = LineString(l_coords) if both_ends: return line_extension(line_extended.reverse(), poly, both_ends=False) return line_extended def _longest_path(multi_line: MultiLineString) -> LineString: """Find the longest path among all pairs of leaf nodes using Dijkstra's algorithm.""" net = nx.Graph() # Create graph using only the first and last coordinates of each line for i, line in enumerate(multi_line.geoms): start, end = line.coords[0], line.coords[-1] net.add_edge(start, end, weight=1 / line.length, index=i) # Identify leaf nodes leaf_nodes = [ node for node, deg in nx.degree(net) if deg == 1 # pyright: ignore[reportGeneralTypeIssues] ] longest_path = [] longest_path_length = 0 # Find the longest path among all pairs of leaf nodes for source in leaf_nodes: length, path = nx.single_source_dijkstra(net, source, weight="weight") for target in leaf_nodes: if source == target: continue path_length = length.get(target, None) # pyright: ignore[reportGeneralTypeIssues] if path_length is not None and path_length > longest_path_length: longest_path = path[target] longest_path_length = path_length # Fetch original lines original_lines = [ multi_line.geoms[net[u][v]["index"]] for u, v in zip(longest_path[:-1], longest_path[1:]) ] main_line = ops.linemerge(original_lines) if isinstance(main_line, MultiLineString): raise NoMainCenterlineError return main_line def poly_centerline(geometry: Polygon) -> LineString: """Create centerline from a polygon. This function is based on the `Centerline <https://github.com/fitodic/centerline>`__ package (MIT License). Parameters ---------- geometry : shapely.Polygon or shapely.MultiPolygon Input geometry which can be either ``Polygon``` or ``MultiPolygon``. Returns ------- shapely.LineString Centerline of the input geometry """ centerlines = [] centerline = None for c in np.linspace(0.1, 1, 10): centerline_interp = geometry.area / geometry.length * c centerlines.append( _poly_centerline(geometry, centerline_interp).simplify(centerline_interp) ) if isinstance(centerlines[-1], LineString): centerline = centerlines[-1] break if centerline is None: centerline = _longest_path(centerlines[-1]) return line_extension(centerline, geometry) def __get_idx(d_sp: npt.NDArray[np.float64], distance: float) -> npt.NDArray[np.int64]: """Get the index of the closest points based on a given distance.""" dis = pd.DataFrame(d_sp, columns=["distance"]).reset_index() bins = np.arange(0, dis["distance"].max() + distance, distance) grouper = pd.cut(dis["distance"], bins) idx = dis.groupby(grouper, observed=True).last()["index"].to_numpy("int64") return np.append(0, idx) def __get_spline_params( line: LineString, n_seg: int, distance: float, crs: CRSTYPE ) -> tuple[ npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.float64], ]: """Get Spline parameters (x, y, phi).""" _n_seg = n_seg spline = smoothing.smooth_linestring(line, crs, _n_seg, degree=5) idx = __get_idx(spline.distance, distance) while np.isnan(idx).any(): _n_seg *= 2 spline = smoothing.smooth_linestring(line, crs, _n_seg, degree=5) idx = __get_idx(spline.distance, distance) return spline.x[idx], spline.y[idx], spline.phi[idx], spline.distance[idx] def __get_perpendicular( line: LineString, n_seg: int, distance: float, half_width: float, crs: str | int | pyproj.CRS ) -> list[LineString]: """Get perpendiculars to a line.""" x, y, phi, dis = __get_spline_params(line, n_seg, distance, crs) x_l = x - half_width * np.sin(phi) x_r = x + half_width * np.sin(phi) y_l = y + half_width * np.cos(phi) y_r = y - half_width * np.cos(phi) if np.diff(dis)[-1] < 0.25 * distance: x_l = np.delete(x_l, -2) x_r = np.delete(x_r, -2) y_l = np.delete(y_l, -2) y_r = np.delete(y_r, -2) return [LineString([(x1, y1), (x2, y2)]) for x1, y1, x2, y2 in zip(x_l, y_l, x_r, y_r)] def line_xsection(line: LineString, distance: float, width: float, crs: CRSTYPE) -> gpd.GeoSeries: """Get cross-sections along the line at a given spacing. Parameters ---------- line : shapely.LineString A line along which the cross-sections will be generated. distance : float The distance between two consecutive cross-sections. width : float The width of the cross-section. crs : str or int or pyproj.CRS The CRS of the input line. Using projected CRS is highly recommended. Returns ------- geopandas.GeoSeries Cross-sections along the line, sorted by line direction. """ n_seg = int(np.ceil(line.length / distance)) * 100 half_width = width * 0.5 main_split = __get_perpendicular(line, n_seg, distance, half_width, crs) return gpd.GeoSeries(main_split, crs=pyproj.CRS(crs)) def poly_segmentize( poly: shapely.Polygon, crs: CRSTYPE, spacing_streamwise: float, xs_npts: int, ) -> gpd.GeoSeries: """Segmentize a polygon into a curvilinear grid. Parameters ---------- poly : shapely.Polygon Polygon to convert to a grid of transects. crs : int, str, or pyproj.CRS Coordinate reference system of the polygon. Using projected CRS is highly recommended. spacing_streamwise : float Spacing between cross-sections along the polygon's centerline. xs_npts : int Number of points along each cross-section. Returns ------- gpd.GeoSeries Cross-sections as a GeoSeries of LineStrings. """ if not isinstance(poly, Polygon): raise InputTypeError("poly", "Polygon") centerline = poly_centerline(poly) if spacing_streamwise > centerline.length:
raise InputRangeError(
1
2023-10-13 17:41:11+00:00
8k
THUKElab/CLEME
tests/test_cleme.py
[ { "identifier": "M2DataReader", "path": "cleme/data.py", "snippet": "class M2DataReader(DataReader):\n def read(\n self, file_input: str,\n max_sample: int = -1,\n max_target: int = -1,\n ) -> Dataset:\n data, tgt_tokens_list, edit_lines_list, edit_objs_list...
import os import sys import unittest from cleme.data import M2DataReader from cleme.cleme import DependentChunkMetric, IndependentChunkMetric
3,696
sys.path.append(f"{os.path.dirname(__file__)}/../") class TestCLEME(unittest.TestCase): def setUp(self) -> None: self.reader = M2DataReader() # Read M2 file self.dataset_ref = self.reader.read(f"{os.path.dirname(__file__)}/examples/conll14.errant") self.dataset_hyp = self.reader.read(f"{os.path.dirname(__file__)}/examples/conll14-AMU.errant") print("Example of reference", self.dataset_ref[-1]) print("Example of hypothesis", self.dataset_hyp[-1]) def test_demo(self): # Read M2 file dataset_ref = self.reader.read(f"{os.path.dirname(__file__)}/examples/demo.errant") dataset_hyp = self.reader.read(f"{os.path.dirname(__file__)}/examples/demo-AMU.errant") print(len(dataset_ref), len(dataset_hyp)) print("Example of reference", dataset_ref[-1]) print("Example of hypothesis", dataset_hyp[-1]) # Evaluate using CLEME_dependent config_dependent = { "tp": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": False}, "fp": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": True}, "fn": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": False}, } metric_dependent = DependentChunkMetric(weigher_config=config_dependent) score, results = metric_dependent.evaluate(dataset_hyp, dataset_ref) print(f"==================== Evaluate Demo ====================") print(score) # Visualize metric_dependent.visualize(dataset_ref, dataset_hyp) def test_cleme_dependent(self): # Read M2 file dataset_ref = self.dataset_ref dataset_hyp = self.dataset_hyp # Evaluate using CLEME_dependent config = { "tp": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": False}, "fp": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": True}, "fn": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": False}, } # No length weighting # config = { # "tp": {"alpha": 2.0, "min_value": 1.0, "max_value": 1.0, "reverse": False}, # "fp": {"alpha": 2.0, "min_value": 1.0, "max_value": 1.0, "reverse": True}, # "fn": {"alpha": 2.0, "min_value": 1.0, "max_value": 1.0, "reverse": False}, # } metric_dependent = DependentChunkMetric(weigher_config=config) score, results = metric_dependent.evaluate(dataset_hyp, dataset_ref) print(f"==================== Evaluate using CLEME_dependent ====================") print(score) def test_cleme_independent(self): # Read M2 file dataset_ref = self.dataset_ref dataset_hyp = self.dataset_hyp # Evaluate using CLEME_independent # config = { # "tp": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": False}, # "fp": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": True}, # "fn": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": False}, # } # No length weighting config = { "tp": {"alpha": 2.0, "min_value": 1.0, "max_value": 1.0, "reverse": False}, "fp": {"alpha": 2.0, "min_value": 1.0, "max_value": 1.0, "reverse": True}, "fn": {"alpha": 2.0, "min_value": 1.0, "max_value": 1.0, "reverse": False}, }
sys.path.append(f"{os.path.dirname(__file__)}/../") class TestCLEME(unittest.TestCase): def setUp(self) -> None: self.reader = M2DataReader() # Read M2 file self.dataset_ref = self.reader.read(f"{os.path.dirname(__file__)}/examples/conll14.errant") self.dataset_hyp = self.reader.read(f"{os.path.dirname(__file__)}/examples/conll14-AMU.errant") print("Example of reference", self.dataset_ref[-1]) print("Example of hypothesis", self.dataset_hyp[-1]) def test_demo(self): # Read M2 file dataset_ref = self.reader.read(f"{os.path.dirname(__file__)}/examples/demo.errant") dataset_hyp = self.reader.read(f"{os.path.dirname(__file__)}/examples/demo-AMU.errant") print(len(dataset_ref), len(dataset_hyp)) print("Example of reference", dataset_ref[-1]) print("Example of hypothesis", dataset_hyp[-1]) # Evaluate using CLEME_dependent config_dependent = { "tp": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": False}, "fp": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": True}, "fn": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": False}, } metric_dependent = DependentChunkMetric(weigher_config=config_dependent) score, results = metric_dependent.evaluate(dataset_hyp, dataset_ref) print(f"==================== Evaluate Demo ====================") print(score) # Visualize metric_dependent.visualize(dataset_ref, dataset_hyp) def test_cleme_dependent(self): # Read M2 file dataset_ref = self.dataset_ref dataset_hyp = self.dataset_hyp # Evaluate using CLEME_dependent config = { "tp": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": False}, "fp": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": True}, "fn": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": False}, } # No length weighting # config = { # "tp": {"alpha": 2.0, "min_value": 1.0, "max_value": 1.0, "reverse": False}, # "fp": {"alpha": 2.0, "min_value": 1.0, "max_value": 1.0, "reverse": True}, # "fn": {"alpha": 2.0, "min_value": 1.0, "max_value": 1.0, "reverse": False}, # } metric_dependent = DependentChunkMetric(weigher_config=config) score, results = metric_dependent.evaluate(dataset_hyp, dataset_ref) print(f"==================== Evaluate using CLEME_dependent ====================") print(score) def test_cleme_independent(self): # Read M2 file dataset_ref = self.dataset_ref dataset_hyp = self.dataset_hyp # Evaluate using CLEME_independent # config = { # "tp": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": False}, # "fp": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": True}, # "fn": {"alpha": 2.0, "min_value": 0.75, "max_value": 1.25, "reverse": False}, # } # No length weighting config = { "tp": {"alpha": 2.0, "min_value": 1.0, "max_value": 1.0, "reverse": False}, "fp": {"alpha": 2.0, "min_value": 1.0, "max_value": 1.0, "reverse": True}, "fn": {"alpha": 2.0, "min_value": 1.0, "max_value": 1.0, "reverse": False}, }
metric_independent = IndependentChunkMetric(weigher_config=config)
2
2023-10-07 12:32:04+00:00
8k
mytk2012/YOLOV8_INT8_TRT
ultralytics/trackers/byte_tracker.py
[ { "identifier": "BaseTrack", "path": "ultralytics/trackers/basetrack.py", "snippet": "class BaseTrack:\n \"\"\"Base class for object tracking, handling basic track attributes and operations.\"\"\"\n\n _count = 0\n\n track_id = 0\n is_activated = False\n state = TrackState.New\n\n histo...
import numpy as np from .basetrack import BaseTrack, TrackState from .utils import matching from .utils.kalman_filter import KalmanFilterXYAH
4,743
self.state = TrackState.Tracked self.is_activated = True self.score = new_track.score self.cls = new_track.cls self.idx = new_track.idx def convert_coords(self, tlwh): """Convert a bounding box's top-left-width-height format to its x-y-angle-height equivalent.""" return self.tlwh_to_xyah(tlwh) @property def tlwh(self): """Get current position in bounding box format `(top left x, top left y, width, height)`. """ if self.mean is None: return self._tlwh.copy() ret = self.mean[:4].copy() ret[2] *= ret[3] ret[:2] -= ret[2:] / 2 return ret @property def tlbr(self): """Convert bounding box to format `(min x, min y, max x, max y)`, i.e., `(top left, bottom right)`. """ ret = self.tlwh.copy() ret[2:] += ret[:2] return ret @staticmethod def tlwh_to_xyah(tlwh): """Convert bounding box to format `(center x, center y, aspect ratio, height)`, where the aspect ratio is `width / height`. """ ret = np.asarray(tlwh).copy() ret[:2] += ret[2:] / 2 ret[2] /= ret[3] return ret @staticmethod def tlbr_to_tlwh(tlbr): """Converts top-left bottom-right format to top-left width height format.""" ret = np.asarray(tlbr).copy() ret[2:] -= ret[:2] return ret @staticmethod def tlwh_to_tlbr(tlwh): """Converts tlwh bounding box format to tlbr format.""" ret = np.asarray(tlwh).copy() ret[2:] += ret[:2] return ret def __repr__(self): """Return a string representation of the BYTETracker object with start and end frames and track ID.""" return f'OT_{self.track_id}_({self.start_frame}-{self.end_frame})' class BYTETracker: def __init__(self, args, frame_rate=30): """Initialize a YOLOv8 object to track objects with given arguments and frame rate.""" self.tracked_stracks = [] # type: list[STrack] self.lost_stracks = [] # type: list[STrack] self.removed_stracks = [] # type: list[STrack] self.frame_id = 0 self.args = args self.max_time_lost = int(frame_rate / 30.0 * args.track_buffer) self.kalman_filter = self.get_kalmanfilter() self.reset_id() def update(self, results, img=None): """Updates object tracker with new detections and returns tracked object bounding boxes.""" self.frame_id += 1 activated_stracks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] scores = results.conf bboxes = results.xyxy # Add index bboxes = np.concatenate([bboxes, np.arange(len(bboxes)).reshape(-1, 1)], axis=-1) cls = results.cls remain_inds = scores > self.args.track_high_thresh inds_low = scores > self.args.track_low_thresh inds_high = scores < self.args.track_high_thresh inds_second = np.logical_and(inds_low, inds_high) dets_second = bboxes[inds_second] dets = bboxes[remain_inds] scores_keep = scores[remain_inds] scores_second = scores[inds_second] cls_keep = cls[remain_inds] cls_second = cls[inds_second] detections = self.init_track(dets, scores_keep, cls_keep, img) # Add newly detected tracklets to tracked_stracks unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) # Step 2: First association, with high score detection boxes strack_pool = self.joint_stracks(tracked_stracks, self.lost_stracks) # Predict the current location with KF self.multi_predict(strack_pool) if hasattr(self, 'gmc') and img is not None: warp = self.gmc.apply(img, dets) STrack.multi_gmc(strack_pool, warp) STrack.multi_gmc(unconfirmed, warp) dists = self.get_dists(strack_pool, detections)
# Ultralytics YOLO 🚀, AGPL-3.0 license class STrack(BaseTrack): shared_kalman = KalmanFilterXYAH() def __init__(self, tlwh, score, cls): """wait activate.""" self._tlwh = np.asarray(self.tlbr_to_tlwh(tlwh[:-1]), dtype=np.float32) self.kalman_filter = None self.mean, self.covariance = None, None self.is_activated = False self.score = score self.tracklet_len = 0 self.cls = cls self.idx = tlwh[-1] def predict(self): """Predicts mean and covariance using Kalman filter.""" mean_state = self.mean.copy() if self.state != TrackState.Tracked: mean_state[7] = 0 self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance) @staticmethod def multi_predict(stracks): """Perform multi-object predictive tracking using Kalman filter for given stracks.""" if len(stracks) <= 0: return multi_mean = np.asarray([st.mean.copy() for st in stracks]) multi_covariance = np.asarray([st.covariance for st in stracks]) for i, st in enumerate(stracks): if st.state != TrackState.Tracked: multi_mean[i][7] = 0 multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance) for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)): stracks[i].mean = mean stracks[i].covariance = cov @staticmethod def multi_gmc(stracks, H=np.eye(2, 3)): """Update state tracks positions and covariances using a homography matrix.""" if len(stracks) > 0: multi_mean = np.asarray([st.mean.copy() for st in stracks]) multi_covariance = np.asarray([st.covariance for st in stracks]) R = H[:2, :2] R8x8 = np.kron(np.eye(4, dtype=float), R) t = H[:2, 2] for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)): mean = R8x8.dot(mean) mean[:2] += t cov = R8x8.dot(cov).dot(R8x8.transpose()) stracks[i].mean = mean stracks[i].covariance = cov def activate(self, kalman_filter, frame_id): """Start a new tracklet.""" self.kalman_filter = kalman_filter self.track_id = self.next_id() self.mean, self.covariance = self.kalman_filter.initiate(self.convert_coords(self._tlwh)) self.tracklet_len = 0 self.state = TrackState.Tracked if frame_id == 1: self.is_activated = True self.frame_id = frame_id self.start_frame = frame_id def re_activate(self, new_track, frame_id, new_id=False): """Reactivates a previously lost track with a new detection.""" self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance, self.convert_coords(new_track.tlwh)) self.tracklet_len = 0 self.state = TrackState.Tracked self.is_activated = True self.frame_id = frame_id if new_id: self.track_id = self.next_id() self.score = new_track.score self.cls = new_track.cls self.idx = new_track.idx def update(self, new_track, frame_id): """ Update a matched track :type new_track: STrack :type frame_id: int :return: """ self.frame_id = frame_id self.tracklet_len += 1 new_tlwh = new_track.tlwh self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance, self.convert_coords(new_tlwh)) self.state = TrackState.Tracked self.is_activated = True self.score = new_track.score self.cls = new_track.cls self.idx = new_track.idx def convert_coords(self, tlwh): """Convert a bounding box's top-left-width-height format to its x-y-angle-height equivalent.""" return self.tlwh_to_xyah(tlwh) @property def tlwh(self): """Get current position in bounding box format `(top left x, top left y, width, height)`. """ if self.mean is None: return self._tlwh.copy() ret = self.mean[:4].copy() ret[2] *= ret[3] ret[:2] -= ret[2:] / 2 return ret @property def tlbr(self): """Convert bounding box to format `(min x, min y, max x, max y)`, i.e., `(top left, bottom right)`. """ ret = self.tlwh.copy() ret[2:] += ret[:2] return ret @staticmethod def tlwh_to_xyah(tlwh): """Convert bounding box to format `(center x, center y, aspect ratio, height)`, where the aspect ratio is `width / height`. """ ret = np.asarray(tlwh).copy() ret[:2] += ret[2:] / 2 ret[2] /= ret[3] return ret @staticmethod def tlbr_to_tlwh(tlbr): """Converts top-left bottom-right format to top-left width height format.""" ret = np.asarray(tlbr).copy() ret[2:] -= ret[:2] return ret @staticmethod def tlwh_to_tlbr(tlwh): """Converts tlwh bounding box format to tlbr format.""" ret = np.asarray(tlwh).copy() ret[2:] += ret[:2] return ret def __repr__(self): """Return a string representation of the BYTETracker object with start and end frames and track ID.""" return f'OT_{self.track_id}_({self.start_frame}-{self.end_frame})' class BYTETracker: def __init__(self, args, frame_rate=30): """Initialize a YOLOv8 object to track objects with given arguments and frame rate.""" self.tracked_stracks = [] # type: list[STrack] self.lost_stracks = [] # type: list[STrack] self.removed_stracks = [] # type: list[STrack] self.frame_id = 0 self.args = args self.max_time_lost = int(frame_rate / 30.0 * args.track_buffer) self.kalman_filter = self.get_kalmanfilter() self.reset_id() def update(self, results, img=None): """Updates object tracker with new detections and returns tracked object bounding boxes.""" self.frame_id += 1 activated_stracks = [] refind_stracks = [] lost_stracks = [] removed_stracks = [] scores = results.conf bboxes = results.xyxy # Add index bboxes = np.concatenate([bboxes, np.arange(len(bboxes)).reshape(-1, 1)], axis=-1) cls = results.cls remain_inds = scores > self.args.track_high_thresh inds_low = scores > self.args.track_low_thresh inds_high = scores < self.args.track_high_thresh inds_second = np.logical_and(inds_low, inds_high) dets_second = bboxes[inds_second] dets = bboxes[remain_inds] scores_keep = scores[remain_inds] scores_second = scores[inds_second] cls_keep = cls[remain_inds] cls_second = cls[inds_second] detections = self.init_track(dets, scores_keep, cls_keep, img) # Add newly detected tracklets to tracked_stracks unconfirmed = [] tracked_stracks = [] # type: list[STrack] for track in self.tracked_stracks: if not track.is_activated: unconfirmed.append(track) else: tracked_stracks.append(track) # Step 2: First association, with high score detection boxes strack_pool = self.joint_stracks(tracked_stracks, self.lost_stracks) # Predict the current location with KF self.multi_predict(strack_pool) if hasattr(self, 'gmc') and img is not None: warp = self.gmc.apply(img, dets) STrack.multi_gmc(strack_pool, warp) STrack.multi_gmc(unconfirmed, warp) dists = self.get_dists(strack_pool, detections)
matches, u_track, u_detection = matching.linear_assignment(dists, thresh=self.args.match_thresh)
2
2023-10-14 09:14:04+00:00
8k
Wisely-ingenieria/ws-agents-workshop
05_multitool_agent_example.py
[ { "identifier": "Agent", "path": "agents/agent.py", "snippet": "class Agent:\n def __init__(self, tools):\n self.tools = tools\n self.log = Logger()\n self.memory = RelevantMemories()\n\n def get_tools_schema(self):\n final_answer_schema = {\n \"name\": \"fin...
import streamlit as st from agents.agent import Agent from agents.tools.fs import SearchDirectory, ListDirectory, ViewFile from agents.tools.llm import QueryFile from agents.tools.github import GetUserInfo, GetRepositories, CloneRepo, CreateIssue, GetIssueDetails, GetIssues
6,163
if "agent" not in st.session_state: st.session_state["agent"] = Agent( [ GetUserInfo(), GetRepositories(), CloneRepo(), CreateIssue(), GetIssueDetails(), GetIssues(), ListDirectory(), SearchDirectory(), ViewFile(),
if "agent" not in st.session_state: st.session_state["agent"] = Agent( [ GetUserInfo(), GetRepositories(), CloneRepo(), CreateIssue(), GetIssueDetails(), GetIssues(), ListDirectory(), SearchDirectory(), ViewFile(),
QueryFile(),
4
2023-10-12 14:37:38+00:00
8k
xuuHuang/IMTLab
src/imt_environment/imt_system/leca/leca_transformer.py
[ { "identifier": "LecaEncoder", "path": "src/imt_environment/imt_system/leca/leca_encoder.py", "snippet": "class LecaEncoder(TransformerEncoderBase):\n def __init__(self, cfg, dictionary, embed_tokens, return_fc=False):\n super().__init__(cfg, dictionary, embed_tokens, return_fc)\n self....
from dataclasses import dataclass, field from fairseq.dataclass.utils import gen_parser_from_dataclass from fairseq.models import ( register_model, register_model_architecture, ) from fairseq.models.transformer.transformer_config import ( TransformerConfig, DEFAULT_MAX_SOURCE_POSITIONS, DEFAULT_MAX_TARGET_POSITIONS, DEFAULT_MIN_PARAMS_TO_WRAP, ) from fairseq.models.transformer.transformer_base import ( TransformerModelBase, ) from fairseq.models.transformer.transformer_legacy import ( base_architecture, transformer_wmt_en_de_big ) from .leca_encoder import LecaEncoder from .leca_decoder import LecaDecoder
4,407
@dataclass class LecaTransformerConfig(TransformerConfig): use_ptr: bool = field( default=True, metadata={"help": "set to use pointer network"} ) max_constraints_num: int = field( default=10, metadata={"help": "maximum constrained phrases number"} ) @register_model("leca") class LecaTransformer(TransformerModelBase): def __init__(self, args, encoder, decoder): cfg = LecaTransformerConfig.from_namespace(args) super().__init__(cfg, encoder, decoder) self.args = args @classmethod def add_args(cls, parser): """Add model-specific arguments to the parser.""" # we want to build the args recursively in this case. # do not set defaults so that settings defaults from various architectures still works gen_parser_from_dataclass( parser, TransformerConfig(), delete_default=True, with_prefix="" ) @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure all arguments are present in older models base_architecture(args) if args.encoder_layers_to_keep: args.encoder_layers = len(args.encoder_layers_to_keep.split(",")) if args.decoder_layers_to_keep: args.decoder_layers = len(args.decoder_layers_to_keep.split(",")) if getattr(args, "max_source_positions", None) is None: args.max_source_positions = DEFAULT_MAX_SOURCE_POSITIONS if getattr(args, "max_target_positions", None) is None: args.max_target_positions = DEFAULT_MAX_TARGET_POSITIONS src_dict, tgt_dict = task.source_dictionary, task.target_dictionary if args.share_all_embeddings: if src_dict != tgt_dict: raise ValueError("--share-all-embeddings requires a joined dictionary") if args.encoder_embed_dim != args.decoder_embed_dim: raise ValueError( "--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim" ) if args.decoder_embed_path and ( args.decoder_embed_path != args.encoder_embed_path ): raise ValueError( "--share-all-embeddings not compatible with --decoder-embed-path" ) args.share_decoder_input_output_embed = True if getattr(args, "offload_activations", False): args.checkpoint_activations = True # offloading implies checkpointing if not args.share_all_embeddings: args.min_params_to_wrap = getattr( args, "min_params_to_wrap", DEFAULT_MIN_PARAMS_TO_WRAP ) cfg = LecaTransformerConfig.from_namespace(args) return super().build_model(cfg, task) @classmethod def build_encoder(cls, cfg, src_dict, embed_tokens): return LecaEncoder(cfg, src_dict, embed_tokens) @classmethod def build_decoder(cls, cfg, tgt_dict, embed_tokens):
@dataclass class LecaTransformerConfig(TransformerConfig): use_ptr: bool = field( default=True, metadata={"help": "set to use pointer network"} ) max_constraints_num: int = field( default=10, metadata={"help": "maximum constrained phrases number"} ) @register_model("leca") class LecaTransformer(TransformerModelBase): def __init__(self, args, encoder, decoder): cfg = LecaTransformerConfig.from_namespace(args) super().__init__(cfg, encoder, decoder) self.args = args @classmethod def add_args(cls, parser): """Add model-specific arguments to the parser.""" # we want to build the args recursively in this case. # do not set defaults so that settings defaults from various architectures still works gen_parser_from_dataclass( parser, TransformerConfig(), delete_default=True, with_prefix="" ) @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure all arguments are present in older models base_architecture(args) if args.encoder_layers_to_keep: args.encoder_layers = len(args.encoder_layers_to_keep.split(",")) if args.decoder_layers_to_keep: args.decoder_layers = len(args.decoder_layers_to_keep.split(",")) if getattr(args, "max_source_positions", None) is None: args.max_source_positions = DEFAULT_MAX_SOURCE_POSITIONS if getattr(args, "max_target_positions", None) is None: args.max_target_positions = DEFAULT_MAX_TARGET_POSITIONS src_dict, tgt_dict = task.source_dictionary, task.target_dictionary if args.share_all_embeddings: if src_dict != tgt_dict: raise ValueError("--share-all-embeddings requires a joined dictionary") if args.encoder_embed_dim != args.decoder_embed_dim: raise ValueError( "--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim" ) if args.decoder_embed_path and ( args.decoder_embed_path != args.encoder_embed_path ): raise ValueError( "--share-all-embeddings not compatible with --decoder-embed-path" ) args.share_decoder_input_output_embed = True if getattr(args, "offload_activations", False): args.checkpoint_activations = True # offloading implies checkpointing if not args.share_all_embeddings: args.min_params_to_wrap = getattr( args, "min_params_to_wrap", DEFAULT_MIN_PARAMS_TO_WRAP ) cfg = LecaTransformerConfig.from_namespace(args) return super().build_model(cfg, task) @classmethod def build_encoder(cls, cfg, src_dict, embed_tokens): return LecaEncoder(cfg, src_dict, embed_tokens) @classmethod def build_decoder(cls, cfg, tgt_dict, embed_tokens):
return LecaDecoder(cfg, tgt_dict, embed_tokens)
1
2023-10-11 13:08:22+00:00
8k
krulllab/DVLAE
lvae/models/lvae.py
[ { "identifier": "crop_img_tensor", "path": "lvae/lib/utils.py", "snippet": "def crop_img_tensor(x, size) -> torch.Tensor:\n \"\"\"Crops a tensor.\n Crops a tensor of shape (batch, channels, h, w) to new height and width\n given by a tuple.\n Args:\n x (torch.Tensor): Input image\n ...
import numpy as np import torch from torch import nn from torch import optim from pytorch_lightning import LightningModule from ..lib.utils import crop_img_tensor, pad_img_tensor from .lvae_layers import ( TopDownLayer, BottomUpLayer, TopDownDeterministicResBlock, BottomUpDeterministicResBlock, )
4,054
# Bottom-up inference: return list of length n_layers (bottom to top) bu_values = self.bottomup_pass(x_pad) # Top-down inference/generation s_code, kl = self.topdown_pass(bu_values) if not self.mode_pred: # Calculate KL divergence kl_sums = [torch.sum(layer) for layer in kl] kl_loss = sum(kl_sums) / float( x.shape[0] * x.shape[1] * x.shape[2] * x.shape[3]) else: kl_loss = None # Restore original image size s_code = crop_img_tensor(s_code, img_size) output = { "kl_loss": kl_loss, "s_code": s_code, } return output def bottomup_pass(self, x): # Bottom-up initial layer x = self.first_bottom_up(x) # Loop from bottom to top layer, store all deterministic nodes we # need in the top-down pass bu_values = [] for i in range(self.n_layers): x = self.bottom_up_layers[i](x) bu_values.append(x) return bu_values def topdown_pass( self, bu_values=None, n_img_prior=None, mode_layers=None, constant_layers=None, forced_latent=None, ): # Default: no layer is sampled from the distribution's mode if mode_layers is None: mode_layers = [] if constant_layers is None: constant_layers = [] # If the bottom-up inference values are not given, don't do # inference, sample from prior instead inference_mode = bu_values is not None # Check consistency of arguments if inference_mode != (n_img_prior is None): msg = ("Number of images for top-down generation has to be given " "if and only if we're not doing inference") raise RuntimeError(msg) # KL divergence of each layer kl = [None] * self.n_layers if forced_latent is None: forced_latent = [None] * self.n_layers # Top-down inference/generation loop out = None for i in reversed(range(self.n_layers)): # If available, get deterministic node from bottom-up inference try: bu_value = bu_values[i] except TypeError: bu_value = None # Whether the current layer should be sampled from the mode use_mode = i in mode_layers constant_out = i in constant_layers # Input for skip connection skip_input = out # TODO or out_pre_residual? or both? # Full top-down layer, including sampling and deterministic part out, kl_elementwise = self.top_down_layers[i]( out, skip_connection_input=skip_input, inference_mode=inference_mode, bu_value=bu_value, n_img_prior=n_img_prior, use_mode=use_mode, force_constant_output=constant_out, forced_latent=forced_latent[i], mode_pred=self.mode_pred, ) kl[i] = kl_elementwise # Final top-down layer out = self.final_top_down(out) return out, kl @torch.no_grad() def sample_from_prior(self, n_images): # Sample from p(z_L) and do top-down generative path # Spatial size of image is given by self.img_shape out, _ = self.topdown_pass(n_img_prior=n_images) generated_s_code = crop_img_tensor(out, self.img_shape) generated_s = self.s_decoder(generated_s_code) generated_x = self.noise_model.sample(generated_s_code) return generated_s, generated_x def pad_input(self, x): """ Pads input x so that its sizes are powers of 2 :param x: :return: Padded tensor """ size = self.get_padded_size(x.size())
class LadderVAE(nn.Module): """Hierarchical variational autoencoder. Parameters ---------- colour_channels : int Number of colour channels in input. img_shape : tuple Spatial dimensions of the input (Height, Width) s_code_channels : int Numer of channels in latent code. z_dims : list Number of feature channels at each layer of the hierarchy. blocks_per_layer : int Number of residual blocks between each latent. n_filters : int Numer of feature channels. learn_top_prior : bool Whether to learn the parameters of topmost prior. res_block_type : string The ordering of operations within each block. See ..lib.nn.ResidualBlock merge_type : string How features from bottom-up pass will be merged with features from top-down pass. See .lvae_layers.MergeLayer stochastic_skip : bool Whether to use skip connections from previous layer of hierarchy. gated : bool Whether to uses forget gate activation. batchnorm : bool Use of batch normalisation. downsample : list Number of times to downsample for each latent variable. mode_pred : bool If false, losses will not be calculated. """ def __init__( self, colour_channels, img_shape, s_code_channels, z_dims=None, blocks_per_layer=1, n_filters=64, learn_top_prior=True, res_block_type="bacbac", merge_type="residual", stochastic_skip=True, gated=True, batchnorm=True, downsampling=None, mode_pred=False, ): if z_dims is None: z_dims = [32] * 12 super().__init__() self.img_shape = tuple(img_shape) self.z_dims = z_dims self.n_layers = len(self.z_dims) self.blocks_per_layer = blocks_per_layer self.n_filters = n_filters self.stochastic_skip = stochastic_skip self.gated = gated self.mode_pred = mode_pred # We need to optimize the s_decoder separately # from the main VAE and noise_model self.automatic_optimization = False # Number of downsampling steps per layer if downsampling is None: downsampling = [0] * self.n_layers # Downsample by a factor of 2 at each downsampling operation self.overall_downscale_factor = np.power(2, sum(downsampling)) assert max(downsampling) <= self.blocks_per_layer assert len(downsampling) == self.n_layers # First bottom-up layer: change num channels self.first_bottom_up = nn.Sequential( nn.Conv2d(colour_channels, n_filters, 5, padding=2, padding_mode="replicate"), nn.Mish(), BottomUpDeterministicResBlock( c_in=n_filters, c_out=n_filters, batchnorm=batchnorm, res_block_type=res_block_type, ), ) # Init lists of layers self.top_down_layers = nn.ModuleList([]) self.bottom_up_layers = nn.ModuleList([]) for i in range(self.n_layers): # Whether this is the top layer is_top = i == self.n_layers - 1 # Add bottom-up deterministic layer at level i. # It's a sequence of residual blocks (BottomUpDeterministicResBlock) # possibly with downsampling between them. self.bottom_up_layers.append( BottomUpLayer( n_res_blocks=self.blocks_per_layer, n_filters=n_filters, downsampling_steps=downsampling[i], batchnorm=batchnorm, res_block_type=res_block_type, gated=gated, )) # Add top-down stochastic layer at level i. # The architecture when doing inference is roughly as follows: # p_params = output of top-down layer above # bu = inferred bottom-up value at this layer # q_params = merge(bu, p_params) # z = stochastic_layer(q_params) # possibly get skip connection from previous top-down layer # top-down deterministic ResNet # # When doing generation only, the value bu is not available, the # merge layer is not used, and z is sampled directly from p_params. self.top_down_layers.append( TopDownLayer( z_dim=z_dims[i], n_res_blocks=blocks_per_layer, n_filters=n_filters, is_top_layer=is_top, downsampling_steps=downsampling[i], merge_type=merge_type, batchnorm=batchnorm, stochastic_skip=stochastic_skip, learn_top_prior=learn_top_prior, top_prior_param_shape=self.get_top_prior_param_shape(), res_block_type=res_block_type, gated=gated, )) # Final top-down layer modules = list() for i in range(blocks_per_layer): modules.append( TopDownDeterministicResBlock( c_in=n_filters, c_out=n_filters if i < (blocks_per_layer - 1) else s_code_channels, batchnorm=batchnorm, res_block_type=res_block_type, gated=gated, )) self.final_top_down = nn.Sequential(*modules) def forward(self, x): # Pad x to have base 2 side lengths to make resampling steps simpler # Save size to crop back down later img_size = x.size()[2:] x_pad = self.pad_input(x) # Bottom-up inference: return list of length n_layers (bottom to top) bu_values = self.bottomup_pass(x_pad) # Top-down inference/generation s_code, kl = self.topdown_pass(bu_values) if not self.mode_pred: # Calculate KL divergence kl_sums = [torch.sum(layer) for layer in kl] kl_loss = sum(kl_sums) / float( x.shape[0] * x.shape[1] * x.shape[2] * x.shape[3]) else: kl_loss = None # Restore original image size s_code = crop_img_tensor(s_code, img_size) output = { "kl_loss": kl_loss, "s_code": s_code, } return output def bottomup_pass(self, x): # Bottom-up initial layer x = self.first_bottom_up(x) # Loop from bottom to top layer, store all deterministic nodes we # need in the top-down pass bu_values = [] for i in range(self.n_layers): x = self.bottom_up_layers[i](x) bu_values.append(x) return bu_values def topdown_pass( self, bu_values=None, n_img_prior=None, mode_layers=None, constant_layers=None, forced_latent=None, ): # Default: no layer is sampled from the distribution's mode if mode_layers is None: mode_layers = [] if constant_layers is None: constant_layers = [] # If the bottom-up inference values are not given, don't do # inference, sample from prior instead inference_mode = bu_values is not None # Check consistency of arguments if inference_mode != (n_img_prior is None): msg = ("Number of images for top-down generation has to be given " "if and only if we're not doing inference") raise RuntimeError(msg) # KL divergence of each layer kl = [None] * self.n_layers if forced_latent is None: forced_latent = [None] * self.n_layers # Top-down inference/generation loop out = None for i in reversed(range(self.n_layers)): # If available, get deterministic node from bottom-up inference try: bu_value = bu_values[i] except TypeError: bu_value = None # Whether the current layer should be sampled from the mode use_mode = i in mode_layers constant_out = i in constant_layers # Input for skip connection skip_input = out # TODO or out_pre_residual? or both? # Full top-down layer, including sampling and deterministic part out, kl_elementwise = self.top_down_layers[i]( out, skip_connection_input=skip_input, inference_mode=inference_mode, bu_value=bu_value, n_img_prior=n_img_prior, use_mode=use_mode, force_constant_output=constant_out, forced_latent=forced_latent[i], mode_pred=self.mode_pred, ) kl[i] = kl_elementwise # Final top-down layer out = self.final_top_down(out) return out, kl @torch.no_grad() def sample_from_prior(self, n_images): # Sample from p(z_L) and do top-down generative path # Spatial size of image is given by self.img_shape out, _ = self.topdown_pass(n_img_prior=n_images) generated_s_code = crop_img_tensor(out, self.img_shape) generated_s = self.s_decoder(generated_s_code) generated_x = self.noise_model.sample(generated_s_code) return generated_s, generated_x def pad_input(self, x): """ Pads input x so that its sizes are powers of 2 :param x: :return: Padded tensor """ size = self.get_padded_size(x.size())
x = pad_img_tensor(x, size)
1
2023-10-10 16:05:08+00:00
8k
Significant-Gravitas/autostandup
scheduler.py
[ { "identifier": "StreaksManager", "path": "streaks/streaks_manager.py", "snippet": "class StreaksManager:\n \"\"\"\n Manages the streaks for team members.\n \"\"\"\n \n def __init__(self, streaks_db: StreaksDB):\n \"\"\"\n Initializes a new StreaksManager instance.\n\n ...
from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.triggers.cron import CronTrigger from streaks.streaks_manager import StreaksManager from team_members.team_member import TeamMember from updates.updates_manager import UpdatesManager from weekly_posts.weekly_post_manager import WeeklyPostManager from typing import Dict, List from datetime import datetime import pytz
6,120
class Scheduler: """Scheduler class to manage timed jobs for sending status requests. Attributes: scheduler: The APScheduler object. job_ids: A dictionary to store lists of job IDs for each member. """ def __init__(self) -> None: """Initialize the Scheduler object and start the APScheduler.""" self.scheduler: AsyncIOScheduler = AsyncIOScheduler() self.job_ids: Dict[int, List[str]] = {} # Store job IDs indexed by member's Discord ID self.weekly_post_job_id = None # To store the ID of the scheduled weekly post job self.scheduler.start()
class Scheduler: """Scheduler class to manage timed jobs for sending status requests. Attributes: scheduler: The APScheduler object. job_ids: A dictionary to store lists of job IDs for each member. """ def __init__(self) -> None: """Initialize the Scheduler object and start the APScheduler.""" self.scheduler: AsyncIOScheduler = AsyncIOScheduler() self.job_ids: Dict[int, List[str]] = {} # Store job IDs indexed by member's Discord ID self.weekly_post_job_id = None # To store the ID of the scheduled weekly post job self.scheduler.start()
def add_job(self, func: callable, member: TeamMember, weekly_post_manager: WeeklyPostManager, streaks_manager: StreaksManager, updates_manager: UpdatesManager) -> None:
3
2023-10-12 02:01:46+00:00
8k
azuline/rose
rose/rule_parser_test.py
[ { "identifier": "AddAction", "path": "rose/rule_parser.py", "snippet": "class AddAction:\n \"\"\"\n Adds a value to the tag. This action is only allowed on multi-value tags. If the value already\n exists, this action No-Ops.\n \"\"\"\n\n value: str" }, { "identifier": "DeleteActio...
import re import click import pytest from rose.rule_parser import ( AddAction, DeleteAction, InvalidRuleError, MatcherPattern, MetadataAction, MetadataMatcher, MetadataRule, ReplaceAction, RuleSyntaxError, SedAction, SplitAction, take, )
6,203
test_err( "tracknumber", """\ Failed to parse matcher, invalid syntax: tracknumber ^ Expected to find ',' or ':', found end of string. """, ) test_err( "tracktitle:Tr:ck", """\ Failed to parse matcher, invalid syntax: tracktitle:Tr:ck ^ Unrecognized flag: Please specify one of the supported flags: `i` (case insensitive). """, ) test_err( "tracktitle::", """\ Failed to parse matcher, invalid syntax: tracktitle:: ^ No flags specified: Please remove this section (by deleting the colon) or specify one of the supported flags: `i` (case insensitive). """, ) test_err( "tracktitle::i:hihi", """\ Failed to parse matcher, invalid syntax: tracktitle::i:hihi ^ Extra input found after end of matcher. Perhaps you meant to escape this colon? """, ) def test_rule_parse_action() -> None: assert MetadataAction.parse( "replace:lalala", matcher=MetadataMatcher(tags=["tracktitle"], pattern=MatcherPattern("haha")), ) == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["tracktitle"], pattern=MatcherPattern("haha"), ) assert MetadataAction.parse("genre::replace:lalala") == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["genre"], pattern=None, ) assert MetadataAction.parse("tracknumber,genre::replace:lalala") == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["tracknumber", "genre"], pattern=None, ) assert MetadataAction.parse("genre:lala::replace:lalala") == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["genre"], pattern=MatcherPattern("lala"), ) assert MetadataAction.parse("genre:lala:i::replace:lalala") == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["genre"], pattern=MatcherPattern("lala", case_insensitive=True), ) assert MetadataAction.parse( "matched:^x::replace:lalala", matcher=MetadataMatcher(tags=["tracktitle"], pattern=MatcherPattern("haha")), ) == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["tracktitle"], pattern=MatcherPattern("^x"), ) # Test that case insensitivity is inherited from the matcher. assert MetadataAction.parse( "replace:lalala", matcher=MetadataMatcher( tags=["tracktitle"], pattern=MatcherPattern("haha", case_insensitive=True) ), ) == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["tracktitle"], pattern=MatcherPattern("haha", case_insensitive=True), ) # Test that the action excludes the immutable *total tags. assert MetadataAction.parse( "replace:5", matcher=MetadataMatcher( tags=["tracknumber", "tracktotal", "discnumber", "disctotal"], pattern=MatcherPattern("1"), ), ) == MetadataAction( behavior=ReplaceAction(replacement="5"), tags=["tracknumber", "discnumber"], pattern=MatcherPattern("1"), ) assert MetadataAction.parse( "sed:lalala:hahaha", matcher=MetadataMatcher(tags=["genre"], pattern=MatcherPattern("haha")), ) == MetadataAction( behavior=SedAction(src=re.compile("lalala"), dst="hahaha"), tags=["genre"], pattern=MatcherPattern("haha"), ) assert MetadataAction.parse( r"split:\:", matcher=MetadataMatcher(tags=["genre"], pattern=MatcherPattern("haha")), ) == MetadataAction(
def test_rule_str() -> None: rule = MetadataRule.parse("tracktitle:Track", ["albumartist,genre::replace:lalala"]) assert str(rule) == "matcher=tracktitle:Track action=albumartist,genre::replace:lalala" # Test that rules are quoted properly. rule = MetadataRule.parse(r"tracktitle,albumartist,genre:\:", [r"sed:\::; "]) assert ( str(rule) == r"matcher='tracktitle,albumartist,genre:\:' action='tracktitle,albumartist,genre:\:::sed:\::; '" ) # Test that custom action matcher is printed properly. rule = MetadataRule.parse("tracktitle:Track", ["genre:lala::replace:lalala"]) assert str(rule) == "matcher=tracktitle:Track action=genre:lala::replace:lalala" # Test that we print `matched` when action pattern is not null. rule = MetadataRule.parse("genre:b", ["genre:h::replace:hi"]) assert str(rule) == r"matcher=genre:b action=genre:h::replace:hi" def test_rule_parse_matcher() -> None: assert MetadataMatcher.parse("tracktitle:Track") == MetadataMatcher( tags=["tracktitle"], pattern=MatcherPattern("Track"), ) assert MetadataMatcher.parse("tracktitle,tracknumber:Track") == MetadataMatcher( tags=["tracktitle", "tracknumber"], pattern=MatcherPattern("Track"), ) assert MetadataMatcher.parse("tracktitle,tracknumber:^Track$") == MetadataMatcher( tags=["tracktitle", "tracknumber"], pattern=MatcherPattern("^Track$"), ) assert MetadataMatcher.parse(r"tracktitle,tracknumber:Tr\:ck") == MetadataMatcher( tags=["tracktitle", "tracknumber"], pattern=MatcherPattern("Tr:ck"), ) assert MetadataMatcher.parse("tracktitle,tracknumber:Track:i") == MetadataMatcher( tags=["tracktitle", "tracknumber"], pattern=MatcherPattern("Track", case_insensitive=True), ) assert MetadataMatcher.parse(r"tracktitle:") == MetadataMatcher( tags=["tracktitle"], pattern=MatcherPattern(""), ) def test_err(rule: str, err: str) -> None: with pytest.raises(RuleSyntaxError) as exc: MetadataMatcher.parse(rule) assert click.unstyle(str(exc.value)) == err test_err( "tracknumber^Track$", """\ Failed to parse matcher, invalid syntax: tracknumber^Track$ ^ Invalid tag: must be one of {tracktitle, trackartist, trackartist[main], trackartist[guest], trackartist[remixer], trackartist[producer], trackartist[composer], trackartist[djmixer], tracknumber, tracktotal, discnumber, disctotal, albumtitle, albumartist, albumartist[main], albumartist[guest], albumartist[remixer], albumartist[producer], albumartist[composer], albumartist[djmixer], releasetype, year, genre, label, artist}. The next character after a tag must be ':' or ','. """, ) test_err( "tracknumber", """\ Failed to parse matcher, invalid syntax: tracknumber ^ Expected to find ',' or ':', found end of string. """, ) test_err( "tracktitle:Tr:ck", """\ Failed to parse matcher, invalid syntax: tracktitle:Tr:ck ^ Unrecognized flag: Please specify one of the supported flags: `i` (case insensitive). """, ) test_err( "tracktitle::", """\ Failed to parse matcher, invalid syntax: tracktitle:: ^ No flags specified: Please remove this section (by deleting the colon) or specify one of the supported flags: `i` (case insensitive). """, ) test_err( "tracktitle::i:hihi", """\ Failed to parse matcher, invalid syntax: tracktitle::i:hihi ^ Extra input found after end of matcher. Perhaps you meant to escape this colon? """, ) def test_rule_parse_action() -> None: assert MetadataAction.parse( "replace:lalala", matcher=MetadataMatcher(tags=["tracktitle"], pattern=MatcherPattern("haha")), ) == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["tracktitle"], pattern=MatcherPattern("haha"), ) assert MetadataAction.parse("genre::replace:lalala") == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["genre"], pattern=None, ) assert MetadataAction.parse("tracknumber,genre::replace:lalala") == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["tracknumber", "genre"], pattern=None, ) assert MetadataAction.parse("genre:lala::replace:lalala") == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["genre"], pattern=MatcherPattern("lala"), ) assert MetadataAction.parse("genre:lala:i::replace:lalala") == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["genre"], pattern=MatcherPattern("lala", case_insensitive=True), ) assert MetadataAction.parse( "matched:^x::replace:lalala", matcher=MetadataMatcher(tags=["tracktitle"], pattern=MatcherPattern("haha")), ) == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["tracktitle"], pattern=MatcherPattern("^x"), ) # Test that case insensitivity is inherited from the matcher. assert MetadataAction.parse( "replace:lalala", matcher=MetadataMatcher( tags=["tracktitle"], pattern=MatcherPattern("haha", case_insensitive=True) ), ) == MetadataAction( behavior=ReplaceAction(replacement="lalala"), tags=["tracktitle"], pattern=MatcherPattern("haha", case_insensitive=True), ) # Test that the action excludes the immutable *total tags. assert MetadataAction.parse( "replace:5", matcher=MetadataMatcher( tags=["tracknumber", "tracktotal", "discnumber", "disctotal"], pattern=MatcherPattern("1"), ), ) == MetadataAction( behavior=ReplaceAction(replacement="5"), tags=["tracknumber", "discnumber"], pattern=MatcherPattern("1"), ) assert MetadataAction.parse( "sed:lalala:hahaha", matcher=MetadataMatcher(tags=["genre"], pattern=MatcherPattern("haha")), ) == MetadataAction( behavior=SedAction(src=re.compile("lalala"), dst="hahaha"), tags=["genre"], pattern=MatcherPattern("haha"), ) assert MetadataAction.parse( r"split:\:", matcher=MetadataMatcher(tags=["genre"], pattern=MatcherPattern("haha")), ) == MetadataAction(
behavior=SplitAction(delimiter=":"),
10
2023-10-09 14:42:23+00:00
8k
mikeshardmind/wakfu-utils
wakautosolver/versioned_entrypoints.py
[ { "identifier": "encode", "path": "wakautosolver/b2048/encoder.py", "snippet": "def encode(bys: bytes, /) -> str:\n ret = StringIO()\n stage = 0\n remaining = 0\n\n for byte in bys:\n need = 11 - remaining\n if need < 8:\n remaining = 8 - need\n index = (s...
import traceback import zlib from collections.abc import Callable from typing import Literal from msgspec import Struct, field, msgpack from msgspec.structs import asdict from .b2048 import encode as b2048encode from .object_parsing import load_item_source_data from .restructured_types import DUMMY_MAX, DUMMY_MIN, ClassElements, ElementsEnum, Priority, StatPriority, Stats from .restructured_types import SetMaximums as RealSetMaxs from .restructured_types import SetMinimums as RealSetMins from .solver import ImpossibleStatError, SolveError, solve, v1Config from .wakforge_buildcodes import Buildv1 as WFBuild
6,123
"Eca", "Eni", "Iop", "Cra", "Sadi", "Sac", "Panda", "Rogue", "Masq", "Ougi", "Fog", "Elio", "Hupper", ] _adaptive_tolerance_map: dict[int, int] = { 20: 20, 35: 35, 50: 50, 65: 30, 80: 30, 95: 30, 110: 30, 125: 15, 140: 15, 155: 15, 170: 15, 185: 15, 200: 14, 215: 15, 230: 14, } v1Result = tuple[list[int] | None, str | None] # Exists because versioning class SetMinimums(Struct, frozen=True, gc=True): ap: int = DUMMY_MIN mp: int = DUMMY_MIN wp: int = DUMMY_MIN ra: int = DUMMY_MIN crit: int = DUMMY_MIN crit_mastery: int = DUMMY_MIN elemental_mastery: int = DUMMY_MIN one_element_mastery: int = DUMMY_MIN two_element_mastery: int = DUMMY_MIN three_element_mastery: int = DUMMY_MIN distance_mastery: int = DUMMY_MIN rear_mastery: int = DUMMY_MIN heal_mastery: int = DUMMY_MIN beserk_mastery: int = DUMMY_MIN melee_mastery: int = DUMMY_MIN control: int = DUMMY_MIN block: int = DUMMY_MIN fd: int = DUMMY_MIN heals_performed: int = DUMMY_MIN lock: int = DUMMY_MIN dodge: int = DUMMY_MIN armor_given: int = DUMMY_MIN def to_real(self) -> RealSetMins: data = asdict(self) for new, old in ( ("critical_hit", "crit"), ("critical_mastery", "crit_mastery"), ("mastery_3_elements", "three_element_mastery"), ("mastery_2_elements", "two_element_mastery"), ("mastery_1_element", "one_element_mastery"), ("healing_mastery", "heal_mastery"), ("berserk_mastery", "beserk_mastery"), ): data[new] = data.pop(old) return RealSetMins(**data) class SetMaximums(Struct, frozen=True, gc=True): ap: int = DUMMY_MAX mp: int = DUMMY_MAX wp: int = DUMMY_MAX ra: int = DUMMY_MAX crit: int = DUMMY_MAX crit_mastery: int = DUMMY_MAX elemental_mastery: int = DUMMY_MAX one_element_mastery: int = DUMMY_MAX two_element_mastery: int = DUMMY_MAX three_element_mastery: int = DUMMY_MAX distance_mastery: int = DUMMY_MAX rear_mastery: int = DUMMY_MAX heal_mastery: int = DUMMY_MAX beserk_mastery: int = DUMMY_MAX melee_mastery: int = DUMMY_MAX control: int = DUMMY_MAX block: int = DUMMY_MAX fd: int = DUMMY_MAX heals_performed: int = DUMMY_MAX lock: int = DUMMY_MAX dodge: int = DUMMY_MAX armor_given: int = DUMMY_MAX def to_real(self) -> RealSetMaxs: data = asdict(self) for new, old in ( ("critical_hit", "crit"), ("critical_mastery", "crit_mastery"), ("mastery_3_elements", "three_element_mastery"), ("mastery_2_elements", "two_element_mastery"), ("mastery_1_element", "one_element_mastery"), ("healing_mastery", "heal_mastery"), ("berserk_mastery", "beserk_mastery"), ): data[new] = data.pop(old) return RealSetMaxs(**data) def partial_solve_v1( *, lv: int,
""" This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (C) 2023 Michael Hall <https://github.com/mikeshardmind> """ from __future__ import annotations ClassNames = Literal[ "Feca", "Osa", "Enu", "Sram", "Xel", "Eca", "Eni", "Iop", "Cra", "Sadi", "Sac", "Panda", "Rogue", "Masq", "Ougi", "Fog", "Elio", "Hupper", ] _adaptive_tolerance_map: dict[int, int] = { 20: 20, 35: 35, 50: 50, 65: 30, 80: 30, 95: 30, 110: 30, 125: 15, 140: 15, 155: 15, 170: 15, 185: 15, 200: 14, 215: 15, 230: 14, } v1Result = tuple[list[int] | None, str | None] # Exists because versioning class SetMinimums(Struct, frozen=True, gc=True): ap: int = DUMMY_MIN mp: int = DUMMY_MIN wp: int = DUMMY_MIN ra: int = DUMMY_MIN crit: int = DUMMY_MIN crit_mastery: int = DUMMY_MIN elemental_mastery: int = DUMMY_MIN one_element_mastery: int = DUMMY_MIN two_element_mastery: int = DUMMY_MIN three_element_mastery: int = DUMMY_MIN distance_mastery: int = DUMMY_MIN rear_mastery: int = DUMMY_MIN heal_mastery: int = DUMMY_MIN beserk_mastery: int = DUMMY_MIN melee_mastery: int = DUMMY_MIN control: int = DUMMY_MIN block: int = DUMMY_MIN fd: int = DUMMY_MIN heals_performed: int = DUMMY_MIN lock: int = DUMMY_MIN dodge: int = DUMMY_MIN armor_given: int = DUMMY_MIN def to_real(self) -> RealSetMins: data = asdict(self) for new, old in ( ("critical_hit", "crit"), ("critical_mastery", "crit_mastery"), ("mastery_3_elements", "three_element_mastery"), ("mastery_2_elements", "two_element_mastery"), ("mastery_1_element", "one_element_mastery"), ("healing_mastery", "heal_mastery"), ("berserk_mastery", "beserk_mastery"), ): data[new] = data.pop(old) return RealSetMins(**data) class SetMaximums(Struct, frozen=True, gc=True): ap: int = DUMMY_MAX mp: int = DUMMY_MAX wp: int = DUMMY_MAX ra: int = DUMMY_MAX crit: int = DUMMY_MAX crit_mastery: int = DUMMY_MAX elemental_mastery: int = DUMMY_MAX one_element_mastery: int = DUMMY_MAX two_element_mastery: int = DUMMY_MAX three_element_mastery: int = DUMMY_MAX distance_mastery: int = DUMMY_MAX rear_mastery: int = DUMMY_MAX heal_mastery: int = DUMMY_MAX beserk_mastery: int = DUMMY_MAX melee_mastery: int = DUMMY_MAX control: int = DUMMY_MAX block: int = DUMMY_MAX fd: int = DUMMY_MAX heals_performed: int = DUMMY_MAX lock: int = DUMMY_MAX dodge: int = DUMMY_MAX armor_given: int = DUMMY_MAX def to_real(self) -> RealSetMaxs: data = asdict(self) for new, old in ( ("critical_hit", "crit"), ("critical_mastery", "crit_mastery"), ("mastery_3_elements", "three_element_mastery"), ("mastery_2_elements", "two_element_mastery"), ("mastery_1_element", "one_element_mastery"), ("healing_mastery", "heal_mastery"), ("berserk_mastery", "beserk_mastery"), ): data[new] = data.pop(old) return RealSetMaxs(**data) def partial_solve_v1( *, lv: int,
stats: Stats,
2
2023-10-10 21:54:23+00:00
8k
bittranslateio/bittranslate
simulate/run_miner.py
[ { "identifier": "M2MMiner", "path": "neurons/miners/m2m_miner.py", "snippet": "class M2MMiner(BaseMiner):\n @classmethod\n def add_args(cls, parser: argparse.ArgumentParser) -> None:\n\n parser.add_argument(\n \"--model_name\",\n type=str,\n default=\"facebo...
import argparse import json import time from neurons.miners.m2m_miner import M2MMiner from mock.mock_network import mocked_network from neurons.protocol import Translate from bittranslate import Validator
4,868
def get_config(): parser = argparse.ArgumentParser() parser.add_argument( "--rounds", type=int, default=100, help="Number of rounds that will be performed for evaluating the model" ) parser.add_argument('--val_device', default="cuda", help="The device used for the validator's components.") parser.add_argument('--save_data', default=None, help="Where the generated data will be saved. If None no saving will occur..") parser.add_argument('--load_data', default=None, help="Path to where data will be loaded from. If None new data will be generated.") M2MMiner.add_args(parser) args = parser.parse_args() return args def main():
def get_config(): parser = argparse.ArgumentParser() parser.add_argument( "--rounds", type=int, default=100, help="Number of rounds that will be performed for evaluating the model" ) parser.add_argument('--val_device', default="cuda", help="The device used for the validator's components.") parser.add_argument('--save_data', default=None, help="Where the generated data will be saved. If None no saving will occur..") parser.add_argument('--load_data', default=None, help="Path to where data will be loaded from. If None new data will be generated.") M2MMiner.add_args(parser) args = parser.parse_args() return args def main():
with mocked_network():
1
2023-10-09 12:08:05+00:00
8k
grainseed/monitask
sam/segment_anything/modeling/sam.py
[ { "identifier": "ImageEncoderViT", "path": "sam/segment_anything/modeling/image_encoder.py", "snippet": "class ImageEncoderViT(nn.Module):\r\n def __init__(\r\n self,\r\n img_size: int = 1024,\r\n patch_size: int = 16,\r\n in_chans: int = 3,\r\n embed_dim: int = 768...
import torch from torch import nn from torch.nn import functional as F from typing import Any, Dict, List, Tuple from .image_encoder import ImageEncoderViT from .mask_decoder import MaskDecoder from .prompt_encoder import PromptEncoder
4,130
# 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 Sam(nn.Module): mask_threshold: float = 0.0 image_format: str = "RGB" def __init__( self, image_encoder: ImageEncoderViT, prompt_encoder: PromptEncoder,
# 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 Sam(nn.Module): mask_threshold: float = 0.0 image_format: str = "RGB" def __init__( self, image_encoder: ImageEncoderViT, prompt_encoder: PromptEncoder,
mask_decoder: MaskDecoder,
1
2023-10-14 13:45:54+00:00
8k
AI4HealthUOL/s4sleep
clinical_ts/ecg_utils.py
[ { "identifier": "stratify", "path": "clinical_ts/stratify.py", "snippet": "def stratify(data, classes, ratios, samples_per_group=None,random_seed=0,verbose=True):\n \"\"\"Stratifying procedure. Modified from https://vict0rs.ch/2018/05/24/sample-multilabel-dataset/ (based on Sechidis 2011)\n\n data...
import wfdb import scipy.io import numpy as np import pandas as pd import resampy import h5py import datetime from tqdm.auto import tqdm from pathlib import Path from ishneholterlib import Holter from .stratify import stratify,stratify_batched from .timeseries_utils import *
6,677
#trainlist = np.load("./old/trainlist.npy") df_ptb["strat_fold_old"] = -1 for i in range(len(evallist)): df_ptb.loc[df_ptb.ecg.isin(["PTB_"+x for x in indexlst[evallist[i]][:,1]]),"strat_fold_old"]=i #export current splits for debugging evallist =[] trainlist =[] for i in range(strat_folds): valid_ecgs= np.array(df_ptb[(df_ptb.strat_fold>=0)&(df_ptb.strat_fold==i)].ecg.apply(lambda x: x[4:])) train_ecgs= np.array(df_ptb[(df_ptb.strat_fold>=0)&(df_ptb.strat_fold!=i)].ecg.apply(lambda x: x[4:])) evallist.append([np.where(indexlst==v)[0][0] for v in valid_ecgs]) trainlist.append([np.where(indexlst==t)[0][0] for t in train_ecgs]) np.save("./old/evallist_new.npy",evallist) np.save("./old/trainlist_new.npy",trainlist) #add means and std dataset_add_mean_col(df_ptb,data_folder=target_root_ptb) dataset_add_std_col(df_ptb,data_folder=target_root_ptb) dataset_add_length_col(df_ptb,data_folder=target_root_ptb) #dataset_add_median_col(df_ptb,data_folder=target_folder) #dataset_add_iqr_col(df_ptb,data_folder=target_folder) #compute means and stds mean_ptb, std_ptb = dataset_get_stats(df_ptb) #save save_dataset(df_ptb,lbl_itos_ptb,mean_ptb,std_ptb,target_root_ptb) else: df_ptb, lbl_itos_ptb, mean_ptb, std_ptb = load_dataset(target_root_ptb,df_mapped=False) return df_ptb, lbl_itos_ptb, mean_ptb, std_ptb # Cell def mat_to_np(filename_in, target_fs=100, channels=12, channel_stoi=None, fs=500, target_folder=None): channel_labels=["i","ii", "iii", "avr", "avl", "avf", "v1", "v2", "v3", "v4", "v5", "v6"] filename_out, filename_out_relative = get_filename_out(filename_in, target_folder) channels_available = get_available_channels(channel_labels,channel_stoi) data_raw = scipy.io.loadmat(filename_in) sex,age,sigbufs=data_raw['ECG'][0][0] sigbufs =np.transpose(sigbufs) data = resample_data(sigbufs=sigbufs,channel_stoi=channel_stoi,channel_labels=channel_labels,fs=fs,target_fs=target_fs, channels=channels) np.save(filename_out, data.astype(np.float32)) return sex[0], age[0,0], channels_available, filename_out, filename_out_relative def reformat_data_icbeb(datafiles, labelfile, target_fs=100, channels=12, channel_stoi=channel_stoi_default, target_folder=None): #labels label_itos=["NORMAL","AF", "I-AVB","LBBB","RBBB","PAC","PVC","STD","STE"] labels=pd.read_csv(labelfile) labels.columns=["ecg","label1","label2","label3"] labels=labels.set_index("ecg") labels.label1=labels.label1.apply(lambda x: int(x) -1 if not np.isnan(x) else np.nan) labels.label2=labels.label2.apply(lambda x: int(x) -1 if not np.isnan(x) else np.nan) labels.label3=labels.label3.apply(lambda x: int(x) -1 if not np.isnan(x) else np.nan) #data rows=[] for d in tqdm(datafiles): sex,age,channels_available,filename_out,filename_out_relative=mat_to_np(filename_in=d, target_fs=target_fs, channels=channels, channel_stoi=channel_stoi, target_folder=target_folder) rows.append({"ecg":d.stem, "dataset":"ICBEB2018", "data":filename_out_relative, "age": (np.nan if np.isnan(age) else int(age)), "sex": sex.lower(), "channels_available":channels_available}) df=pd.DataFrame(rows) df=df.set_index("ecg") #join df=df.join(labels) df=df.reset_index() #define actual label (label 2 and label 3 are multilabels) df["label"]=df["label1"] df["has_label2"]=~pd.isna(df["label2"])#i.e. multilabeled label 3 will only be set if label 2 is df["has_label3"]=~pd.isna(df["label3"]) #age df["label_age"]=df.age.apply(lambda x: _age_to_categorical(x)) #sex df["label_sex"]=df.sex.apply(lambda x: _sex_to_categorical(x)) def multi_label(x): res = np.zeros(len(label_itos),dtype=np.float32) for xi in x: if(np.isfinite(xi) and int(xi) in list(range(len(label_itos)))): res[int(xi)]=1 return res def combine_labels(x): res = [x["label1"]] if(np.isfinite(x["label2"])): res += [int(x["label2"])] if(np.isfinite(x["label3"])): res += [int(x["label3"])] return res df["labels"]=df.apply(lambda x: combine_labels(x),axis=1) df["label_multi"]=df.labels.apply(lambda x:multi_label(x)) return df, label_itos def prepare_data_icbeb(data_folder, target_folder=None, channel_stoi=channel_stoi_default, channels=12, target_fs=50, strat_folds=10, cv_random_state=42,recreate_data=False,discard_valtest=True): target_root_icbeb = Path(".") if target_folder is None else target_folder if(recreate_data): #collect files datafiles_icbeb=list(data_folder.glob('**/*.mat')) labelfile_icbeb=data_folder/"REFERENCE.csv" #reformat data df_icbeb, lbl_itos_icbeb = reformat_data_icbeb(datafiles_icbeb,labelfile_icbeb,channel_stoi=channel_stoi,target_fs=target_fs,channels=channels,target_folder=target_folder) #TODO eventually move all the stuff below into reformat data #remove valid data df_icbeb["set"] = df_icbeb.data.apply(lambda x: (0 if "train" in x.parts else 1)) if(discard_valtest is True): df_icbeb=df_icbeb[df_icbeb["set"]==0].reset_index()#only train set has label else:#reset labels that have been set erroneously df_icbeb.loc[df_icbeb["set"]==1,"label"]=np.nan df_icbeb.loc[df_icbeb["set"]==1,"label_multi"]=np.nan df_icbeb.loc[df_icbeb["set"]==1,"label1"]=np.nan df_icbeb.loc[df_icbeb["set"]==1,"label2"]=np.nan df_icbeb.loc[df_icbeb["set"]==1,"label3"]=np.nan #train test split (all)
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/05_ecg_utils.ipynb (unless otherwise specified). __all__ = ['get_available_channels', 'channel_stoi_default', 'resample_data', 'get_filename_out', 'reformat_data_ptb', 'prepare_data_ptb', 'mat_to_np', 'reformat_data_icbeb', 'prepare_data_icbeb', 'prepare_data_ptb_xl', 'map_and_filter_labels', 'thew_to_np', 'reformat_data_thew', 'prepare_data_thew', 'prepare_data_cinc', 'prepare_data_chapman', 'prepare_data_ribeiro_test', 'prepare_data_ludb', 'prepare_data_ribeiro_full', 'prepare_mitdb','prepare_afdb','prepare_ltafdb','prepare_vfdb','prepare_cpsc21','get_data_annot_stats'] # Cell #from skimage import transform #from scipy.ndimage import zoom #thew #ribeiro #from clinical_ts.misc_utils import * # Cell channel_stoi_default = {"i": 0, "ii": 1, "v1":2, "v2":3, "v3":4, "v4":5, "v5":6, "v6":7, "iii":8, "avr":9, "avl":10, "avf":11, "vx":12, "vy":13, "vz":14} def get_available_channels(channel_labels, channel_stoi): if(channel_stoi is None): return range(len(channel_labels)) else: return sorted([channel_stoi[c] for c in channel_labels if c in channel_stoi.keys()]) # Cell def resample_data(sigbufs, channel_labels, fs, target_fs, channels=12, channel_stoi=None):#,skimage_transform=True,interpolation_order=3): channel_labels = [c.lower() for c in channel_labels] #https://github.com/scipy/scipy/issues/7324 zoom issues factor = target_fs/fs timesteps_new = int(len(sigbufs)*factor) if(channel_stoi is not None): data = np.zeros((timesteps_new, channels), dtype=np.float32) for i,cl in enumerate(channel_labels): if(cl in channel_stoi.keys() and channel_stoi[cl]<channels): #if(skimage_transform): # data[:,channel_stoi[cl]]=transform.resize(sigbufs[:,i],(timesteps_new,),order=interpolation_order).astype(np.float32) #else: # data[:,channel_stoi[cl]]=zoom(sigbufs[:,i],timesteps_new/len(sigbufs),order=interpolation_order).astype(np.float32) data[:,channel_stoi[cl]] = resampy.resample(sigbufs[:,i], fs, target_fs).astype(np.float32) else: #if(skimage_transform): # data=transform.resize(sigbufs,(timesteps_new,channels),order=interpolation_order).astype(np.float32) #else: # data=zoom(sigbufs,(timesteps_new/len(sigbufs),1),order=interpolation_order).astype(np.float32) data = resampy.resample(sigbufs, fs, target_fs, axis=0).astype(np.float32) return data # Cell def get_filename_out(filename_in, target_folder=None, suffix=""): if target_folder is None: #absolute path here filename_out = filename_in.parent/(filename_in.stem+suffix+".npy") filename_out_relative = filename_out else: if("train" in filename_in.parts): target_folder_train = target_folder/"train" # relative path here filename_out = target_folder_train/(filename_in.stem+suffix+".npy") filename_out_relative = filename_out.relative_to(target_folder) target_folder_train.mkdir(parents=True, exist_ok=True) elif("eval" in filename_in.parts or "dev_test" in filename_in.parts or "valid" in filename_in.parts or "valtest" in filename_in.parts): target_folder_valid = target_folder/"valid" filename_out = target_folder_valid/(filename_in.stem+suffix+".npy") filename_out_relative = filename_out.relative_to(target_folder) target_folder_valid.mkdir(parents=True, exist_ok=True) else: filename_out = target_folder/(filename_in.stem+suffix+".npy") filename_out_relative = filename_out.relative_to(target_folder) target_folder.mkdir(parents=True, exist_ok=True) return filename_out, filename_out_relative # Cell def _age_to_categorical(age): if(np.isnan(age)): label_age = -1 elif(age<30): label_age = 0 elif(age<40): label_age = 1 elif(age<50): label_age = 2 elif(age<60): label_age = 3 elif(age<70): label_age = 4 elif(age<80): label_age = 5 else: label_age = 6 return label_age def _sex_to_categorical(sex): sex_mapping = {"n/a":-1, "male":0, "female":1, "":-1} return sex_mapping[sex] def reformat_data_ptb(datafiles, target_fs=200, channels=12, channel_stoi=channel_stoi_default, lbl_itos=None, target_folder=None): rows = [] for filename_in in tqdm(datafiles): filename_out, filename_out_relative = get_filename_out(filename_in,target_folder) sigbufs, header = wfdb.rdsamp(str(filename_in.parent/filename_in.stem)) data = resample_data(sigbufs=sigbufs,channel_stoi=channel_stoi,channel_labels=header['sig_name'],fs=header['fs'],target_fs=target_fs, channels=channels) np.save(filename_out,data.astype(np.float32)) metadata=[(":".join(h.split(":")[1:])).strip() for h in header['comments']] metadata_descr = [(h.split(":")[0]).strip() for h in header['comments']] #for i,(m1,m2) in enumerate(zip(metadata_descr,metadata)): # print(i,m1,m2) #input() ecg = filename_in.stem patient = str(filename_in.parent)[-3:] channels_available = get_available_channels(header['sig_name'],channel_stoi) try: age=int(metadata[0]) except ValueError: age=np.nan label_age = _age_to_categorical(age) diagnosis1 = metadata[4] diagnosis2 = [l.strip() for l in metadata[7].split(",") if l.strip() not in ["no","unknown","n/a"]] diagnosis2 = [l.replace("Typ IIa","Type IIa").replace("Hypertension","hypertension").replace(" (intraventricular gradient 100-160mmHg)","").replace("Fibrillation","fibrillation").replace("Recurrent ventricular tachycardias","Recurrent ventricular tachycardia").replace("Thyriodectomy","Thyroidectomy").replace("Dilated Cardiomyopathy secondary to coronary artery disease. Mitral regurgitation (grade 2)","Dilated Cardiomyopathy") for l in diagnosis2]#clean up #remove type from Hyperlipoproteinemia Type xx TODO diagnosis2 = [l.replace("Hyperlipoproteinemia Type IIa","Hyperlipoproteinemia").replace("Hyperlipoproteinemia Type IV","Hyperlipoproteinemia").replace("Hyperlipoproteinemia Type IIb","Hyperlipoproteinemia") for l in diagnosis2]#clean up diagnosis12 = [diagnosis1]+diagnosis2 smoker = metadata[8] smoker_mapping = {"no":0, "yes":1, "n/a":-1, "unknown":-1} label_smoker = smoker_mapping[smoker] sex = metadata[1] label_sex = _sex_to_categorical(sex) row={"data":filename_out_relative,"dataset":"PTB","channels_available":channels_available,"patient":"PTB_"+patient, "ecg": "PTB_"+ecg, "age": age, "label_age":label_age,"sex": sex, "label_sex": label_sex, "ecg_date":metadata[2], "diagnosis":diagnosis1, "infarction_localization":metadata[5], "diagnosis2": diagnosis2, "diagnosis12": diagnosis12,"smoker": smoker, "label_smoker":label_smoker, "infarction_date":metadata[10], "catheterization_date":metadata[14]} #add hemodynamics for i in range(14,36): row[metadata_descr[i]]=metadata[i] #clean up localization if(row["diagnosis"]!="Myocardial infarction"): row["infarction_localization"]="" if row["infarction_localization"] == "infero-latera": row["infarction_localization"] = "infero-lateral" if row["infarction_localization"] == "infero-posterior-lateral": row["infarction_localization"] = "infero-postero-lateral" if row["infarction_localization"] == "infero-poster-lateral": row["infarction_localization"] = "infero-postero-lateral" if row["infarction_localization"] == "no": row["infarction_localization"] = "" rows.append(row) df_all = pd.DataFrame(rows) _ptb_cleanup_hemodynamics(df_all) #fill label column if(lbl_itos is not None): lbl_stoi = {s:i for i,s in enumerate(lbl_itos)} df_all["label"] = df_all.diagnosis.apply(lambda x: (lbl_stoi[x] if x in lbl_stoi.keys() else len(lbl_itos)))#map everything that cannot be found in the dictionary to last entry else: lbl_itos = np.unique(df_all["diagnosis"]) lbl_stoi = {s:i for i,s in enumerate(lbl_itos)} df_all["label"] = df_all.diagnosis.apply(lambda x: lbl_stoi[x]) #convert datatypes (be careful the standard to_datetime does not work correctly here) #df_all.ecg_date=pd.to_datetime(df_all.ecg_date,errors='coerce') #df_all.infarction_date=pd.to_datetime(df_all.infarction_date,errors='coerce') #df_all.catheterization_date=pd.to_datetime(df_all.catheterization_date,errors='coerce') #df_all=df_all.set_index("ecg") return df_all, lbl_itos def _ptb_cleanup_hemodynamics(df_ptb): def _extract_numeric(x,mode=0): if x=="n/a": return np.nan else: if mode==0: return float(x.split(" ")[0]) elif mode==1: return float(x.split(" ")[0].split("/")[0]) else: return float(x.split(" ")[0].split("/")[1]) def _reformat_col(df, col_in, col_out1, col_out2=None): df[col_out1]= df[col_in].apply(lambda x: _extract_numeric(x,0 if col_out2 is None else 1)) if col_out2 is not None: df[col_out2]= df[col_in].apply(lambda x: _extract_numeric(x,2)) df.drop(col_in,axis=1,inplace=True) _reformat_col(df_ptb,"Aorta (at rest) (syst/diast)","aorta_at_rest_syst","aorta_at_rest_diast") _reformat_col(df_ptb,"Aorta (at rest) mean","aorta_at_rest_mean") df_ptb["Cardiac index (at rest)"]=df_ptb["Cardiac index (at rest)"].apply(lambda x: x.replace(",",".")) _reformat_col(df_ptb,"Cardiac index (at rest)","cardiac_index_at_rest") df_ptb["Cardiac index (load)"]=df_ptb["Cardiac index (load)"].apply(lambda x: x.replace(",",".")) _reformat_col(df_ptb,"Cardiac index (load)","cardiac_index_load") df_ptb["Cardiac output (at rest)"]=df_ptb["Cardiac output (at rest)"].apply(lambda x: x.replace(",",".")) _reformat_col(df_ptb,"Cardiac output (at rest)","cardiac_output_at_rest") df_ptb["Cardiac output (load)"]=df_ptb["Cardiac output (load)"].apply(lambda x: x.replace(",",".")) _reformat_col(df_ptb,"Cardiac output (load)","cardiac_output_load") df_ptb.drop('Chest X-ray',axis=1,inplace=True) df_ptb.drop('Left coronary artery stenoses (RCX)',axis=1,inplace=True) df_ptb.drop('Left coronary artery stenoses (RIVA)',axis=1,inplace=True) df_ptb.drop('Right coronary artery stenoses (RCA)',axis=1,inplace=True) df_ptb.drop('Ventriculography',axis=1,inplace=True) df_ptb.drop('Catheterization date',axis=1,inplace=True) df_ptb["Peripheral blood Pressure (syst/diast)"]=df_ptb["Peripheral blood Pressure (syst/diast)"].apply(lambda x: x.replace("120 /70","120/70")) _reformat_col(df_ptb,"Peripheral blood Pressure (syst/diast)","peripheral_bp_syst","peripheral_bp_diast") _reformat_col(df_ptb,"Pulmonary artery pressure (at rest) (mean)","pulmonary_ap_at_rest_mean") _reformat_col(df_ptb,"Pulmonary artery pressure (at rest) (syst/diast)","pulmonary_ap_at_rest_syst","pulmonary_ap_at_rest_diast") _reformat_col(df_ptb,"Pulmonary artery pressure (laod) (mean)","pulmonary_load_mean") _reformat_col(df_ptb,"Pulmonary artery pressure (laod) (syst/diast)","pulmonary_ap_load_syst","pulmonary_ap_load_diast") _reformat_col(df_ptb,"Pulmonary capillary wedge pressure (at rest)","pulmonary_cwp_at_rest") _reformat_col(df_ptb,"Pulmonary capillary wedge pressure (load)","pulmonary_cwp_load") df_ptb["Left ventricular enddiastolic pressure"]=df_ptb["Left ventricular enddiastolic pressure"].apply(lambda x:x[-8:].strip())#only post value _reformat_col(df_ptb,"Left ventricular enddiastolic pressure","left_ventricular_ed_pressure") _reformat_col(df_ptb,"Stroke volume index (at rest)","stroke_volume_index_at_rest") df_ptb["Stroke volume index (load)"]=df_ptb["Stroke volume index (load)"].apply(lambda x: x.replace(",",".")) _reformat_col(df_ptb,"Stroke volume index (load)","stroke_volume_index_load") def prepare_data_ptb(data_folder, target_folder=None, channel_stoi=channel_stoi_default, channels=12, target_fs=50, strat_folds=10, cv_random_state=42,recreate_data=False,ptb_permanently_remove_diagnosis_na = True, ptb_permanently_remove_multiple_ecgs = False,ptb_select_only_first_mi = True, ptb_remove_unknown_loc_mi = True,lbl_itos_ptb_in = ["Healthy control", "Myocardial infarction"],lbl_itos_ptb_regression = ["pulmonary_ap_at_rest_mean"],lbl_itos_ptb_all = ["Diabetes mellitus"]): target_root_ptb = Path(".") if target_folder is None else target_folder diagnosis_to_int_w_subdiagnosis = { #"Healthy control": 0, # 80 "anterior": 1, # 47 "antero-septal": 1, # 77 "antero-septo-lateral": 1, # 2 "antero-lateral": 1, # 43 "lateral": 1, # 3 "inferior": 2, # 89 "infero-posterior": 2, # 1 "infero-postero-lateral": 2, # 16 "infero-poster-lateral": 2, # 3 "infero-latera": 2, # 3 "infero-lateral": 2, # 53 "posterior": 2, # 4 "postero-lateral": 2, # 5 #"other": -1 # 123 "":0 } int_to_str=[""," anterior", "inferior"] if(recreate_data): #collect files datafiles_ptb = list(data_folder.glob('**/*.dat')) #reformat data df_ptb, lbl_itos_ptb=reformat_data_ptb(datafiles=datafiles_ptb,target_fs=target_fs, channels=channels,lbl_itos=lbl_itos_ptb_in, target_folder=target_folder) df_ptb["infarction_localization_mapped"]=df_ptb["infarction_localization"].apply(lambda x: int_to_str[diagnosis_to_int_w_subdiagnosis[x]]) df_ptb["diagnosis_extended"]=df_ptb.apply(lambda row: row["diagnosis"]+" "+row["infarction_localization_mapped"], axis=1) #TODO move all this stuff into reformat_data_ptb #set regression label(s) df_ptb["label_regression"]=df_ptb.apply(lambda row: row[lbl_itos_ptb_regression[0]] if len(lbl_itos_ptb_regression)==1 else [row[regression_col] for regression_col in lbl_itos_ptb_regression] ,axis=1) df_ptb.label_regression.apply(lambda x: np.float32(np.log(x))) if(len(lbl_itos_ptb_regression)==1): df_ptb.label_regression=df_ptb.label_regression.astype(np.float32) #set diagnosis_all multilabels def extract_multilabel(x, lbl_itos): ret = np.zeros(len(lbl_itos),dtype=np.float32) for xi in x: if(xi in lbl_itos): ret[lbl_itos.index(xi)]=1.0 return ret df_ptb["label_multi_all"]=df_ptb.diagnosis12.apply(lambda x: extract_multilabel(x, lbl_itos_ptb_all) if len(lbl_itos_ptb_all)>1 else int(lbl_itos_ptb_all[0] in x)) #permanently discard diagnosis n/a if(ptb_permanently_remove_diagnosis_na): df_ptb = df_ptb[df_ptb.diagnosis != "n/a"].copy() #permanently remove multiple ecgs if(ptb_permanently_remove_multiple_ecgs): df_ptb=df_ptb.sort_values(by='ecg') df_ptb["first_ecg"]=df_ptb.ecg.isin(df_ptb.groupby("patient").first().ecg) df_ptb["drop"]=df_ptb.ecg.isin(df_ptb[(df_ptb.diagnosis=="Myocardial infarction") & (df_ptb.first_ecg==False)].ecg) df_ptb=df_ptb[df_ptb["drop"]==False].reset_index().drop("index",axis=1) #discard other diagnosis classes that were not selected df_ptb2 = df_ptb[df_ptb.label <= len(lbl_itos_ptb)-1].copy() #select first record for MI patients if(ptb_select_only_first_mi): df_ptb2=df_ptb2.sort_values(by='ecg') df_ptb2["first_ecg"]=df_ptb2.ecg.isin(df_ptb2.groupby("patient").first().ecg) df_ptb2["drop"]=df_ptb2.ecg.isin(df_ptb2[(df_ptb2.diagnosis=="Myocardial infarction") & (df_ptb2.first_ecg==False)].ecg) df_ptb2=df_ptb2[df_ptb2["drop"]==False].reset_index().drop("index",axis=1) #remove MIs with unknown infarction status if(ptb_remove_unknown_loc_mi): df_ptb2=df_ptb2[~((df_ptb2.diagnosis=="Myocardial infarction") & (df_ptb2.infarction_localization==""))] #train test split for label (main diagnosis) based on patients label_patients=df_ptb2.groupby("patient")["diagnosis_extended"].first() splits_patients = get_stratified_kfolds(np.array(label_patients),n_splits=strat_folds,random_state=cv_random_state) df_ptb["strat_fold"] = -1 for i,split in enumerate(splits_patients): patients_valid = np.array(label_patients.index)[split[1]] #now select from ptb2 (as second MIs etc might have been excluded) ecgs_valid = np.array(df_ptb2[df_ptb2.patient.isin(patients_valid)]["ecg"]) df_ptb.loc[df_ptb.ecg.isin(ecgs_valid),"strat_fold"]=i #train test split for regression based on ecgs (but does not work properly anyway) df_ptb["strat_fold_regression"]=-1 df_ptb_regression = df_ptb[df_ptb.label_regression.apply(lambda x: np.isfinite(x))].copy() label_patients=df_ptb_regression.groupby("patient")["diagnosis_extended"].first() splits_patients = get_stratified_kfolds(np.array(label_patients),n_splits=strat_folds,random_state=cv_random_state) for i,split in enumerate(splits_patients): patients_valid = np.array(label_patients.index)[split[1]] #now select from ptb_regression ecgs_valid = np.array(df_ptb_regression[df_ptb_regression.patient.isin(patients_valid)]["ecg"]) df_ptb.loc[df_ptb.ecg.isin(ecgs_valid),"strat_fold_regression"]=i #train test split for label_multi_all (main diagnosis) based on patients label_patients=df_ptb.groupby("patient")["diagnosis_extended"].first() splits_patients = get_stratified_kfolds(np.array(label_patients),n_splits=strat_folds,random_state=cv_random_state) df_ptb["strat_fold_all"] = -1 for i,split in enumerate(splits_patients): patients_valid = np.array(label_patients.index)[split[1]] df_ptb.loc[df_ptb.patient.isin(patients_valid),"strat_fold_all"]=i #train test split for smoker based on patients df_ptb_smoker = df_ptb[df_ptb.label_smoker>=0].copy() label_patients=df_ptb_smoker.groupby("patient")["diagnosis_extended"].first() splits_patients = get_stratified_kfolds(np.array(label_patients),n_splits=strat_folds,random_state=cv_random_state) df_ptb["strat_fold_smoker"] = -1 for i,split in enumerate(splits_patients): patients_valid = np.array(label_patients.index)[split[1]] #now select from ptb_smoker ecgs_valid = np.array(df_ptb_smoker[df_ptb_smoker.patient.isin(patients_valid)]["ecg"]) df_ptb.loc[df_ptb.ecg.isin(ecgs_valid),"strat_fold_smoker"]=i #train test split for age based on patients df_ptb_age = df_ptb[df_ptb.label_age>=0].copy() label_patients=df_ptb_age.groupby("patient")["diagnosis_extended"].first() splits_patients = get_stratified_kfolds(np.array(label_patients),n_splits=strat_folds,random_state=cv_random_state) df_ptb["strat_fold_age"] = -1 for i,split in enumerate(splits_patients): patients_valid = np.array(label_patients.index)[split[1]] #now select from ptb_age ecgs_valid = np.array(df_ptb_age[df_ptb_age.patient.isin(patients_valid)]["ecg"]) df_ptb.loc[df_ptb.ecg.isin(ecgs_valid),"strat_fold_age"]=i #train test split for sex based on patients df_ptb_sex = df_ptb[df_ptb.label_sex>=0].copy() label_patients=df_ptb_sex.groupby("patient")["diagnosis_extended"].first() splits_patients = get_stratified_kfolds(np.array(label_patients),n_splits=strat_folds,random_state=cv_random_state) df_ptb["strat_fold_sex"] = -1 for i,split in enumerate(splits_patients): patients_valid = np.array(label_patients.index)[split[1]] #now select from ptb_sex ecgs_valid = np.array(df_ptb_sex[df_ptb_sex.patient.isin(patients_valid)]["ecg"]) df_ptb.loc[df_ptb.ecg.isin(ecgs_valid),"strat_fold_sex"]=i #DEBUG #importing old splits for debugging indexlst = np.load("./old/index_lst.npy") evallist = np.load("./old/evallist.npy") #trainlist = np.load("./old/trainlist.npy") df_ptb["strat_fold_old"] = -1 for i in range(len(evallist)): df_ptb.loc[df_ptb.ecg.isin(["PTB_"+x for x in indexlst[evallist[i]][:,1]]),"strat_fold_old"]=i #export current splits for debugging evallist =[] trainlist =[] for i in range(strat_folds): valid_ecgs= np.array(df_ptb[(df_ptb.strat_fold>=0)&(df_ptb.strat_fold==i)].ecg.apply(lambda x: x[4:])) train_ecgs= np.array(df_ptb[(df_ptb.strat_fold>=0)&(df_ptb.strat_fold!=i)].ecg.apply(lambda x: x[4:])) evallist.append([np.where(indexlst==v)[0][0] for v in valid_ecgs]) trainlist.append([np.where(indexlst==t)[0][0] for t in train_ecgs]) np.save("./old/evallist_new.npy",evallist) np.save("./old/trainlist_new.npy",trainlist) #add means and std dataset_add_mean_col(df_ptb,data_folder=target_root_ptb) dataset_add_std_col(df_ptb,data_folder=target_root_ptb) dataset_add_length_col(df_ptb,data_folder=target_root_ptb) #dataset_add_median_col(df_ptb,data_folder=target_folder) #dataset_add_iqr_col(df_ptb,data_folder=target_folder) #compute means and stds mean_ptb, std_ptb = dataset_get_stats(df_ptb) #save save_dataset(df_ptb,lbl_itos_ptb,mean_ptb,std_ptb,target_root_ptb) else: df_ptb, lbl_itos_ptb, mean_ptb, std_ptb = load_dataset(target_root_ptb,df_mapped=False) return df_ptb, lbl_itos_ptb, mean_ptb, std_ptb # Cell def mat_to_np(filename_in, target_fs=100, channels=12, channel_stoi=None, fs=500, target_folder=None): channel_labels=["i","ii", "iii", "avr", "avl", "avf", "v1", "v2", "v3", "v4", "v5", "v6"] filename_out, filename_out_relative = get_filename_out(filename_in, target_folder) channels_available = get_available_channels(channel_labels,channel_stoi) data_raw = scipy.io.loadmat(filename_in) sex,age,sigbufs=data_raw['ECG'][0][0] sigbufs =np.transpose(sigbufs) data = resample_data(sigbufs=sigbufs,channel_stoi=channel_stoi,channel_labels=channel_labels,fs=fs,target_fs=target_fs, channels=channels) np.save(filename_out, data.astype(np.float32)) return sex[0], age[0,0], channels_available, filename_out, filename_out_relative def reformat_data_icbeb(datafiles, labelfile, target_fs=100, channels=12, channel_stoi=channel_stoi_default, target_folder=None): #labels label_itos=["NORMAL","AF", "I-AVB","LBBB","RBBB","PAC","PVC","STD","STE"] labels=pd.read_csv(labelfile) labels.columns=["ecg","label1","label2","label3"] labels=labels.set_index("ecg") labels.label1=labels.label1.apply(lambda x: int(x) -1 if not np.isnan(x) else np.nan) labels.label2=labels.label2.apply(lambda x: int(x) -1 if not np.isnan(x) else np.nan) labels.label3=labels.label3.apply(lambda x: int(x) -1 if not np.isnan(x) else np.nan) #data rows=[] for d in tqdm(datafiles): sex,age,channels_available,filename_out,filename_out_relative=mat_to_np(filename_in=d, target_fs=target_fs, channels=channels, channel_stoi=channel_stoi, target_folder=target_folder) rows.append({"ecg":d.stem, "dataset":"ICBEB2018", "data":filename_out_relative, "age": (np.nan if np.isnan(age) else int(age)), "sex": sex.lower(), "channels_available":channels_available}) df=pd.DataFrame(rows) df=df.set_index("ecg") #join df=df.join(labels) df=df.reset_index() #define actual label (label 2 and label 3 are multilabels) df["label"]=df["label1"] df["has_label2"]=~pd.isna(df["label2"])#i.e. multilabeled label 3 will only be set if label 2 is df["has_label3"]=~pd.isna(df["label3"]) #age df["label_age"]=df.age.apply(lambda x: _age_to_categorical(x)) #sex df["label_sex"]=df.sex.apply(lambda x: _sex_to_categorical(x)) def multi_label(x): res = np.zeros(len(label_itos),dtype=np.float32) for xi in x: if(np.isfinite(xi) and int(xi) in list(range(len(label_itos)))): res[int(xi)]=1 return res def combine_labels(x): res = [x["label1"]] if(np.isfinite(x["label2"])): res += [int(x["label2"])] if(np.isfinite(x["label3"])): res += [int(x["label3"])] return res df["labels"]=df.apply(lambda x: combine_labels(x),axis=1) df["label_multi"]=df.labels.apply(lambda x:multi_label(x)) return df, label_itos def prepare_data_icbeb(data_folder, target_folder=None, channel_stoi=channel_stoi_default, channels=12, target_fs=50, strat_folds=10, cv_random_state=42,recreate_data=False,discard_valtest=True): target_root_icbeb = Path(".") if target_folder is None else target_folder if(recreate_data): #collect files datafiles_icbeb=list(data_folder.glob('**/*.mat')) labelfile_icbeb=data_folder/"REFERENCE.csv" #reformat data df_icbeb, lbl_itos_icbeb = reformat_data_icbeb(datafiles_icbeb,labelfile_icbeb,channel_stoi=channel_stoi,target_fs=target_fs,channels=channels,target_folder=target_folder) #TODO eventually move all the stuff below into reformat data #remove valid data df_icbeb["set"] = df_icbeb.data.apply(lambda x: (0 if "train" in x.parts else 1)) if(discard_valtest is True): df_icbeb=df_icbeb[df_icbeb["set"]==0].reset_index()#only train set has label else:#reset labels that have been set erroneously df_icbeb.loc[df_icbeb["set"]==1,"label"]=np.nan df_icbeb.loc[df_icbeb["set"]==1,"label_multi"]=np.nan df_icbeb.loc[df_icbeb["set"]==1,"label1"]=np.nan df_icbeb.loc[df_icbeb["set"]==1,"label2"]=np.nan df_icbeb.loc[df_icbeb["set"]==1,"label3"]=np.nan #train test split (all)
stratified_ids = stratify(list(df_icbeb["label_multi"]), range(len(lbl_itos_icbeb)), [1./strat_folds]*strat_folds)
0
2023-10-10 14:15:14+00:00
8k
zhaoyizhou1123/mbrcsl
examples/pointmaze/run_mbbc_maze.py
[ { "identifier": "evaluate_episode", "path": "envs/pointmaze/utils/evaluate_episodes.py", "snippet": "def evaluate_episode(\n env,\n state_dim,\n act_dim,\n model,\n max_ep_len=1000,\n device='cuda',\n target_return=None,\n mode='normal',\n s...
import numpy as np import torch import random import datetime import argparse import os import pickle from envs.pointmaze.utils.evaluate_episodes import evaluate_episode from offlinerlkit.policy import MLPBCModel from offlinerlkit.policy_trainer import ActTrainer from offlinerlkit.utils.logger import Logger, make_log_dirs from offlinerlkit.utils.set_up_seed import set_up_seed from offlinerlkit.utils.trajectory import Dict2Traj from envs.pointmaze.create_maze_dataset import create_env from envs.pointmaze.utils.maze_utils import PointMazeObsWrapper
4,128
def get_args(): parser = argparse.ArgumentParser() # general parser.add_argument("--algo_name", type=str, default="mbbc") parser.add_argument("--task", type=str, default="pointmaze", help="task name") parser.add_argument("--seed", type=int, default=0) parser.add_argument("--num_workers", type=int, default=1, help="Dataloader workers, align with cpu number") parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu") parser.add_argument("--last_eval", action="store_true") # env config parser.add_argument('--horizon', type=int, default=200, help="max path length for pickplace") parser.add_argument('--rollout_ckpt_path', type=str, required=True, help="dir path, used to load mbrcsl rollout trajectories") parser.add_argument('--maze_config_file', type=str, default='envs/pointmaze/config/maze_default.json') # mlp bc policy parser.add_argument('--ctx', type=int, default=20) parser.add_argument('--data_ratio', type = float, default=0.1, help="%BC") parser.add_argument('--embed_dim', type=int, default=128) parser.add_argument('--n_layer', type=int, default=3) # training parser.add_argument('--batch_size', type=int, default=256) parser.add_argument("--eval_episodes", type=int, default=10) parser.add_argument("--epoch", type=int, default=100) parser.add_argument('--warmup_steps', type=int, default=10000) parser.add_argument('--lr', type=float, default=1e-4, help="learning rate of Trainer" ) parser.add_argument('--weight_decay', '-wd', type=float, default=1e-4) parser.add_argument("--step_per_epoch", type=int, default=1000) args = parser.parse_args() return args def discount_cumsum(x, gamma): discount_cumsum = np.zeros_like(x) discount_cumsum[-1] = x[-1] for t in reversed(range(x.shape[0]-1)): discount_cumsum[t] = x[t] + gamma * discount_cumsum[t+1] return discount_cumsum def train(args = get_args()): variant = vars(args) device = variant.get('device', 'cuda') env_name = variant['task'] model_type = variant['algo_name'] set_up_seed(args.seed) # create env and dataset if args.task == 'pointmaze': env = create_env(args)
def get_args(): parser = argparse.ArgumentParser() # general parser.add_argument("--algo_name", type=str, default="mbbc") parser.add_argument("--task", type=str, default="pointmaze", help="task name") parser.add_argument("--seed", type=int, default=0) parser.add_argument("--num_workers", type=int, default=1, help="Dataloader workers, align with cpu number") parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu") parser.add_argument("--last_eval", action="store_true") # env config parser.add_argument('--horizon', type=int, default=200, help="max path length for pickplace") parser.add_argument('--rollout_ckpt_path', type=str, required=True, help="dir path, used to load mbrcsl rollout trajectories") parser.add_argument('--maze_config_file', type=str, default='envs/pointmaze/config/maze_default.json') # mlp bc policy parser.add_argument('--ctx', type=int, default=20) parser.add_argument('--data_ratio', type = float, default=0.1, help="%BC") parser.add_argument('--embed_dim', type=int, default=128) parser.add_argument('--n_layer', type=int, default=3) # training parser.add_argument('--batch_size', type=int, default=256) parser.add_argument("--eval_episodes", type=int, default=10) parser.add_argument("--epoch", type=int, default=100) parser.add_argument('--warmup_steps', type=int, default=10000) parser.add_argument('--lr', type=float, default=1e-4, help="learning rate of Trainer" ) parser.add_argument('--weight_decay', '-wd', type=float, default=1e-4) parser.add_argument("--step_per_epoch", type=int, default=1000) args = parser.parse_args() return args def discount_cumsum(x, gamma): discount_cumsum = np.zeros_like(x) discount_cumsum[-1] = x[-1] for t in reversed(range(x.shape[0]-1)): discount_cumsum[t] = x[t] + gamma * discount_cumsum[t+1] return discount_cumsum def train(args = get_args()): variant = vars(args) device = variant.get('device', 'cuda') env_name = variant['task'] model_type = variant['algo_name'] set_up_seed(args.seed) # create env and dataset if args.task == 'pointmaze': env = create_env(args)
env = PointMazeObsWrapper(env)
8
2023-10-11 08:36:06+00:00
8k
khuongav/Graphical-Adversarial-Modeling-of-EEG
train.py
[ { "identifier": "get_data_loader", "path": "data.py", "snippet": "def get_data_loader(dataset_prefix, batch_size, device, shuffle=True, preload_gpu=False, training=True, ictal=False):\n train_1_data_path, train_3_data_path, train_5_data_path, train_2_data_path, train_6_data_path, train_10_data_path =...
import argparse import time import datetime import os import sys import numpy as np import torch import torch.fft as fft from torch.nn import init from torch.utils.tensorboard import SummaryWriter from torch.distributions import OneHotCategorical from models import * from data import get_data_loader from utils import to_device, plot_freq_domain, plot_time_domain, set_seed
4,343
# ---------------------------- # Train Generators and Extractors # ---------------------------- reset_gradients_to_train(models_GE) # GMM fake_validity_GGMM = discriminatorGMM(k_p, h_p) err_GGMM = criterion(fake_validity_GGMM, real) err_GGMM.backward(retain_graph=True) real_validity_EGMM = discriminatorGMM(k_q, h_q) err_EGMM = criterion(real_validity_EGMM, fake) err_EGMM.backward(retain_graph=True) for idx in range(T): # G fake_validity_GG = discriminator1( x_T_p[idx], h_p, v_T_p[idx], conds) err_GG = criterion(fake_validity_GG, real) err_GG_T.append(err_GG.item()) err_GG.backward(retain_graph=True) # E real_validity_E1 = discriminator1( x_T_q[idx], h_q, v_T_q[idx], conds) err_E1 = criterion(real_validity_E1, fake) err_E1_T.append(err_E1.item()) err_E1.backward(retain_graph=True) if idx < T - 1: # G fake_validity_GO = discriminator2(v_T_p[idx], v_T_p[idx + 1]) err_GO = criterion(fake_validity_GO, real) err_GO_T.append(err_GO.item()) err_GO.backward(retain_graph=True) # E real_validity_E2 = discriminator2(v_T_q[idx], v_T_q[idx + 1]) err_E2 = criterion(real_validity_E2, fake) err_E2_T.append(err_E2.item()) err_E2.backward(retain_graph=True) gen_samples = torch.cat(x_T_p, dim=-1) loss_v = moment_loss(gen_samples, X_q) * args.delta_mome loss_fft = fft_loss(gen_samples, X_q) * args.omega_fft (loss_fft + loss_v).backward() optimizer_EMB.step() optimizer_G.step() optimizer_E.step() # -------------- # Log Progress # -------------- # Determine approximate time left batches_done = epoch * len(dataloader) + i batches_left = args.n_epochs * len(dataloader) - batches_done time_left = datetime.timedelta( seconds=batches_left * (time.time() - prev_time)) prev_time = time.time() # Print log sys.stdout.write( "\r[Epoch %d/%d] [Batch %d/%d] [err_GG: %f] [err_GO: %f] [err_E1: %f] [err_E2: %f] [err_D1: %f] [err_D2: %f] [err_DGM: %f] [err_V: %f] [err_F: %f] ETA: %s" % (epoch, args.n_epochs, i, len(dataloader), np.mean(err_GG_T), np.mean(err_GO_T), np.mean(err_E1_T), np.mean(err_E2_T), np.mean(err_D1_T), np.mean(err_D2_T), err_DGMM.item(), loss_v, loss_fft.item(), time_left) ) if args.checkpoint_interval != -1 and epoch % args.checkpoint_interval == 0: viz_histograms(models, epoch) # Save model checkpoints torch.save({ 'epoch': epoch, 'com_mu_state_dict': com_mu_sig.state_dict(), 'generatorG_state_dict': generatorG.state_dict(), 'generatorO_state_dict': generatorO.state_dict(), 'extractor1_state_dict': extractor1.state_dict(), 'extractor2_state_dict': extractor2.state_dict(), 'hyper_extractor_state_dict': hyper_extractor.state_dict(), 'discriminator1_state_dict': discriminator1.state_dict(), 'discriminator2_state_dict': discriminator2.state_dict(), 'discriminatorGMM_state_dict': discriminatorGMM.state_dict(), 'optimizer_EMB_state_dict': optimizer_EMB.state_dict(), 'optimizer_G_state_dict': optimizer_G.state_dict(), 'optimizer_E_state_dict': optimizer_E.state_dict(), 'optimizer_D_state_dict': optimizer_D.state_dict(), }, "saved_models/%s/multi_models_%s.pth" % (args.experiment_name, epoch)) com_mu_sig.eval() generatorG.eval() generatorO.eval() with torch.no_grad(): if args.preload_gpu: valid_data = next(iter(dataloader))[0] else: valid_data = next(iter(dataloader)) valid_data = valid_data.squeeze()[:, 12, :].detach().cpu() patient = torch.from_numpy(np.array([val_patient] * args.batch_size)).float().to(device) k_p = prior_k.sample((args.batch_size,)).to(device) hyper_noise = torch.randn(args.batch_size, LATENT_DIM, device=device) h_p = hyper_generator(com_mu_sig, k_p, hyper_noise) vt_p = torch.randn(bs, V_DIM, device=device) x_T_p = [] for idx in range(T): xt_p = generatorG(h_p, vt_p, patient) x_T_p.append(xt_p) if idx < T - 1: epst_p = torch.randn(bs, EPS_DIM, device=device) vt_p = generatorO(vt_p, epst_p) gen_samples = torch.cat(x_T_p, dim=-1).squeeze()[:, 12, :].detach().cpu() img_dir = "sample_signals/%s/time_%s.png" % (args.experiment_name, epoch)
set_seed() parser = argparse.ArgumentParser() parser.add_argument("--experiment_name", type=str, default="gmmarkov-gan", help="name of the experiment") parser.add_argument("--dataset_prefix", type=str, default="eeg_dataset/", help="path to the train and valid dataset") parser.add_argument("--epoch", type=int, default=0, help="epoch to start training from") parser.add_argument("--shuffle", type=bool, default=True, help="shuffle dataset") parser.add_argument("--is_eval", type=bool, default=False, help="evaluation mode") parser.add_argument("--gpu_idx", type=int, default=0, help="GPU index") parser.add_argument("--n_epochs", type=int, default=601, help="number of epochs of training") parser.add_argument("--batch_size", type=int, default=128, help="size of the batches") parser.add_argument("--lr", type=float, default=1e-4, help="adam: learning rate") parser.add_argument("--lr_disc", type=float, default=4e-4, help="adam: discriminator learning rate") parser.add_argument("--b1", type=float, default=0.5, help="adam: decay of first order momentum of gradient") parser.add_argument("--b2", type=float, default=0.999, help="adam: decay of first order momentum of gradient") parser.add_argument("--delta_mome", type=float, default=10, help="Loss weight for moments"), parser.add_argument("--omega_fft", type=float, default=0.1, help="Loss weight for FFT"), parser.add_argument("--preload_gpu", type=bool, default=True, help="Preload data to GPU") parser.add_argument("--sampling_rate", type=int, default=256, help="sampling rate of the signals") parser.add_argument("--checkpoint_interval", type=int, default=20, help="interval between model checkpoints") args, unknown = parser.parse_known_args() print(args) device = torch.device('cuda:%s' % args.gpu_idx if torch.cuda.is_available() else 'cpu') cuda = True if torch.cuda.is_available() else False print(cuda, device) tb = SummaryWriter("logs/%s" % args.experiment_name) # ------------------ def init_weights(models): for model in models: model.apply(weights_init_normal) def viz_histograms(models, epoch): for model in models: for name, weight in model.named_parameters(): try: tb.add_histogram(name, weight, epoch) tb.add_histogram(f'{name}.grad', weight.grad, epoch) except NotImplementedError: continue def reset_gradients_to_train(models): for model in models: model.train() for p in model.parameters(): p.grad = None def moment_loss(X_p, X_q): loss_v1 = criterion_moments(X_p.mean(dim=0), X_q.mean(dim=0).detach()) loss_v2 = criterion_moments( X_p.std(dim=0) + 1e-6, X_q.std(dim=0).detach() + 1e-6) loss_v = loss_v1 + loss_v2 return loss_v def fft_loss(X_p, X_q): fft_fake_x = fft.rfft(X_p) fft_abs_fake_x = torch.abs(fft_fake_x).mean(dim=0) fft_phase_fake_x = torch.angle(fft_fake_x).mean(dim=0) fft_real_x = fft.rfft(X_q) fft_abs_real_x = torch.abs(fft_real_x).mean(dim=0) fft_phase_real_x = torch.angle(fft_real_x).mean(dim=0) loss_fft_abs_x = criterion_fft(fft_abs_fake_x, fft_abs_real_x) loss_fft_phase_x = criterion_fft(fft_phase_fake_x, fft_phase_real_x) loss_fft = loss_fft_abs_x + loss_fft_phase_x return loss_fft os.makedirs("saved_models/%s" % args.experiment_name, exist_ok=True) os.makedirs("sample_signals/%s" % args.experiment_name, exist_ok=True) os.makedirs("logs/%s" % args.experiment_name, exist_ok=True) # Load data dataloader = get_data_loader(args.dataset_prefix, args.batch_size, device=device, shuffle=args.shuffle, preload_gpu=args.preload_gpu) # Initialize generator and discriminator N_GM = 10 PI = torch.tensor([1. / N_GM, ] * N_GM) LATENT_DIM = 128 EPS_DIM = 16 V_DIM = 32 C_SIZE = 6 T = 10 ECHANNELS = 23 d = 24 split_size = args.sampling_rate val_patient = [0, 1, 0, 0, 0, 0] prior_k = OneHotCategorical(PI) com_mu_sig = GMM(N_GM, LATENT_DIM) generatorG = GeneratorG(h_size=LATENT_DIM, v_size=V_DIM, c_size=C_SIZE, echannels=ECHANNELS, d=d) generatorO = DynamicGeneratorO(v_size=V_DIM) extractor1 = Extractor1(h_size=LATENT_DIM, c_size=C_SIZE, T=T, echannels=ECHANNELS, d=d) extractor2 = DynamicExtractor2(v_size=V_DIM, echannels=ECHANNELS, d=d) hyper_extractor = HyperExtractor(z_size=LATENT_DIM, n_gm=N_GM) discriminator1 = Discriminator1(h_size=LATENT_DIM, v_size=V_DIM, c_size=C_SIZE, echannels=ECHANNELS, d=d) discriminator2 = Discriminator2(v_size=V_DIM) discriminatorGMM = DiscriminatorGMM(k_size=N_GM, z_size=LATENT_DIM) models_GE = [com_mu_sig, generatorG, generatorO, extractor1, extractor2, hyper_extractor] models_D = [discriminator1, discriminator2, discriminatorGMM] models = models_GE + models_D criterion = torch.nn.BCEWithLogitsLoss() criterion_moments = torch.nn.L1Loss() criterion_fft = torch.nn.L1Loss() # Optimizers optimizer_EMB = torch.optim.Adam( com_mu_sig.parameters(), lr=args.lr, betas=(args.b1, args.b2)) optimizer_G = torch.optim.Adam( list(generatorG.parameters()) + list(generatorO.parameters()), lr=args.lr, betas=(args.b1, args.b2)) optimizer_E = torch.optim.Adam( list(extractor1.parameters()) + list(extractor2.parameters()), lr=args.lr, betas=(args.b1, args.b2)) optimizer_D = torch.optim.Adam( list(discriminator1.parameters()) + list(discriminator2.parameters()) + list(discriminatorGMM.parameters()), lr=args.lr_disc, betas=(args.b1, args.b2)) if cuda: to_device(models, device) PI = PI.to(device) criterion = criterion.to(device) criterion_moments = criterion_moments.to(device) criterion_fft = criterion_fft.to(device) if args.epoch != 0: # Load pretrained models pretrained_path = "saved_models/%s/multi_models_%s.pth" % (args.experiment_name, args.epoch) checkpoint = torch.load(pretrained_path, map_location=device) com_mu_sig.load_state_dict(checkpoint['com_mu_state_dict']) generatorG.load_state_dict(checkpoint['generatorG_state_dict']) generatorO.load_state_dict(checkpoint['generatorO_state_dict']) extractor1.load_state_dict(checkpoint['extractor1_state_dict']) extractor2.load_state_dict(checkpoint['extractor2_state_dict']) hyper_extractor.load_state_dict(checkpoint['hyper_extractor_state_dict']) discriminator1.load_state_dict(checkpoint['discriminator1_state_dict']) discriminator2.load_state_dict(checkpoint['discriminator2_state_dict']) discriminatorGMM.load_state_dict(checkpoint['discriminatorGMM_state_dict']) optimizer_EMB.load_state_dict(checkpoint['optimizer_EMB_state_dict']) optimizer_G.load_state_dict(checkpoint['optimizer_G_state_dict']) optimizer_E.load_state_dict(checkpoint['optimizer_E_state_dict']) optimizer_D.load_state_dict(checkpoint['optimizer_D_state_dict']) else: # Initialize weights init_weights(models[1:]) prev_time = time.time() for epoch in range(args.epoch+1, args.n_epochs): for i, batch in enumerate(dataloader): # Model inputs if args.preload_gpu: X_q, conds = batch[0], batch[1] else: X_q = batch.to(device, non_blocking=True).squeeze() bs = len(X_q) real = torch.full((bs, 1), 1, dtype=torch.float, device=device) real_soft = torch.full((bs, 1), 1, dtype=torch.float, device=device) fake = torch.full((bs, 1), 0, dtype=torch.float, device=device) err_GG_T, err_GO_T, err_E1_T, err_E2_T, err_V_T, err_D1_T, err_D2_T = [], [], [], [], [], [], [] # ---------------------------- # Train Discriminators # ---------------------------- reset_gradients_to_train(models_D) # GMM hyper_noise = torch.randn(bs, LATENT_DIM, device=device) k_p = prior_k.sample((bs,)).to(device) h_p = hyper_generator(com_mu_sig, k_p, hyper_noise) x_T_q = torch.split(X_q, split_size_or_sections=split_size, dim=-1) h_q, mu_q, sig_q = extractor1(x_T_q, device, conds) k_q = hyper_extractor(h_q) fake_validity = discriminatorGMM(k_p.detach(), h_p.detach()) err_DGMM_fake = criterion(fake_validity, fake) err_DGMM_fake.backward() real_validity = discriminatorGMM(k_q.detach(), h_q.detach()) err_DGMM_real = criterion(real_validity, real_soft) err_DGMM_real.backward() err_DGMM = err_DGMM_real + err_DGMM_fake x_T_p = [] v_T_p = [] v_T_q = [] vt_p = torch.randn(bs, V_DIM, device=device) xt_q = x_T_q[0] vt_q = extractor2(xt_q) for idx in range(T): xt_p = generatorG(h_p, vt_p, conds) x_T_p.append(xt_p) v_T_p.append(vt_p) v_T_q.append(vt_q) # D1 fake_validity = discriminator1(xt_p.detach(), h_p.detach(), vt_p.detach(), conds) err_D1_fake = criterion(fake_validity, fake) err_D1_fake.backward() real_validity = discriminator1(xt_q.detach(), h_q.detach(), vt_q.detach(), conds) err_D1_real = criterion(real_validity, real_soft) err_D1_real.backward() err_D1_T.append(err_D1_real.item() + err_D1_fake.item()) if idx < T - 1: epst_p = torch.randn(bs, EPS_DIM, device=device) vtnext_p = generatorO(vt_p, epst_p) xtnext_q = x_T_q[idx + 1] vtnext_q = extractor2(xtnext_q) # D2 fake_validity = discriminator2(vt_p.detach(), vtnext_p.detach()) err_D2_fake = criterion(fake_validity, fake) err_D2_fake.backward() real_validity = discriminator2(vt_q.detach(), vtnext_q.detach()) err_D2_real = criterion(real_validity, real_soft) err_D2_real.backward() err_D2_T.append(err_D2_real.item() + err_D2_fake.item()) vt_p = vtnext_p vt_q = vtnext_q xt_q = xtnext_q optimizer_D.step() # ---------------------------- # Train Generators and Extractors # ---------------------------- reset_gradients_to_train(models_GE) # GMM fake_validity_GGMM = discriminatorGMM(k_p, h_p) err_GGMM = criterion(fake_validity_GGMM, real) err_GGMM.backward(retain_graph=True) real_validity_EGMM = discriminatorGMM(k_q, h_q) err_EGMM = criterion(real_validity_EGMM, fake) err_EGMM.backward(retain_graph=True) for idx in range(T): # G fake_validity_GG = discriminator1( x_T_p[idx], h_p, v_T_p[idx], conds) err_GG = criterion(fake_validity_GG, real) err_GG_T.append(err_GG.item()) err_GG.backward(retain_graph=True) # E real_validity_E1 = discriminator1( x_T_q[idx], h_q, v_T_q[idx], conds) err_E1 = criterion(real_validity_E1, fake) err_E1_T.append(err_E1.item()) err_E1.backward(retain_graph=True) if idx < T - 1: # G fake_validity_GO = discriminator2(v_T_p[idx], v_T_p[idx + 1]) err_GO = criterion(fake_validity_GO, real) err_GO_T.append(err_GO.item()) err_GO.backward(retain_graph=True) # E real_validity_E2 = discriminator2(v_T_q[idx], v_T_q[idx + 1]) err_E2 = criterion(real_validity_E2, fake) err_E2_T.append(err_E2.item()) err_E2.backward(retain_graph=True) gen_samples = torch.cat(x_T_p, dim=-1) loss_v = moment_loss(gen_samples, X_q) * args.delta_mome loss_fft = fft_loss(gen_samples, X_q) * args.omega_fft (loss_fft + loss_v).backward() optimizer_EMB.step() optimizer_G.step() optimizer_E.step() # -------------- # Log Progress # -------------- # Determine approximate time left batches_done = epoch * len(dataloader) + i batches_left = args.n_epochs * len(dataloader) - batches_done time_left = datetime.timedelta( seconds=batches_left * (time.time() - prev_time)) prev_time = time.time() # Print log sys.stdout.write( "\r[Epoch %d/%d] [Batch %d/%d] [err_GG: %f] [err_GO: %f] [err_E1: %f] [err_E2: %f] [err_D1: %f] [err_D2: %f] [err_DGM: %f] [err_V: %f] [err_F: %f] ETA: %s" % (epoch, args.n_epochs, i, len(dataloader), np.mean(err_GG_T), np.mean(err_GO_T), np.mean(err_E1_T), np.mean(err_E2_T), np.mean(err_D1_T), np.mean(err_D2_T), err_DGMM.item(), loss_v, loss_fft.item(), time_left) ) if args.checkpoint_interval != -1 and epoch % args.checkpoint_interval == 0: viz_histograms(models, epoch) # Save model checkpoints torch.save({ 'epoch': epoch, 'com_mu_state_dict': com_mu_sig.state_dict(), 'generatorG_state_dict': generatorG.state_dict(), 'generatorO_state_dict': generatorO.state_dict(), 'extractor1_state_dict': extractor1.state_dict(), 'extractor2_state_dict': extractor2.state_dict(), 'hyper_extractor_state_dict': hyper_extractor.state_dict(), 'discriminator1_state_dict': discriminator1.state_dict(), 'discriminator2_state_dict': discriminator2.state_dict(), 'discriminatorGMM_state_dict': discriminatorGMM.state_dict(), 'optimizer_EMB_state_dict': optimizer_EMB.state_dict(), 'optimizer_G_state_dict': optimizer_G.state_dict(), 'optimizer_E_state_dict': optimizer_E.state_dict(), 'optimizer_D_state_dict': optimizer_D.state_dict(), }, "saved_models/%s/multi_models_%s.pth" % (args.experiment_name, epoch)) com_mu_sig.eval() generatorG.eval() generatorO.eval() with torch.no_grad(): if args.preload_gpu: valid_data = next(iter(dataloader))[0] else: valid_data = next(iter(dataloader)) valid_data = valid_data.squeeze()[:, 12, :].detach().cpu() patient = torch.from_numpy(np.array([val_patient] * args.batch_size)).float().to(device) k_p = prior_k.sample((args.batch_size,)).to(device) hyper_noise = torch.randn(args.batch_size, LATENT_DIM, device=device) h_p = hyper_generator(com_mu_sig, k_p, hyper_noise) vt_p = torch.randn(bs, V_DIM, device=device) x_T_p = [] for idx in range(T): xt_p = generatorG(h_p, vt_p, patient) x_T_p.append(xt_p) if idx < T - 1: epst_p = torch.randn(bs, EPS_DIM, device=device) vt_p = generatorO(vt_p, epst_p) gen_samples = torch.cat(x_T_p, dim=-1).squeeze()[:, 12, :].detach().cpu() img_dir = "sample_signals/%s/time_%s.png" % (args.experiment_name, epoch)
plot_time_domain(valid_data, gen_samples, img_dir)
3
2023-10-08 23:39:18+00:00
8k
tarsil/polyforce
polyforce/_internal/_construction.py
[ { "identifier": "MissingAnnotation", "path": "polyforce/exceptions.py", "snippet": "class MissingAnnotation(PolyException):\n detail: Union[\n str, None\n ] = \"'{name}' is not typed. If you are not sure, annotate with 'typing.Any'.\"\n\n def __init__(self, name: str) -> None:\n d...
import inspect from abc import ABCMeta from inspect import Parameter, Signature from itertools import islice from typing import ( TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, Set, Tuple, Type, Union, _SpecialForm, cast, ) from typing_extensions import dataclass_transform from polyforce.exceptions import MissingAnnotation, ReturnSignatureMissing, ValidationError from ..constants import INIT_FUNCTION, SPECIAL_CHECK from ..core._polyforce_core import PolyforceUndefined from ..decorator import polycheck from ..fields import Field, PolyField from ._config import ConfigWrapper from ._errors import ErrorDetail from ._serializer import json_serializable from ..main import PolyModel from ..main import PolyModel
6,808
INIT_FUNCTION not in cls.__dict__ and INIT_FUNCTION not in cls.__signature__ ): methods.append(INIT_FUNCTION) signatures: Dict[str, Signature] = {} for method in methods: signatures[method] = generate_model_signature(cls, method, config) cls.__signature__.update(signatures) # Special decorator for the __init__ since it is not manipulated by the # __getattribute__ functionality if INIT_FUNCTION in cls.__dict__ or ( INIT_FUNCTION not in cls.__dict__ and INIT_FUNCTION not in cls.__signature__ ): decorate_function(cls, config) # Generate the PolyFields for value, signature in cls.__signature__.items(): for param in signature.parameters.values(): # Generate the PolyField for each function. generate_polyfields(cls, value, param) return True def decorate_function(cls: Type["PolyModel"], config: ConfigWrapper) -> None: """ Decorates the __init__ function to make sure it can apply the validations upon instantiation. The `__init__` is not called inside the `__getattribute__` and therefore the polycheck decorator is applied. """ signature: Signature = cls.__signature__["__init__"] decorator = polycheck(signature=signature, **config.config) init_func = decorator(cls.__init__) cls.__init__ = init_func # type: ignore[method-assign] def ignore_signature(signature: Signature) -> Signature: """ Ignores the signature and assigns the Any type to all the fields and the return signature. Args: signature (Signature): The signature to ignore. Returns: Signature: The modified signature with Any types. This function ignores the signature and assigns the Any type to all the fields and the return signature. """ merged_params: Dict[str, Parameter] = {} for param in islice(signature.parameters.values(), 1, None): param = param.replace(annotation=Any) merged_params[param.name] = param return Signature(parameters=list(merged_params.values()), return_annotation=Any) def generate_polyfields( cls: Type["PolyModel"], method: str, parameter: Parameter ) -> Dict[str, Dict[str, PolyField]]: """ For all the fields found in the signature, it will generate PolyField type variable. When generating PolyFields, it matches if there is already a PolyField generated by the Field() type. """ if not isinstance(parameter.default, PolyField): data = { "annotation": parameter.annotation, "name": parameter.name, "default": PolyforceUndefined if parameter.default == Signature.empty else parameter.default, } field = PolyField(**data) else: field = parameter.default field.annotation = parameter.annotation field.name = parameter.name field._validate_default_with_annotation() field_data = {parameter.name: field} if method not in cls.poly_fields: cls.poly_fields[method] = {} cls.poly_fields[method].update(field_data) return cls.poly_fields def generate_model_signature( cls: Type["PolyModel"], value: str, config: ConfigWrapper ) -> Signature: """ Generates a signature for each method of the given class. Args: cls (Type[PolyModel]): The PolyModel class. value (str): The method name. config (ConfigWrapper): Configuration wrapper. Returns: Signature: The generated signature. This function generates a signature for each method of the given class. """ func_type = inspect.getattr_static(cls, value) func = func_type.__func__ if isinstance(func_type, (classmethod, staticmethod)) else func_type signature = Signature.from_callable(func) if config.ignore: return ignore_signature(signature) params = signature.parameters.values() merged_params: Dict[str, Parameter] = {} if signature.return_annotation == inspect.Signature.empty:
if TYPE_CHECKING: object_setattr = object.__setattr__ @dataclass_transform(kw_only_default=True, field_specifiers=(Field,)) class PolyMetaclass(ABCMeta): """ Base metaclass used for the PolyModel objects and applies all static type checking needed for all the functions and methods of a given class. """ __filtered_functions__: Set[str] __signature__: ClassVar[Dict[str, Signature]] = {} def __new__( cls: Type["PolyMetaclass"], name: str, bases: Tuple[Type], attrs: Dict[str, Any], **kwargs: Any, ) -> Type["PolyModel"]: """ Create a new class using the PolyMetaclass. Args: cls (Type["PolyMetaclass"]): The metaclass. name (str): The name of the class. bases (Tuple[Type]): The base classes. attrs (Dict[str, Any]): The class attributes. Returns: Type["PolyModel"]: The new class. This method creates a new class using the PolyMetaclass and applies static type checking. """ if bases: base_class_vars = cls._collect_data_from_bases(bases) config_wrapper = ConfigWrapper.for_model(bases, attrs) attrs["config"] = config_wrapper.config attrs["__class_vars__"] = base_class_vars model = cast("Type[PolyModel]", super().__new__(cls, name, bases, attrs)) parents = [parent for parent in bases if isinstance(parent, PolyMetaclass)] if not parents: return model model.__polymodel_custom_init__ = not getattr( model.__init__, "__polymodel_base_init__", False ) # Making sure the PolyFields are only from this class object. model.poly_fields = {} model.__signature__ = {} complete_poly_class(model, bases, config_wrapper) return model return cast("Type[PolyModel]", super().__new__(cls, name, bases, attrs)) @staticmethod def _collect_data_from_bases(bases: Tuple[Type]) -> Set[str]: """ Collect class variables from base classes. Args: bases (Tuple[Type]): Base classes. Returns: Set[str]: Set of class variables. This method collects class variables from the base classes. """ class_vars: Set[str] = set() for base in bases: if issubclass(base, PolyModel) and base is not PolyModel: class_vars.update(base.__class_vars__) return class_vars def __getattribute__(self, name: str) -> Any: """ Get an attribute with static type checking. Args: name (str): The name of the attribute to access. Returns: Any: The value of the attribute. Raises: AttributeError: If the attribute does not exist. Example: ``` obj = MyObject(42) value = obj.value # Accessing the 'value' attribute ``` """ try: func = super().__getattribute__(name) __signature__: Dict[str, Any] = super().__getattribute__("__signature__") signature: Union[Signature, None] = __signature__.get(name, None) if signature is not None and name not in SPECIAL_CHECK: return self._add_static_type_checking(func, signature) else: return func except (KeyError, AttributeError): return object.__getattribute__(self, name) def _extract_type_hint(self, type_hint: Union[Type, tuple]) -> Any: """ Extracts the base type from a type hint, considering typing extensions. This function checks if the given type hint is a generic type hint and extracts the base type. If not, it returns the original type hint. Args: type_hint (Union[Type, tuple]): The type hint to extract the base type from. Returns: Union[Type, tuple]: The base type of the type hint or the original type hint. Example: ``` from typing import List, Union # Extract the base type from a List hint base_type = extract_type_hint(List[int]) # Returns int # If the hint is not a generic type, it returns the original hint original_hint = extract_type_hint(Union[int, str]) # Returns Union[int, str] ``` """ origin = getattr(type_hint, "__origin__", type_hint) if isinstance(origin, _SpecialForm): origin = type_hint.__args__ # type: ignore return origin def _add_static_type_checking( self: Type["PolyModel"], func: Any, signature: Signature ) -> Callable: """ Add static type checking to a method or function. Args: func (Any): The method or function to add type checking to. signature (Signature): The method's signature for type checking. Returns: Callable: A wrapped function with type checking. Example: ``` def my_method(self, value: int) -> str: return str(value) obj = MyObject(42) obj.__signature__['my_method'] = inspect.signature(my_method) # Accessing 'my_method' will now perform type checking result = obj.my_method(42) # This is valid result = obj.my_method("42") # This will raise a TypeError ``` """ def polycheck(*args: Any, **kwargs: Any) -> Any: bound = signature.bind(*args, **kwargs) bound.apply_defaults() for name, value in bound.arguments.items(): if name in self.poly_fields[func.__name__]: field: PolyField = self.poly_fields[func.__name__][name] expected_type = field.annotation if expected_type in (_SpecialForm, Any): continue expected_args = self._extract_type_hint(expected_type) if isinstance(expected_args, tuple): if any(value == Any for value in expected_args): continue if not isinstance(value, expected_args): expected_value = ( tuple(value.__name__ for value in expected_args) if isinstance(expected_args, tuple) else expected_args.__name__ ) error_message: str = ( f"Expected '{expected_value}' for attribute '{name}', " f"but received type '{type(value).__name__}'." ) error: ErrorDetail = ErrorDetail( source=self.__name__, value=json_serializable(value), input=name, expected=expected_value, message=error_message, ) raise ValidationError.from_exception_data([error]) return func(*args, **kwargs) return polycheck def complete_poly_class(cls: Type["PolyModel"], bases: Tuple[Type], config: ConfigWrapper) -> bool: """ Completes the polyclass model construction and applies all the fields and configurations. Args: cls (Type[PolyModel]): The PolyModel class to complete. config (ConfigWrapper): Configuration wrapper. Returns: bool: True if the completion was successful. This function completes the PolyModel class construction and applies fields and configurations. """ methods: List[str] = [ attr for attr in cls.__dict__.keys() if not attr.startswith("__") and not attr.endswith("__") and inspect.isroutine(getattr(cls, attr)) ] for base in bases: if hasattr(base, "__signature__"): cls.__signature__.update(base.__signature__) if INIT_FUNCTION in cls.__dict__ or ( INIT_FUNCTION not in cls.__dict__ and INIT_FUNCTION not in cls.__signature__ ): methods.append(INIT_FUNCTION) signatures: Dict[str, Signature] = {} for method in methods: signatures[method] = generate_model_signature(cls, method, config) cls.__signature__.update(signatures) # Special decorator for the __init__ since it is not manipulated by the # __getattribute__ functionality if INIT_FUNCTION in cls.__dict__ or ( INIT_FUNCTION not in cls.__dict__ and INIT_FUNCTION not in cls.__signature__ ): decorate_function(cls, config) # Generate the PolyFields for value, signature in cls.__signature__.items(): for param in signature.parameters.values(): # Generate the PolyField for each function. generate_polyfields(cls, value, param) return True def decorate_function(cls: Type["PolyModel"], config: ConfigWrapper) -> None: """ Decorates the __init__ function to make sure it can apply the validations upon instantiation. The `__init__` is not called inside the `__getattribute__` and therefore the polycheck decorator is applied. """ signature: Signature = cls.__signature__["__init__"] decorator = polycheck(signature=signature, **config.config) init_func = decorator(cls.__init__) cls.__init__ = init_func # type: ignore[method-assign] def ignore_signature(signature: Signature) -> Signature: """ Ignores the signature and assigns the Any type to all the fields and the return signature. Args: signature (Signature): The signature to ignore. Returns: Signature: The modified signature with Any types. This function ignores the signature and assigns the Any type to all the fields and the return signature. """ merged_params: Dict[str, Parameter] = {} for param in islice(signature.parameters.values(), 1, None): param = param.replace(annotation=Any) merged_params[param.name] = param return Signature(parameters=list(merged_params.values()), return_annotation=Any) def generate_polyfields( cls: Type["PolyModel"], method: str, parameter: Parameter ) -> Dict[str, Dict[str, PolyField]]: """ For all the fields found in the signature, it will generate PolyField type variable. When generating PolyFields, it matches if there is already a PolyField generated by the Field() type. """ if not isinstance(parameter.default, PolyField): data = { "annotation": parameter.annotation, "name": parameter.name, "default": PolyforceUndefined if parameter.default == Signature.empty else parameter.default, } field = PolyField(**data) else: field = parameter.default field.annotation = parameter.annotation field.name = parameter.name field._validate_default_with_annotation() field_data = {parameter.name: field} if method not in cls.poly_fields: cls.poly_fields[method] = {} cls.poly_fields[method].update(field_data) return cls.poly_fields def generate_model_signature( cls: Type["PolyModel"], value: str, config: ConfigWrapper ) -> Signature: """ Generates a signature for each method of the given class. Args: cls (Type[PolyModel]): The PolyModel class. value (str): The method name. config (ConfigWrapper): Configuration wrapper. Returns: Signature: The generated signature. This function generates a signature for each method of the given class. """ func_type = inspect.getattr_static(cls, value) func = func_type.__func__ if isinstance(func_type, (classmethod, staticmethod)) else func_type signature = Signature.from_callable(func) if config.ignore: return ignore_signature(signature) params = signature.parameters.values() merged_params: Dict[str, Parameter] = {} if signature.return_annotation == inspect.Signature.empty:
raise ReturnSignatureMissing(func=value)
1
2023-10-09 15:18:46+00:00
8k
nipirennipi/BJTU-M502075B-2023
train.py
[ { "identifier": "get_args", "path": "arguments.py", "snippet": "def get_args():\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\n '--seed',\n type=int, \n default=23, \n help='Random seed.',\n )\n\n parser.add_argument(\n '--data_path',\n ...
import os import pprint import torch from datetime import datetime from torch.optim import Adam from torch.utils.data import DataLoader from tqdm import tqdm from arguments import get_args from dataset import MindDataset from model import NewsRecBaseModel from utils import init_seed, read_news, load_word_vectors, green_print from metrics import *
3,794
@torch.no_grad() def eval(args, model, val_loader): model.eval() val_loader = tqdm(val_loader, ncols=args.ncols) logloss = 0. impid_list, label_list, score_list = [], [], [] for step, ( batch_impid, batch_history, batch_imp, batch_label, ) in enumerate(val_loader): batch_impid = batch_impid.to(args.device) batch_history = [ history.to(args.device) for history in batch_history ] batch_imp = batch_imp.to(args.device) batch_label = batch_label.to(args.device) batch_loss, batch_score = model( batch_history, batch_imp, batch_label ) logloss += batch_loss.item() impid_list.extend(batch_impid.tolist()) label_list.extend(batch_label.tolist()) score_list.extend(batch_score.tolist()) logloss = logloss / step impres = {} for impid, label, score in zip(impid_list, label_list, score_list): if impid not in impres: impres[impid] = {} impres[impid]['label'] = [] impres[impid]['score'] = [] impres[impid]['label'].append(label) impres[impid]['score'].append(score) auc_list, mrr_list, ndcg5_list, ndcg10_list = [], [], [], [] for impid in impres.keys(): label = impres[impid]['label'] score = impres[impid]['score'] imp_auc = roc_auc_score(label, score) imp_mrr = mrr_score(label, score) imp_ndcg5 = ndcg_score(label, score, k=5) imp_ndcg10 = ndcg_score(label, score, k=10) auc_list.append(imp_auc) mrr_list.append(imp_mrr) ndcg5_list.append(imp_ndcg5) ndcg10_list.append(imp_ndcg10) auc = np.mean(auc_list) mrr = np.mean(mrr_list) ndcg5 = np.mean(ndcg5_list) ndcg10 = np.mean(ndcg10_list) return logloss, auc, mrr, ndcg5, ndcg10 def main(): args = get_args() green_print('### arguments:') pprint.pprint(args.__dict__, width=1) init_seed(args.seed) green_print('### 1. Build vocabulary and load pre-trained vectors') news_dict, vocab = read_news( file_path=os.path.join(args.data_path, 'news.txt'), filter_num=args.filter_num, ) word_vectors = load_word_vectors( vectors_path=os.path.join( args.vectors_path, 'glove.840B.300d.txt' ), vocab=vocab, ) print(f"vocab size: {len(vocab)}") print(f"unknow words: {len(vocab) - len(word_vectors)}") green_print('### 2. Load data and split') mind_dataset = MindDataset( file_path=os.path.join(args.data_path, 'train_behaviors.txt'), news_dict=news_dict, vocab=vocab, title_size=args.title_size, max_his_size=args.max_his_size, mode='train', ) imps_len = mind_dataset.imps_len() val_imps_len = int(imps_len * args.val_ratio) train_imps_len = imps_len - val_imps_len print( f'# total impressions: {imps_len:>6}\n' \ f'# train impressions: {train_imps_len:>6} | {1 - args.val_ratio:6.2%}\n' \ f'# valid impressions: {val_imps_len:>6} | {args.val_ratio:6.2%}' \ ) train_dataset, val_dataset = mind_dataset.train_val_split(val_imps_len) train_kwargs = { 'batch_size': args.train_batch_size, 'shuffle': True, 'collate_fn': mind_dataset.collate_fn } val_kwargs = { 'batch_size': args.infer_batch_size, 'shuffle': False, 'collate_fn': mind_dataset.collate_fn } train_loader = DataLoader(train_dataset, **train_kwargs) val_loader = DataLoader(val_dataset, **val_kwargs) green_print('### 3. Load model and optimizer')
os.environ["CUDA_VISIBLE_DEVICES"] = '2' def train(args, model, optimizer, train_loader): model.train() train_loader = tqdm(train_loader, ncols=args.ncols) logloss = 0. for step, ( batch_impid, batch_history, batch_imp, batch_label, ) in enumerate(train_loader): batch_impid = batch_impid.to(args.device) batch_history = [ history.to(args.device) for history in batch_history ] batch_imp = batch_imp.to(args.device) batch_label = batch_label.to(args.device) batch_loss, batch_score = model( batch_history, batch_imp, batch_label ) batch_loss.backward() optimizer.step() optimizer.zero_grad() logloss += batch_loss.item() logloss = logloss / step return logloss @torch.no_grad() def eval(args, model, val_loader): model.eval() val_loader = tqdm(val_loader, ncols=args.ncols) logloss = 0. impid_list, label_list, score_list = [], [], [] for step, ( batch_impid, batch_history, batch_imp, batch_label, ) in enumerate(val_loader): batch_impid = batch_impid.to(args.device) batch_history = [ history.to(args.device) for history in batch_history ] batch_imp = batch_imp.to(args.device) batch_label = batch_label.to(args.device) batch_loss, batch_score = model( batch_history, batch_imp, batch_label ) logloss += batch_loss.item() impid_list.extend(batch_impid.tolist()) label_list.extend(batch_label.tolist()) score_list.extend(batch_score.tolist()) logloss = logloss / step impres = {} for impid, label, score in zip(impid_list, label_list, score_list): if impid not in impres: impres[impid] = {} impres[impid]['label'] = [] impres[impid]['score'] = [] impres[impid]['label'].append(label) impres[impid]['score'].append(score) auc_list, mrr_list, ndcg5_list, ndcg10_list = [], [], [], [] for impid in impres.keys(): label = impres[impid]['label'] score = impres[impid]['score'] imp_auc = roc_auc_score(label, score) imp_mrr = mrr_score(label, score) imp_ndcg5 = ndcg_score(label, score, k=5) imp_ndcg10 = ndcg_score(label, score, k=10) auc_list.append(imp_auc) mrr_list.append(imp_mrr) ndcg5_list.append(imp_ndcg5) ndcg10_list.append(imp_ndcg10) auc = np.mean(auc_list) mrr = np.mean(mrr_list) ndcg5 = np.mean(ndcg5_list) ndcg10 = np.mean(ndcg10_list) return logloss, auc, mrr, ndcg5, ndcg10 def main(): args = get_args() green_print('### arguments:') pprint.pprint(args.__dict__, width=1) init_seed(args.seed) green_print('### 1. Build vocabulary and load pre-trained vectors') news_dict, vocab = read_news( file_path=os.path.join(args.data_path, 'news.txt'), filter_num=args.filter_num, ) word_vectors = load_word_vectors( vectors_path=os.path.join( args.vectors_path, 'glove.840B.300d.txt' ), vocab=vocab, ) print(f"vocab size: {len(vocab)}") print(f"unknow words: {len(vocab) - len(word_vectors)}") green_print('### 2. Load data and split') mind_dataset = MindDataset( file_path=os.path.join(args.data_path, 'train_behaviors.txt'), news_dict=news_dict, vocab=vocab, title_size=args.title_size, max_his_size=args.max_his_size, mode='train', ) imps_len = mind_dataset.imps_len() val_imps_len = int(imps_len * args.val_ratio) train_imps_len = imps_len - val_imps_len print( f'# total impressions: {imps_len:>6}\n' \ f'# train impressions: {train_imps_len:>6} | {1 - args.val_ratio:6.2%}\n' \ f'# valid impressions: {val_imps_len:>6} | {args.val_ratio:6.2%}' \ ) train_dataset, val_dataset = mind_dataset.train_val_split(val_imps_len) train_kwargs = { 'batch_size': args.train_batch_size, 'shuffle': True, 'collate_fn': mind_dataset.collate_fn } val_kwargs = { 'batch_size': args.infer_batch_size, 'shuffle': False, 'collate_fn': mind_dataset.collate_fn } train_loader = DataLoader(train_dataset, **train_kwargs) val_loader = DataLoader(val_dataset, **val_kwargs) green_print('### 3. Load model and optimizer')
model = NewsRecBaseModel(
2
2023-10-10 08:06:04+00:00
8k
parklab/Salamander
src/salamander/nmf_framework/mvnmf.py
[ { "identifier": "normalize_WH", "path": "src/salamander/utils.py", "snippet": "@njit\ndef normalize_WH(W, H):\n normalization_factor = np.sum(W, axis=0)\n return W / normalization_factor, H * normalization_factor[:, None]" }, { "identifier": "kl_divergence", "path": "src/salamander/nmf...
import numpy as np import pandas as pd from numba import njit from ..utils import normalize_WH from ._utils_klnmf import kl_divergence, poisson_llh, samplewise_kl_divergence, update_H from .nmf import NMF
4,754
denominator = 4 * lam * WY_abs W_unconstrained = W * numerator / denominator W_unconstrained[:, :n_given_signatures] = W[:, :n_given_signatures].copy() W_unconstrained[:, n_given_signatures:] = W_unconstrained[ :, n_given_signatures: ].clip(EPSILON) return W_unconstrained @njit def line_search( X: np.ndarray, W: np.ndarray, H: np.ndarray, lam: float, delta: float, gamma: float, W_unconstrained: np.ndarray, ) -> tuple[np.ndarray, np.ndarray, float]: prev_of_value = kl_divergence_penalized(X, W, H, lam, delta) W_new, H_new = normalize_WH(W_unconstrained, H) W_new, H_new = W_new.clip(EPSILON), H_new.clip(EPSILON) of_value = kl_divergence_penalized(X, W_new, H_new, lam, delta) while of_value > prev_of_value and gamma > 1e-16: gamma *= 0.8 W_new = (1 - gamma) * W + gamma * W_unconstrained W_new, H_new = normalize_WH(W_new, H) W_new, H_new = W_new.clip(EPSILON), H_new.clip(EPSILON) of_value = kl_divergence_penalized(X, W_new, H_new, lam, delta) gamma = min(1.0, 1.2 * gamma) return W_new, H_new, gamma class MvNMF(NMF): """ Min-volume non-negative matrix factorization. This algorithms is a volume- regularized version of NMF with the generalized Kullback-Leibler (KL) divergence. Parameters ---------- n_signatures: int Number of signatures to decipher. init_method : str, default=nndsvd One of "custom", "flat", "hierarchical_cluster", "nndsvd", "nndsvda", "nndsvdar" "random" and "separableNMF". Please see the initialization module for further details on each method. lam : float, default=1.0 Objective function volume penalty weight. delta : float, default=1.0 Objective function hyperparameter. min_iterations : int, default=500 Minimum number of iterations. max_iterations : int, default=10000 Maximum number of iterations. conv_test_freq: int The frequency at which the algorithm is tested for convergence. The objective function value is only computed every 'conv_test_freq' many iterations, which also affects a potentially saved history of the objective function values. tol : float, default=1e-7 Tolerance of the stopping condition. Reference --------- Leplat, V., Gillis, N. and Ang, A.M., 2020. Blind audio source separation with minimum-volume beta-divergence NMF. IEEE Transactions on Signal Processing, 68, pp.3400-3410. """ def __init__( self, n_signatures=1, init_method="nndsvd", lam=1.0, delta=1.0, min_iterations=500, max_iterations=10000, conv_test_freq=10, tol=1e-7, ): super().__init__( n_signatures, init_method, min_iterations, max_iterations, conv_test_freq, tol, ) self.lam = lam self.delta = delta self._gamma = None @property def reconstruction_error(self): return kl_divergence(self.X, self.W, self.H) @property def samplewise_reconstruction_error(self): return samplewise_kl_divergence(self.X, self.W, self.H) def objective_function(self): return kl_divergence_penalized(self.X, self.W, self.H, self.lam, self.delta) @property def objective(self) -> str: return "minimize" def loglikelihood(self) -> float:
EPSILON = np.finfo(np.float32).eps @njit def volume_logdet(W: np.ndarray, delta: float) -> float: n_signatures = W.shape[1] diag = np.diag(np.full(n_signatures, delta)) volume = np.log(np.linalg.det(W.T @ W + diag)) return volume @njit def kl_divergence_penalized( X: np.ndarray, W: np.ndarray, H: np.ndarray, lam: float, delta: float ) -> float: reconstruction_error = kl_divergence(X, W, H) volume = volume_logdet(W, delta) loss = reconstruction_error + lam * volume return loss @njit def update_W_unconstrained( X: np.ndarray, W: np.ndarray, H: np.ndarray, lam: float, delta: float, n_given_signatures: int = 0, ) -> np.ndarray: n_signatures = W.shape[1] diag = np.diag(np.full(n_signatures, delta)) Y = np.linalg.inv(W.T @ W + diag) Y_minus = np.maximum(0, -Y) Y_abs = np.abs(Y) WY_minus = W @ Y_minus WY_abs = W @ Y_abs rowsums_H = np.sum(H, axis=1) discriminant_s1 = (rowsums_H - 4 * lam * WY_minus) ** 2 discriminant_s2 = 8 * lam * WY_abs * ((X / (W @ H)) @ H.T) numerator_s1 = np.sqrt(discriminant_s1 + discriminant_s2) numerator_s2 = -rowsums_H + 4 * lam * WY_minus numerator = numerator_s1 + numerator_s2 denominator = 4 * lam * WY_abs W_unconstrained = W * numerator / denominator W_unconstrained[:, :n_given_signatures] = W[:, :n_given_signatures].copy() W_unconstrained[:, n_given_signatures:] = W_unconstrained[ :, n_given_signatures: ].clip(EPSILON) return W_unconstrained @njit def line_search( X: np.ndarray, W: np.ndarray, H: np.ndarray, lam: float, delta: float, gamma: float, W_unconstrained: np.ndarray, ) -> tuple[np.ndarray, np.ndarray, float]: prev_of_value = kl_divergence_penalized(X, W, H, lam, delta) W_new, H_new = normalize_WH(W_unconstrained, H) W_new, H_new = W_new.clip(EPSILON), H_new.clip(EPSILON) of_value = kl_divergence_penalized(X, W_new, H_new, lam, delta) while of_value > prev_of_value and gamma > 1e-16: gamma *= 0.8 W_new = (1 - gamma) * W + gamma * W_unconstrained W_new, H_new = normalize_WH(W_new, H) W_new, H_new = W_new.clip(EPSILON), H_new.clip(EPSILON) of_value = kl_divergence_penalized(X, W_new, H_new, lam, delta) gamma = min(1.0, 1.2 * gamma) return W_new, H_new, gamma class MvNMF(NMF): """ Min-volume non-negative matrix factorization. This algorithms is a volume- regularized version of NMF with the generalized Kullback-Leibler (KL) divergence. Parameters ---------- n_signatures: int Number of signatures to decipher. init_method : str, default=nndsvd One of "custom", "flat", "hierarchical_cluster", "nndsvd", "nndsvda", "nndsvdar" "random" and "separableNMF". Please see the initialization module for further details on each method. lam : float, default=1.0 Objective function volume penalty weight. delta : float, default=1.0 Objective function hyperparameter. min_iterations : int, default=500 Minimum number of iterations. max_iterations : int, default=10000 Maximum number of iterations. conv_test_freq: int The frequency at which the algorithm is tested for convergence. The objective function value is only computed every 'conv_test_freq' many iterations, which also affects a potentially saved history of the objective function values. tol : float, default=1e-7 Tolerance of the stopping condition. Reference --------- Leplat, V., Gillis, N. and Ang, A.M., 2020. Blind audio source separation with minimum-volume beta-divergence NMF. IEEE Transactions on Signal Processing, 68, pp.3400-3410. """ def __init__( self, n_signatures=1, init_method="nndsvd", lam=1.0, delta=1.0, min_iterations=500, max_iterations=10000, conv_test_freq=10, tol=1e-7, ): super().__init__( n_signatures, init_method, min_iterations, max_iterations, conv_test_freq, tol, ) self.lam = lam self.delta = delta self._gamma = None @property def reconstruction_error(self): return kl_divergence(self.X, self.W, self.H) @property def samplewise_reconstruction_error(self): return samplewise_kl_divergence(self.X, self.W, self.H) def objective_function(self): return kl_divergence_penalized(self.X, self.W, self.H, self.lam, self.delta) @property def objective(self) -> str: return "minimize" def loglikelihood(self) -> float:
return poisson_llh(self.X, self.W, self.H)
2
2023-10-08 04:29:42+00:00
8k
hfzhang31/A3FL
main/clean.py
[ { "identifier": "Helper", "path": "fl_utils/helper.py", "snippet": "class Helper:\n def __init__(self, config):\n self.config = config\n \n self.config.data_folder = './datasets'\n self.local_model = None\n self.global_model = None\n self.client_models = []\n...
import sys import wandb import argparse import yaml import traceback import torch import torchvision import numpy as np import random import os from fl_utils.helper import Helper from fl_utils.fler import FLer
5,079
sys.path.append("../") def setup_wandb(config_path, sweep): with open(config_path, 'r') as stream: sweep_configuration = yaml.safe_load(stream) if sweep: sweep_id = wandb.sweep(sweep=sweep_configuration, project='FanL-clean') return sweep_id else: config = sweep_configuration['parameters'] d = dict() for k in config.keys(): v = config[k][list(config[k].keys())[0]] if type(v) is list: d[k] = {'value':v[0]} else: d[k] = {'value':v} yaml.dump(d, open('./yamls/tmp.yaml','w')) wandb.init(config='./yamls/tmp.yaml') return None def set_seed(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True def main(): run = wandb.init() set_seed(wandb.config.seed)
sys.path.append("../") def setup_wandb(config_path, sweep): with open(config_path, 'r') as stream: sweep_configuration = yaml.safe_load(stream) if sweep: sweep_id = wandb.sweep(sweep=sweep_configuration, project='FanL-clean') return sweep_id else: config = sweep_configuration['parameters'] d = dict() for k in config.keys(): v = config[k][list(config[k].keys())[0]] if type(v) is list: d[k] = {'value':v[0]} else: d[k] = {'value':v} yaml.dump(d, open('./yamls/tmp.yaml','w')) wandb.init(config='./yamls/tmp.yaml') return None def set_seed(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True def main(): run = wandb.init() set_seed(wandb.config.seed)
helper = Helper(wandb.config)
0
2023-10-10 17:55:01+00:00
8k
logchange/valhalla
valhalla/main.py
[ { "identifier": "get_valhalla_token", "path": "valhalla/ci_provider/get_token.py", "snippet": "def get_valhalla_token() -> str:\n token = os.getenv('VALHALLA_TOKEN')\n\n if token:\n info(f'Variable VALHALLA_TOKEN is set to: {\"*\" * len(token)}')\n\n return token\n else:\n ...
from valhalla.ci_provider.get_token import get_valhalla_token from valhalla.ci_provider.gitlab.merge_request import GitLabValhallaMergeRequest from valhalla.ci_provider.gitlab.release import GitLabValhallaRelease from valhalla.commit import before from valhalla.ci_provider.gitlab.get_version import get_version_number_to_release from valhalla.commit.commit import GitRepository from valhalla.common.get_config import get_config, Config, CommitConfig, MergeRequestConfig from valhalla.common.logger import info, init_logger from valhalla.common.resolver import init_str_resolver, init_str_resolver_custom_variables from valhalla.release.assets import Assets from valhalla.release.description import Description
3,678
def start(): print(f'Release the Valhalla!') version_to_release = get_version_number_to_release() token = get_valhalla_token() init_logger(token) init_str_resolver(version_to_release, token) config = get_config("./valhalla.yml") init_str_resolver_custom_variables(config.variables) commit(config.commit_before_release, token) create_release(config, version_to_release) commit(config.commit_after_release, token) create_merge_request(config.merge_request) def create_merge_request(merge_request_config: MergeRequestConfig): if merge_request_config is None: info("merge_request not specified in valhalla.yml, skipping") return if merge_request_config.enabled: info("Preparing to create merge request") merge_request = GitLabValhallaMergeRequest() merge_request.create(merge_request_config) else: info("merge_request.enabled is False in valhalla.yml, skipping") def create_release(config, version_to_release): info("Preparing to create release") release = GitLabValhallaRelease() description = Description(config.release_config.description_config)
def start(): print(f'Release the Valhalla!') version_to_release = get_version_number_to_release() token = get_valhalla_token() init_logger(token) init_str_resolver(version_to_release, token) config = get_config("./valhalla.yml") init_str_resolver_custom_variables(config.variables) commit(config.commit_before_release, token) create_release(config, version_to_release) commit(config.commit_after_release, token) create_merge_request(config.merge_request) def create_merge_request(merge_request_config: MergeRequestConfig): if merge_request_config is None: info("merge_request not specified in valhalla.yml, skipping") return if merge_request_config.enabled: info("Preparing to create merge request") merge_request = GitLabValhallaMergeRequest() merge_request.create(merge_request_config) else: info("merge_request.enabled is False in valhalla.yml, skipping") def create_release(config, version_to_release): info("Preparing to create release") release = GitLabValhallaRelease() description = Description(config.release_config.description_config)
assets = Assets(config.release_config.assets_config)
14
2023-10-07 11:48:43+00:00
8k
shadlc/FreeKill-Web-Panel
app.py
[ { "identifier": "tailLog", "path": "src/utils.py", "snippet": "def getImgBase64FromURL(url: str) -> str:\ndef getFKVersion() -> str | None:\ndef getGitTree(url: str) -> list:\ndef getVersionFromPath(path: str) -> str:\ndef runCmd(cmd: str, log=True) -> str:\ndef runCmdCorrect(cmd: str, log=True) -> bool...
from platform import system from flask import Flask, render_template, request from flask_socketio import SocketIO from src.utils import tailLog, queryPerf, config from src.v1 import V1API from src.controller import Controller from src.connection import Connection
5,809
app = Flask(__name__, static_folder='static', static_url_path='/') app.json.ensure_ascii = False socketio = SocketIO(app, async_mode='gevent', cors_allowed_origins="*") conn = Connection(socketio)
app = Flask(__name__, static_folder='static', static_url_path='/') app.json.ensure_ascii = False socketio = SocketIO(app, async_mode='gevent', cors_allowed_origins="*") conn = Connection(socketio)
controller = Controller()
2
2023-10-14 12:34:08+00:00
8k
a-pig-akab/PICO-RL_project
train_main.py
[ { "identifier": "batch_norm_layer", "path": "batch_norm_layer.py", "snippet": "def batch_norm_layer(x,is_training,name=None):\n\t'''\n\n\t:param x:\n\t:param is_training:\n\t:param name:\n\t:return:\n\t'''\n\tbn = tf.layers.batch_normalization(\n \tinputs=x,\n \taxis=-1,\n \tmomentu...
import imageio import tensorflow as tf import numpy as np import random import argparse import os import scipy.io as sio import warnings from batch_norm_layer import batch_norm_layer from tensorboardX import SummaryWriter from tqdm import tqdm from SRNet_tensorflow_v1.SRNet import SRNet
6,198
out_shape = [BATCH_SIZE, s64, s64, NUM] kernel10_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM * 2], stddev=0.02), name="kerne10_G") conv10_G = tf.nn.conv2d_transpose(tf.nn.relu(bn9_G), kernel10_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv10_G") bn10_G = batch_norm_layer(conv10_G, is_training, 'bn10_G') bn10_G = tf.nn.dropout(bn10_G, 0.5) bn10_G = tf.concat([bn10_G, bn6_G], 3) with tf.variable_scope("Gen11") as scope: NUM = G_DIM * 8 out_shape = [BATCH_SIZE, s32, s32, NUM] kernel11_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM * 2], stddev=0.02), name="kerne11_G") conv11_G = tf.nn.conv2d_transpose(tf.nn.relu(bn10_G), kernel11_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv11_G") bn11_G = batch_norm_layer(conv11_G, is_training, 'bn11_G') bn11_G = tf.nn.dropout(bn11_G, 0.5) bn11_G = tf.concat([bn11_G, bn5_G], 3) with tf.variable_scope("Gen12") as scope: NUM = G_DIM * 8 out_shape = [BATCH_SIZE, s16, s16, NUM] kernel12_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM * 2], stddev=0.02), name="kerne12_G") conv12_G = tf.nn.conv2d_transpose(tf.nn.relu(bn11_G), kernel12_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv12_G") bn12_G = batch_norm_layer(conv12_G, is_training, 'bn12_G') bn12_G = tf.concat([bn12_G, bn4_G], 3) with tf.variable_scope("Gen13") as scope: NUM = G_DIM * 4 out_shape = [BATCH_SIZE, s8, s8, NUM] kernel13_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM * 4], stddev=0.02), name="kerne13_G") conv13_G = tf.nn.conv2d_transpose(tf.nn.relu(bn12_G), kernel13_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv13_G") bn13_G = batch_norm_layer(conv13_G, is_training, 'bn13_G') bn13_G = tf.concat([bn13_G, bn3_G], 3) with tf.variable_scope("Gen14") as scope: NUM = G_DIM * 2 out_shape = [BATCH_SIZE, s4, s4, NUM] kernel14_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM * 4], stddev=0.02), name="kerne14_G") conv14_G = tf.nn.conv2d_transpose(tf.nn.relu(bn13_G), kernel14_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv14_G") bn14_G = batch_norm_layer(conv14_G, is_training, 'bn14_G') bn14_G = tf.concat([bn14_G, bn2_G], 3) with tf.variable_scope("Gen15") as scope: NUM = G_DIM out_shape = [BATCH_SIZE, s2, s2, NUM] kernel15_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM * 4], stddev=0.02), name="kerne15_G") conv15_G = tf.nn.conv2d_transpose(tf.nn.relu(bn14_G), kernel15_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv15_G") bn15_G = batch_norm_layer(conv15_G, is_training, 'bn15_G') bn15_G = tf.concat([bn15_G, bn1_G], 3) with tf.variable_scope("Gen16") as scope: NUM = NUM_CHANNEL out_shape = [BATCH_SIZE, s, s, NUM] kernel16_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, G_DIM * 2], stddev=0.02), name="kerne16_G") conv16_G = tf.nn.conv2d_transpose(tf.nn.relu(bn15_G), kernel16_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv16_G") # Embeding_prob = tf.nn.relu(tf.nn.sigmoid(conv16_G) - 0.5) # Embeding_prob = tf.nn.relu(tf.nn.sigmoid(conv16_G) - 1 / 3) # Embeding_prob = tf.nn.relu(tf.nn.sigmoid(conv16_G) / 1.5) # rho = tf.nn.relu(tf.nn.sigmoid(conv16_G) - 0.5) # rho = tf.nn.relu(tf.nn.sigmoid(conv16_G)) rho = tf.nn.sigmoid(conv16_G) # Lambda = 40 # Lambda = 128.9 * tf.pow(PAYLOAD, -0.2069) - 116.3 # Lambda = 98.62 * tf.pow(PAYLOAD, -0.251) - 84.12 # BOSSBase-100 # Lambda = 121.9 * tf.pow(PAYLOAD, -0.2124) - 108 # BOSSBase-10000 # Lambda = 101.4 * tf.pow(PAYLOAD, -0.2609) - 88.61 # SZUBase-all(41314) # Lambda = 100.3 * tf.pow(PAYLOAD, -0.2591) - 87.05 # SZUBase-1000 # Lambda = -114.8968 * tf.pow(PAYLOAD, 0.1192) + 132.0939 # SZUBase-1000-MiPOD-p8 Lambda = 149.5766 * tf.pow(PAYLOAD, -0.2163) - 137.4412 # SZUBase-1000-HILL-p8 # Lambda_converted = tf.reshape( # tf.broadcast_to(Lambda, [rho.shape[0], rho.shape[1], rho.shape[2], rho.shape[3]]), tf.shape(rho)) # prob = (tf.exp(-Lambda_converted*rho))/(1+2*tf.exp(-Lambda_converted*rho)) prob = (tf.exp(-Lambda*rho))/(1+2*tf.exp(-Lambda*rho)) # prob = (tf.exp(-tf.multiply(rho,Lambda)))/(1+2*tf.exp(-tf.multiply(rho,Lambda))) # rhoP1 = rho # rhoM1 = rho proChangeP = prob proChangeM = prob # proChangeP = (tf.exp(-Lambda*rhoP1))/(1+tf.exp(-Lambda*rhoP1)+tf.exp(-Lambda*rhoM1)) # proChangeM = (tf.exp(-Lambda*rhoM1))/(1+tf.exp(-Lambda*rhoP1)+tf.exp(-Lambda*rhoM1)) Embeding_prob_shape = rho.get_shape().as_list() output = rho # *************************************************** double-tanh function for embedding simulation *************************************************** # proChangeP = Embeding_prob / 2.0 # proChangeM = Embeding_prob / 2.0 # Embeding_prob_shape = Embeding_prob.get_shape().as_list() noise = tf.placeholder(tf.float32, Embeding_prob_shape) # noise holder modification_0 = tf.zeros([BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNEL]) modification_p1 = tf.ones([BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNEL]) modification_m1 = -1 * tf.ones([BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNEL]) modification_temp_equal = tf.where(noise < proChangeM, modification_m1, modification_0) modification_equal = tf.where(noise > 1 - proChangeP, modification_p1, modification_temp_equal) modification = modification_equal stego = cover + modification_equal # *************************************************** definition of the discriminator ************************************************************** Img = tf.concat([cover, stego], 0) y_array = np.zeros([BATCH_SIZE * 2, NUM_LABELS], dtype=np.float32) for i in range(0, BATCH_SIZE): y_array[i, 1] = 1 for i in range(BATCH_SIZE, BATCH_SIZE * 2): y_array[i, 0] = 1 y = tf.constant(y_array) Img_label = tf.constant(y_array) # *********************** SRNet model ***********************
# By Shihang Wu and Weixiang Li(Code inherited from Weixuan Tang) # tf.disable_v2_behavior() warnings.filterwarnings('ignore') # Parameter setting parser = argparse.ArgumentParser(description="Set system parameters") parser.add_argument('--gpu_num', type=str, default='2', help='set the gpu number') # 添加一个x参数,默认值为1,类型为int parser.add_argument('--train_img_path', type=str, default="./img/SZUBaseGray_256/", help='set train img path') parser.add_argument('--test_img_path', type=str, default="./img/BOSS_256/", help='set test img path') parser.add_argument('--iteration', type=int, default=200000, help='set the train iteration') parser.add_argument('--use_img_of_train', type=float, default=1.0, help='set the percent of train img to use') parser.add_argument('--test_payload', type=float, default=0.4, help='set the payload of test stego') parser.add_argument('--use_tensorboard', type=str, default="true", help='set use the tensorboard to record the loss') parser.add_argument('--save_path', type=str, default='./', help='set the path for model and test img') parser.add_argument('--save_TesImg_iter', type=int, default=100, help='set iter to save the test img at one time') parser.add_argument('--save_model_iter', type=int, default=100, help='set iter to save the model at one time') parser.add_argument('--seed', type=int, default=1234, help='Sets the seed used to scramble the image') parser.add_argument('--train_img_name', type=str, default="SZUBase", help='set train img name') parser.add_argument('--test_img_name', type=str, default="BossBase", help='set test img name') parser.add_argument('--star_iter', type=int, default=0, help='set star iter of train') parser.add_argument('--load_model', type=str, default=None, help='set the load model(None is not load)') parser.add_argument('--train_test', type=str, default='train', help='set the code is used for training or testing') args = parser.parse_args() # Correlation parameter reading os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_num path1 = args.train_img_path # path of training set path2 = args.test_img_path # Gets a list of names for training and test images if args.train_test == 'train': fileList = [] for (dirpath, dirnames, filenames) in os.walk(path1): fileList = filenames np.set_printoptions(threshold=10000000) random.seed(args.seed) random.shuffle(fileList) fileList2 = [] for (dirpath2, dirnames2, filenames2) in os.walk(path2): fileList2 = filenames2 # # select the graphic card # os.environ['CUDA_VISIBLE_DEVICES'] = '1' # # PAYLOAD = 0.4 # Target embedding payload # # os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # path1 = "/data2/wushihang/wsh/img/SPAR-RL/SZUBaseGray_256/" # path of training set # # path1 = "/data2/wushihang/wsh/img/SPAR-RL/Alask_256_Final/" # # path1 = "/data2/wushihang/liweixiang/SPAR-RL/img/SZUBaseGray_256/" # path of training set # path2 = "/data2/wushihang/liweixiang/SPAR-RL/img/BOSS_256/" # path of testing set # pathR = '/data2/wushihang/liweixiang/SPAR-RL/model/SZUBase/PICORL_HILL_p8/' # if not os.path.exists(pathR): # os.makedirs(pathR) # # fileList = [] # for (dirpath, dirnames, filenames) in os.walk(path1): # fileList = filenames # np.set_printoptions(threshold=10000000) # random.seed(1234) # random.shuffle(fileList) # # fileList2 = [] # for (dirpath2, dirnames2, filenames2) in os.walk(path2): # fileList2 = filenames2 # ******************************************* constant value settings ************************************************ img_1 = imageio.imread(path2 + '/' + fileList2[0]) NUM_ITERATION = args.iteration # NUM_IMG = 10000 # The number of images used to train the network if args.train_test == 'train': NUM_IMG = len(fileList) USE_percent = args.use_img_of_train BATCH_SIZE = 25 IMAGE_SIZE = img_1.shape[0] NUM_CHANNEL = 1 # gray image NUM_LABELS = 2 # binary classification G_DIM = 16 # number of feature maps in generator STRIDE = 2 KENEL_SIZE = 3 DKENEL_SIZE = 5 # PAYLOAD = 0.1 # Target embedding payload PAD_SIZE = int((KENEL_SIZE - 1) / 2) Initial_learning_rate = 0.0001 Adam_beta = 0.5 TANH_LAMBDA = 60 # To balance the embedding simulate and avoid gradient vanish problem cover = tf.placeholder(tf.float32, shape=[BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNEL]) is_training = tf.placeholder(tf.bool, name='is_training') # True for training, false for test PAYLOAD = tf.placeholder(tf.float32) # randomly selected payload # ********************************************* definition of the generator ********************************************************* def lrelu(x, alpha): return tf.nn.relu(x) - alpha * tf.nn.relu(-x) # -------------- contracting path --------------------- with tf.variable_scope("Gen1") as scope: NUM = G_DIM * 1 kernel1_G = tf.Variable(tf.truncated_normal([KENEL_SIZE, KENEL_SIZE, NUM_CHANNEL, NUM], stddev=0.02), name="kernel1_G") conv1_G = tf.nn.conv2d(cover / 255, kernel1_G, [1, STRIDE, STRIDE, 1], padding='SAME', name="conv1_G") bn1_G = batch_norm_layer(conv1_G, is_training, 'bn1_G') # feature map shape: 128*128 with tf.variable_scope("Gen2") as scope: NUM = G_DIM * 2 kernel2_G = tf.Variable(tf.truncated_normal([KENEL_SIZE, KENEL_SIZE, int(NUM / 2), NUM], stddev=0.02), name="kernel2_G") conv2_G = tf.nn.conv2d(lrelu(bn1_G, 0.2), kernel2_G, [1, STRIDE, STRIDE, 1], padding='SAME', name="conv2_G") bn2_G = batch_norm_layer(conv2_G, is_training, 'bn2_G') # feature map shape: 64*64 with tf.variable_scope("Gen3") as scope: NUM = G_DIM * 4 kernel3_G = tf.Variable(tf.truncated_normal([KENEL_SIZE, KENEL_SIZE, int(NUM / 2), NUM], stddev=0.02), name="kernel3_G") conv3_G = tf.nn.conv2d(lrelu(bn2_G, 0.2), kernel3_G, [1, STRIDE, STRIDE, 1], padding='SAME', name="conv3_G") bn3_G = batch_norm_layer(conv3_G, is_training, 'bn3_G') # feature map shape: 32*32 with tf.variable_scope("Gen4") as scope: NUM = G_DIM * 8 kernel4_G = tf.Variable(tf.truncated_normal([KENEL_SIZE, KENEL_SIZE, int(NUM / 2), NUM], stddev=0.02), name="kernel4_G") conv4_G = tf.nn.conv2d(lrelu(bn3_G, 0.2), kernel4_G, [1, STRIDE, STRIDE, 1], padding='SAME', name="conv4_G") bn4_G = batch_norm_layer(conv4_G, is_training, 'bn4_G') # feature map shape: 16*16 with tf.variable_scope("Gen5") as scope: NUM = G_DIM * 8 kernel5_G = tf.Variable(tf.truncated_normal([KENEL_SIZE, KENEL_SIZE, NUM, NUM], stddev=0.02), name="kernel5_G") conv5_G = tf.nn.conv2d(lrelu(bn4_G, 0.2), kernel5_G, [1, STRIDE, STRIDE, 1], padding='SAME', name="conv5_G") bn5_G = batch_norm_layer(conv5_G, is_training, 'bn5_G') # feature map shape: 8*8 with tf.variable_scope("Gen6") as scope: NUM = G_DIM * 8 kernel6_G = tf.Variable(tf.truncated_normal([KENEL_SIZE, KENEL_SIZE, NUM, NUM], stddev=0.02), name="kernel6_G") conv6_G = tf.nn.conv2d(lrelu(bn5_G, 0.2), kernel6_G, [1, STRIDE, STRIDE, 1], padding='SAME', name="conv6_G") bn6_G = batch_norm_layer(conv6_G, is_training, 'bn6_G') # feature map shape: 4*4 with tf.variable_scope("Gen7") as scope: NUM = G_DIM * 8 kernel7_G = tf.Variable(tf.truncated_normal([KENEL_SIZE, KENEL_SIZE, NUM, NUM], stddev=0.02), name="kernel7_G") conv7_G = tf.nn.conv2d(lrelu(bn6_G, 0.2), kernel7_G, [1, STRIDE, STRIDE, 1], padding='SAME', name="conv7_G") bn7_G = batch_norm_layer(conv7_G, is_training, 'bn7_G') # 2*2 with tf.variable_scope("Gen8") as scope: NUM = G_DIM * 8 kernel8_G = tf.Variable(tf.truncated_normal([KENEL_SIZE, KENEL_SIZE, NUM, NUM], stddev=0.02), name="kernel8_G") conv8_G = tf.nn.conv2d(lrelu(bn7_G, 0.2), kernel8_G, [1, STRIDE, STRIDE, 1], padding='SAME', name="conv8_G") bn8_G = batch_norm_layer(conv8_G, is_training, 'bn8_G') # 1*1 s = IMAGE_SIZE s2, s4, s8, s16, s32, s64, s128 = int(s / 2), int(s / 4), int(s / 8), int(s / 16), int(s / 32), int(s / 64), int( s / 128) # -------------- expanding path ----------------- with tf.variable_scope("Gen9") as scope: NUM = G_DIM * 8 out_shape = [BATCH_SIZE, s128, s128, NUM] kernel9_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM], stddev=0.02), name="kernel9_G") conv9_G = tf.nn.conv2d_transpose(tf.nn.relu(bn8_G), kernel9_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv9_G") bn9_G = batch_norm_layer(conv9_G, is_training, 'bn9_G') bn9_G = tf.nn.dropout(bn9_G, 0.5) bn9_G = tf.concat([bn9_G, bn7_G], 3) with tf.variable_scope("Gen10") as scope: NUM = G_DIM * 8 out_shape = [BATCH_SIZE, s64, s64, NUM] kernel10_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM * 2], stddev=0.02), name="kerne10_G") conv10_G = tf.nn.conv2d_transpose(tf.nn.relu(bn9_G), kernel10_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv10_G") bn10_G = batch_norm_layer(conv10_G, is_training, 'bn10_G') bn10_G = tf.nn.dropout(bn10_G, 0.5) bn10_G = tf.concat([bn10_G, bn6_G], 3) with tf.variable_scope("Gen11") as scope: NUM = G_DIM * 8 out_shape = [BATCH_SIZE, s32, s32, NUM] kernel11_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM * 2], stddev=0.02), name="kerne11_G") conv11_G = tf.nn.conv2d_transpose(tf.nn.relu(bn10_G), kernel11_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv11_G") bn11_G = batch_norm_layer(conv11_G, is_training, 'bn11_G') bn11_G = tf.nn.dropout(bn11_G, 0.5) bn11_G = tf.concat([bn11_G, bn5_G], 3) with tf.variable_scope("Gen12") as scope: NUM = G_DIM * 8 out_shape = [BATCH_SIZE, s16, s16, NUM] kernel12_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM * 2], stddev=0.02), name="kerne12_G") conv12_G = tf.nn.conv2d_transpose(tf.nn.relu(bn11_G), kernel12_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv12_G") bn12_G = batch_norm_layer(conv12_G, is_training, 'bn12_G') bn12_G = tf.concat([bn12_G, bn4_G], 3) with tf.variable_scope("Gen13") as scope: NUM = G_DIM * 4 out_shape = [BATCH_SIZE, s8, s8, NUM] kernel13_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM * 4], stddev=0.02), name="kerne13_G") conv13_G = tf.nn.conv2d_transpose(tf.nn.relu(bn12_G), kernel13_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv13_G") bn13_G = batch_norm_layer(conv13_G, is_training, 'bn13_G') bn13_G = tf.concat([bn13_G, bn3_G], 3) with tf.variable_scope("Gen14") as scope: NUM = G_DIM * 2 out_shape = [BATCH_SIZE, s4, s4, NUM] kernel14_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM * 4], stddev=0.02), name="kerne14_G") conv14_G = tf.nn.conv2d_transpose(tf.nn.relu(bn13_G), kernel14_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv14_G") bn14_G = batch_norm_layer(conv14_G, is_training, 'bn14_G') bn14_G = tf.concat([bn14_G, bn2_G], 3) with tf.variable_scope("Gen15") as scope: NUM = G_DIM out_shape = [BATCH_SIZE, s2, s2, NUM] kernel15_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, NUM * 4], stddev=0.02), name="kerne15_G") conv15_G = tf.nn.conv2d_transpose(tf.nn.relu(bn14_G), kernel15_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv15_G") bn15_G = batch_norm_layer(conv15_G, is_training, 'bn15_G') bn15_G = tf.concat([bn15_G, bn1_G], 3) with tf.variable_scope("Gen16") as scope: NUM = NUM_CHANNEL out_shape = [BATCH_SIZE, s, s, NUM] kernel16_G = tf.Variable(tf.random_normal([DKENEL_SIZE, DKENEL_SIZE, NUM, G_DIM * 2], stddev=0.02), name="kerne16_G") conv16_G = tf.nn.conv2d_transpose(tf.nn.relu(bn15_G), kernel16_G, out_shape, [1, STRIDE, STRIDE, 1], name="conv16_G") # Embeding_prob = tf.nn.relu(tf.nn.sigmoid(conv16_G) - 0.5) # Embeding_prob = tf.nn.relu(tf.nn.sigmoid(conv16_G) - 1 / 3) # Embeding_prob = tf.nn.relu(tf.nn.sigmoid(conv16_G) / 1.5) # rho = tf.nn.relu(tf.nn.sigmoid(conv16_G) - 0.5) # rho = tf.nn.relu(tf.nn.sigmoid(conv16_G)) rho = tf.nn.sigmoid(conv16_G) # Lambda = 40 # Lambda = 128.9 * tf.pow(PAYLOAD, -0.2069) - 116.3 # Lambda = 98.62 * tf.pow(PAYLOAD, -0.251) - 84.12 # BOSSBase-100 # Lambda = 121.9 * tf.pow(PAYLOAD, -0.2124) - 108 # BOSSBase-10000 # Lambda = 101.4 * tf.pow(PAYLOAD, -0.2609) - 88.61 # SZUBase-all(41314) # Lambda = 100.3 * tf.pow(PAYLOAD, -0.2591) - 87.05 # SZUBase-1000 # Lambda = -114.8968 * tf.pow(PAYLOAD, 0.1192) + 132.0939 # SZUBase-1000-MiPOD-p8 Lambda = 149.5766 * tf.pow(PAYLOAD, -0.2163) - 137.4412 # SZUBase-1000-HILL-p8 # Lambda_converted = tf.reshape( # tf.broadcast_to(Lambda, [rho.shape[0], rho.shape[1], rho.shape[2], rho.shape[3]]), tf.shape(rho)) # prob = (tf.exp(-Lambda_converted*rho))/(1+2*tf.exp(-Lambda_converted*rho)) prob = (tf.exp(-Lambda*rho))/(1+2*tf.exp(-Lambda*rho)) # prob = (tf.exp(-tf.multiply(rho,Lambda)))/(1+2*tf.exp(-tf.multiply(rho,Lambda))) # rhoP1 = rho # rhoM1 = rho proChangeP = prob proChangeM = prob # proChangeP = (tf.exp(-Lambda*rhoP1))/(1+tf.exp(-Lambda*rhoP1)+tf.exp(-Lambda*rhoM1)) # proChangeM = (tf.exp(-Lambda*rhoM1))/(1+tf.exp(-Lambda*rhoP1)+tf.exp(-Lambda*rhoM1)) Embeding_prob_shape = rho.get_shape().as_list() output = rho # *************************************************** double-tanh function for embedding simulation *************************************************** # proChangeP = Embeding_prob / 2.0 # proChangeM = Embeding_prob / 2.0 # Embeding_prob_shape = Embeding_prob.get_shape().as_list() noise = tf.placeholder(tf.float32, Embeding_prob_shape) # noise holder modification_0 = tf.zeros([BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNEL]) modification_p1 = tf.ones([BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNEL]) modification_m1 = -1 * tf.ones([BATCH_SIZE, IMAGE_SIZE, IMAGE_SIZE, NUM_CHANNEL]) modification_temp_equal = tf.where(noise < proChangeM, modification_m1, modification_0) modification_equal = tf.where(noise > 1 - proChangeP, modification_p1, modification_temp_equal) modification = modification_equal stego = cover + modification_equal # *************************************************** definition of the discriminator ************************************************************** Img = tf.concat([cover, stego], 0) y_array = np.zeros([BATCH_SIZE * 2, NUM_LABELS], dtype=np.float32) for i in range(0, BATCH_SIZE): y_array[i, 1] = 1 for i in range(BATCH_SIZE, BATCH_SIZE * 2): y_array[i, 0] = 1 y = tf.constant(y_array) Img_label = tf.constant(y_array) # *********************** SRNet model ***********************
srnet = SRNet(is_training=True)
1
2023-10-11 05:35:01+00:00
8k
felix-thu/DiffCPS
run.py
[ { "identifier": "utils", "path": "utils/utils.py", "snippet": "def print_banner(s, separator=\"-\", num_star=60):\n def __init__(\n self,\n total,\n name=\"Progress\",\n ncol=3,\n max_length=20,\n indent=0,\n line_width=100,\n speed_update_freq=...
import argparse import gym import numpy as np import os import torch import json import d4rl from utils import utils from utils.data_sampler import Data_Sampler from utils.logger import logger, setup_logger from torch.utils.tensorboard import SummaryWriter from agents.diffcps import DiffCPS as Agent
5,868
"reward_tune": "cql_antmaze", "eval_freq": 50, "num_epochs": 1000, "lambda_min": 0.3, "target_kl": 0.2, "gn": 2.0, "freq": 2, }, "antmaze-umaze-diverse-v0": { "lr": 3e-4, "lambda": 3, "max_q_backup": True, "reward_tune": "cql_antmaze", "eval_freq": 50, "num_epochs": 1000, "lambda_min": 0.3, "target_kl": 0.09, "gn": 3.0, "freq": 2, }, "antmaze-medium-play-v0": { "lr": 1e-3, "lambda": 1, "max_q_backup": True, "reward_tune": "cql_antmaze", "eval_freq": 50, "num_epochs": 1000, "lambda_min": 0.3, "target_kl": 0.3, "gn": 2.0, "freq": 2, }, "antmaze-medium-diverse-v0": { "lr": 3e-4, "lambda": 1, "max_q_backup": True, "reward_tune": "cql_antmaze", "eval_freq": 50, "num_epochs": 1000, "lambda_min": 0.3, "target_kl": 0.2, "gn": 1.0, "freq": 2, }, "antmaze-large-play-v0": { "lr": 3e-4, "lambda": 0.5, "max_q_backup": True, "reward_tune": "cql_antmaze", "eval_freq": 50, "num_epochs": 1000, "lambda_min": 0.3, "target_kl": 0.2, "gn": 10.0, "freq": 4, }, "antmaze-large-diverse-v0": { "lr": 3e-4, "lambda": 0.5, "max_q_backup": True, "reward_tune": "cql_antmaze", "eval_freq": 50, "num_epochs": 1000, "lambda_min": 0.3, "target_kl": 0.2, "gn": 7.0, "freq": 4, }, } def train_agent(env, state_dim, action_dim, max_action, device, output_dir, args): # Load buffer dataset = d4rl.qlearning_dataset(env) data_sampler = Data_Sampler(dataset, device, args.reward_tune) utils.print_banner("Loaded buffer") agent = Agent( state_dim=state_dim, action_dim=action_dim, max_action=max_action, device=device, discount=args.discount, tau=args.tau, max_q_backup=args.max_q_backup, beta_schedule=args.beta_schedule, n_timesteps=args.T, LA=args.LA, lr=args.lr, lr_decay=args.lr_decay, lr_maxt=args.num_epochs, grad_norm=args.gn, policy_freq=args.policy_freq, target_kl=args.target_kl, LA_max=args.lambda_max, LA_min=args.lambda_min, ) early_stop = False stop_check = utils.EarlyStopping(tolerance=1, min_delta=0.0) writer = None # SummaryWriter(output_dir) evaluations = [] training_iters = 0 max_timesteps = args.num_epochs * args.num_steps_per_epoch metric = 100.0 utils.print_banner(f"Training Start", separator="*", num_star=30) while (training_iters < max_timesteps) and (not early_stop): iterations = int(args.eval_freq * args.num_steps_per_epoch) loss_metric = agent.train( data_sampler, iterations=iterations, batch_size=args.batch_size, log_writer=writer, ) training_iters += iterations curr_epoch = int(training_iters // int(args.num_steps_per_epoch)) # Logging utils.print_banner(f"Train step: {training_iters}", separator="*", num_star=30)
hyperparameters = { "halfcheetah-medium-v2": { "lr": 3e-4, "lambda": 1.0, "max_q_backup": False, "reward_tune": "no", "eval_freq": 50, "num_epochs": 2000, "freq": 2, "lambda_min": 0, "target_kl": 0.06, "gn": 9.0, }, "hopper-medium-v2": { "lr": 3e-4, "lambda": 1.0, "max_q_backup": False, "reward_tune": "no", "eval_freq": 50, "num_epochs": 2000, "lambda_min": 0, "target_kl": 0.05, "gn": 9.0, "freq": 2, }, "walker2d-medium-v2": { "lr": 3e-4, "lambda": 1.0, "max_q_backup": False, "reward_tune": "no", "eval_freq": 50, "num_epochs": 2000, "lambda_min": 0, "target_kl": 0.03, "gn": 1.0, "freq": 2, }, "halfcheetah-medium-replay-v2": { "lr": 3e-4, "lambda": 1.0, "max_q_backup": False, "reward_tune": "no", "eval_freq": 50, "num_epochs": 2000, "lambda_min": 0, "target_kl": 0.06, "gn": 2.0, "freq": 2, }, "hopper-medium-replay-v2": { "lr": 3e-4, "lambda": 1.0, "max_q_backup": False, "reward_tune": "no", "eval_freq": 50, "num_epochs": 2000, "lambda_min": 0, "target_kl": 0.03, "gn": 4.0, "freq": 2, }, "walker2d-medium-replay-v2": { "lr": 3e-4, "lambda": 1.0, "max_q_backup": False, "reward_tune": "no", "eval_freq": 50, "num_epochs": 2000, "lambda_min": 0, "target_kl": 0.03, "gn": 4.0, "freq": 2, }, "halfcheetah-medium-expert-v2": { "lr": 3e-4, "lambda": 1.0, "max_q_backup": False, "reward_tune": "no", "eval_freq": 50, "num_epochs": 2000, "lambda_min": 0, "target_kl": 0.04, "gn": 7.0, "freq": 2, }, "hopper-medium-expert-v2": { "lr": 3e-4, "lambda": 1.0, "max_q_backup": False, "reward_tune": "no", "eval_freq": 50, "num_epochs": 2000, "lambda_min": 0, "target_kl": 0.03, "gn": 5.0, "freq": 2, }, "walker2d-medium-expert-v2": { "lr": 3e-4, "lambda": 1.0, "max_q_backup": False, "reward_tune": "no", "eval_freq": 50, "num_epochs": 2000, "lambda_min": 0, "target_kl": 0.04, "gn": 5.0, "freq": 2, }, "antmaze-umaze-v0": { "lr": 3e-4, "lambda": 3, "max_q_backup": False, "reward_tune": "cql_antmaze", "eval_freq": 50, "num_epochs": 1000, "lambda_min": 0.3, "target_kl": 0.2, "gn": 2.0, "freq": 2, }, "antmaze-umaze-diverse-v0": { "lr": 3e-4, "lambda": 3, "max_q_backup": True, "reward_tune": "cql_antmaze", "eval_freq": 50, "num_epochs": 1000, "lambda_min": 0.3, "target_kl": 0.09, "gn": 3.0, "freq": 2, }, "antmaze-medium-play-v0": { "lr": 1e-3, "lambda": 1, "max_q_backup": True, "reward_tune": "cql_antmaze", "eval_freq": 50, "num_epochs": 1000, "lambda_min": 0.3, "target_kl": 0.3, "gn": 2.0, "freq": 2, }, "antmaze-medium-diverse-v0": { "lr": 3e-4, "lambda": 1, "max_q_backup": True, "reward_tune": "cql_antmaze", "eval_freq": 50, "num_epochs": 1000, "lambda_min": 0.3, "target_kl": 0.2, "gn": 1.0, "freq": 2, }, "antmaze-large-play-v0": { "lr": 3e-4, "lambda": 0.5, "max_q_backup": True, "reward_tune": "cql_antmaze", "eval_freq": 50, "num_epochs": 1000, "lambda_min": 0.3, "target_kl": 0.2, "gn": 10.0, "freq": 4, }, "antmaze-large-diverse-v0": { "lr": 3e-4, "lambda": 0.5, "max_q_backup": True, "reward_tune": "cql_antmaze", "eval_freq": 50, "num_epochs": 1000, "lambda_min": 0.3, "target_kl": 0.2, "gn": 7.0, "freq": 4, }, } def train_agent(env, state_dim, action_dim, max_action, device, output_dir, args): # Load buffer dataset = d4rl.qlearning_dataset(env) data_sampler = Data_Sampler(dataset, device, args.reward_tune) utils.print_banner("Loaded buffer") agent = Agent( state_dim=state_dim, action_dim=action_dim, max_action=max_action, device=device, discount=args.discount, tau=args.tau, max_q_backup=args.max_q_backup, beta_schedule=args.beta_schedule, n_timesteps=args.T, LA=args.LA, lr=args.lr, lr_decay=args.lr_decay, lr_maxt=args.num_epochs, grad_norm=args.gn, policy_freq=args.policy_freq, target_kl=args.target_kl, LA_max=args.lambda_max, LA_min=args.lambda_min, ) early_stop = False stop_check = utils.EarlyStopping(tolerance=1, min_delta=0.0) writer = None # SummaryWriter(output_dir) evaluations = [] training_iters = 0 max_timesteps = args.num_epochs * args.num_steps_per_epoch metric = 100.0 utils.print_banner(f"Training Start", separator="*", num_star=30) while (training_iters < max_timesteps) and (not early_stop): iterations = int(args.eval_freq * args.num_steps_per_epoch) loss_metric = agent.train( data_sampler, iterations=iterations, batch_size=args.batch_size, log_writer=writer, ) training_iters += iterations curr_epoch = int(training_iters // int(args.num_steps_per_epoch)) # Logging utils.print_banner(f"Train step: {training_iters}", separator="*", num_star=30)
logger.record_tabular("Trained Epochs", curr_epoch)
2
2023-10-08 13:04:29+00:00
8k
wilhelmagren/finq
tests/test_portfolio.py
[ { "identifier": "Portfolio", "path": "finq/portfolio.py", "snippet": "class Portfolio(object):\n \"\"\" \"\"\"\n\n # For a full list of `scipy` optimization methods and references, see the link below.\n # https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html\n _su...
import unittest import numpy as np from unittest.mock import patch from finq import Portfolio from finq.datasets import CustomDataset from .datasets.mock_df import _random_df
3,979
""" MIT License Copyright (c) 2023 Wilhelm Ågren Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. File created: 2023-11-01 Last updated: 2023-11-01 """ class PortfolioTests(unittest.TestCase): """ """ @patch("yfinance.Ticker.history") def test_constructor_dataset(self, mock_ticker_data): """ """
""" MIT License Copyright (c) 2023 Wilhelm Ågren Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. File created: 2023-11-01 Last updated: 2023-11-01 """ class PortfolioTests(unittest.TestCase): """ """ @patch("yfinance.Ticker.history") def test_constructor_dataset(self, mock_ticker_data): """ """
df = _random_df(["Open", "High", "Low", "Close"], days=400)
2
2023-10-09 19:02:54+00:00
8k
ptrumpis/snap-lens-tool
src/tools/resource_tool.py
[ { "identifier": "ResourceParser", "path": "src/common/parser/resource_parser.py", "snippet": "class ResourceParser:\n def __init__(self, filename, data=None):\n self.filename = filename\n self.reader = data and BinaryReader(data)\n self.version = None\n self.header_size = ...
import argparse from lxml import etree as ET from ..common.parser.resource_parser import ResourceParser from ..common.serializer.resource_serializer import ResourceSerializer from ..common.util.binary_reader import BinaryReader, BinaryReaderError
4,536
reader = BinaryReader(raw) strings = [] is_string_array = True # try to read array as strings, and deem it not a string array if it fails try: for _ in range(size): string_len = reader.read_uint32() string = reader.read_string(string_len) strings.append(string) is_string_array = reader.finished() except (UnicodeDecodeError, BinaryReaderError) as e: is_string_array = False if is_string_array: for string in strings: sub_el = ET.SubElement(el, "string") sub_el.text = string elif true_size % size != 0: raise ValueError(f"Failed to infer array structure at offset {header_size + offset}") else: reader.seek(0) while not reader.finished(): sub_el = ET.SubElement(el, "bytes") sub_el.text = reader.read_bytes(true_size // size).hex() def finished(self): return len(self.stack) == 0 def resource_to_xml(filename, outfile): parser = ResourceParser(filename) xml = parser.parse(XmlResourceBuilder) xml = ET.ElementTree(xml) xml.write(outfile, pretty_print=True) def _xml_to_resource_rec(serializer, node): key = node.attrib["key"] if "key" in node.attrib else None if node.tag == "block": serializer.begin(key) for child in node: _xml_to_resource_rec(serializer, child) serializer.end() elif node.tag == "bool8": if node.text.lower() == "true": value = True elif node.text.lower() == "false": value = False else: raise ValueError("Unexpected value for bool8") serializer.write_bool8(key, value) elif node.tag == "bytes": value = "" if node.text is None else node.text value = bytes.fromhex(value) serializer.write_bytes(key, value) elif node.tag == "float64": serializer.write_float64(key, node.text) elif node.tag == "float32": serializer.write_float32(key, node.text) elif node.tag == "uint32": serializer.write_uint32(key, node.text) elif node.tag == "int32": serializer.write_int32(key, node.text) elif node.tag == "uint64": serializer.write_uint64(key, node.text) elif node.tag == "int64": serializer.write_int64(key, node.text) elif node.tag == "mat2f": values = [child.text for child in node] serializer.write_mat2f(key, values) elif node.tag == "mat3f": values = [child.text for child in node] serializer.write_mat3f(key, values) elif node.tag == "mat4f": values = [child.text for child in node] serializer.write_mat4f(key, values) elif node.tag == "quatf": values = [child.text for child in node] serializer.write_quatf(key, values) elif node.tag == "string": value = "" if node.text is None else node.text serializer.write_string(key, value) elif node.tag == "vec2f": values = [child.text for child in node] serializer.write_vec2f(key, values) elif node.tag == "vec3f": values = [child.text for child in node] serializer.write_vec3f(key, values) elif node.tag == "vec4f": values = [child.text for child in node] serializer.write_vec4f(key, values) elif node.tag == "vec4b": values = [child.text for child in node] serializer.write_vec4b(key, values) elif node.tag == "array": if len(node) == 0: serializer.write_bytes_array(key, []) else: sub_tag = node[0].tag arr = [] for child in node: if child.tag != sub_tag: raise ValueError("Array contains multiple types") arr.append(child.text) if sub_tag == "bytes": arr = [bytes.fromhex(x) for x in arr] serializer.write_bytes_array(key, arr) elif sub_tag == "string": serializer.write_string_array(key, arr) else: raise ValueError("Array contains invalid type: " + sub_tag) else: raise ValueError("Tag not recognized: " + node.tag) def xml_to_resource(filename, outfile=None): with open(filename, "rb") as f: xml = ET.parse(f)
#!/usr/bin/env python3 class XmlResourceBuilder: def __init__(self): self.root = ET.Element("resource") self.stack = [self.root] self.arrays = [] self.parent = self.root def start_block(self, key=None): block = ET.SubElement(self.parent, "block") if key is not None: block.set("key", key) self.stack.append(self.parent) self.parent = block def finish_block(self): self.parent = self.stack.pop() def add_value(self, key, value, tag, sub_tag=None): el = ET.SubElement(self.parent, tag, key=key) if sub_tag is None: el.text = str(value) else: for n in value: sub_el = ET.SubElement(el, sub_tag) sub_el.text = str(n) def add_array(self, key, offset, size): el = ET.SubElement(self.parent, "bytes", key=key) self.arrays.append((offset, size, el)) # infer whether an array contains bytes, strings, or something else def infer_arrays(self, data, header_size): self.arrays.sort(key=lambda x: x[0]) for (offset, size, el), i in zip(self.arrays, range(len(self.arrays))): # "size" represents the number of elements (of unknown length) in the array # "true size" is the number of bytes in the array if i == len(self.arrays) - 1: true_size = len(data) - header_size - offset else: true_size = self.arrays[i + 1][0] - offset raw = data[header_size + offset:header_size + offset + true_size] if true_size == size: el.text = raw.hex() else: el.tag = "array" reader = BinaryReader(raw) strings = [] is_string_array = True # try to read array as strings, and deem it not a string array if it fails try: for _ in range(size): string_len = reader.read_uint32() string = reader.read_string(string_len) strings.append(string) is_string_array = reader.finished() except (UnicodeDecodeError, BinaryReaderError) as e: is_string_array = False if is_string_array: for string in strings: sub_el = ET.SubElement(el, "string") sub_el.text = string elif true_size % size != 0: raise ValueError(f"Failed to infer array structure at offset {header_size + offset}") else: reader.seek(0) while not reader.finished(): sub_el = ET.SubElement(el, "bytes") sub_el.text = reader.read_bytes(true_size // size).hex() def finished(self): return len(self.stack) == 0 def resource_to_xml(filename, outfile): parser = ResourceParser(filename) xml = parser.parse(XmlResourceBuilder) xml = ET.ElementTree(xml) xml.write(outfile, pretty_print=True) def _xml_to_resource_rec(serializer, node): key = node.attrib["key"] if "key" in node.attrib else None if node.tag == "block": serializer.begin(key) for child in node: _xml_to_resource_rec(serializer, child) serializer.end() elif node.tag == "bool8": if node.text.lower() == "true": value = True elif node.text.lower() == "false": value = False else: raise ValueError("Unexpected value for bool8") serializer.write_bool8(key, value) elif node.tag == "bytes": value = "" if node.text is None else node.text value = bytes.fromhex(value) serializer.write_bytes(key, value) elif node.tag == "float64": serializer.write_float64(key, node.text) elif node.tag == "float32": serializer.write_float32(key, node.text) elif node.tag == "uint32": serializer.write_uint32(key, node.text) elif node.tag == "int32": serializer.write_int32(key, node.text) elif node.tag == "uint64": serializer.write_uint64(key, node.text) elif node.tag == "int64": serializer.write_int64(key, node.text) elif node.tag == "mat2f": values = [child.text for child in node] serializer.write_mat2f(key, values) elif node.tag == "mat3f": values = [child.text for child in node] serializer.write_mat3f(key, values) elif node.tag == "mat4f": values = [child.text for child in node] serializer.write_mat4f(key, values) elif node.tag == "quatf": values = [child.text for child in node] serializer.write_quatf(key, values) elif node.tag == "string": value = "" if node.text is None else node.text serializer.write_string(key, value) elif node.tag == "vec2f": values = [child.text for child in node] serializer.write_vec2f(key, values) elif node.tag == "vec3f": values = [child.text for child in node] serializer.write_vec3f(key, values) elif node.tag == "vec4f": values = [child.text for child in node] serializer.write_vec4f(key, values) elif node.tag == "vec4b": values = [child.text for child in node] serializer.write_vec4b(key, values) elif node.tag == "array": if len(node) == 0: serializer.write_bytes_array(key, []) else: sub_tag = node[0].tag arr = [] for child in node: if child.tag != sub_tag: raise ValueError("Array contains multiple types") arr.append(child.text) if sub_tag == "bytes": arr = [bytes.fromhex(x) for x in arr] serializer.write_bytes_array(key, arr) elif sub_tag == "string": serializer.write_string_array(key, arr) else: raise ValueError("Array contains invalid type: " + sub_tag) else: raise ValueError("Tag not recognized: " + node.tag) def xml_to_resource(filename, outfile=None): with open(filename, "rb") as f: xml = ET.parse(f)
serializer = ResourceSerializer()
1
2023-10-14 11:18:04+00:00
8k
lmb-freiburg/ldce
ldm/modules/diffusionmodules/openaimodel.py
[ { "identifier": "checkpoint", "path": "ldm/modules/diffusionmodules/util.py", "snippet": "def checkpoint(func, inputs, params, flag):\n \"\"\"\n Evaluate a function without caching intermediate activations, allowing for\n reduced memory at the expense of extra compute in the backward pass.\n ...
from abc import abstractmethod from functools import partial from typing import Iterable from ldm.modules.diffusionmodules.util import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_module, normalization, timestep_embedding, ) from ldm.modules.attention import SpatialTransformer from omegaconf.listconfig import ListConfig import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F
3,769
use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ), AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_checkpoint=use_checkpoint, ), ResBlock( ch, time_embed_dim, dropout, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ), ) self._feature_size += ch self.output_blocks = nn.ModuleList([]) for level, mult in list(enumerate(channel_mult))[::-1]: for i in range(num_res_blocks + 1): ich = input_block_chans.pop() layers = [ ResBlock( ch + ich, time_embed_dim, dropout, out_channels=model_channels * mult, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = model_channels * mult if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels layers.append( AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads_upsample, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_checkpoint=use_checkpoint, ) ) if level and i == num_res_blocks: out_ch = ch layers.append( ResBlock( ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, up=True, ) if resblock_updown else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) ) ds //= 2 self.output_blocks.append(TimestepEmbedSequential(*layers)) self._feature_size += ch self.out = nn.Sequential( normalization(ch), nn.SiLU(), zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)), ) if self.predict_codebook_ids: self.id_predictor = nn.Sequential( normalization(ch), conv_nd(dims, model_channels, n_embed, 1), #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits ) def convert_to_fp16(self): """ Convert the torso of the model to float16. """ self.input_blocks.apply(convert_module_to_f16) self.middle_block.apply(convert_module_to_f16) self.output_blocks.apply(convert_module_to_f16) def convert_to_fp32(self): """ Convert the torso of the model to float32. """ self.input_blocks.apply(convert_module_to_f32) self.middle_block.apply(convert_module_to_f32) self.output_blocks.apply(convert_module_to_f32) def forward(self, x, timesteps=None, context=None, y=None,**kwargs): """ Apply the model to an input batch. :param x: an [N x C x ...] Tensor of inputs. :param timesteps: a 1-D batch of timesteps. :param context: conditioning plugged in via crossattn :param y: an [N] Tensor of labels, if class-conditional. :return: an [N x C x ...] Tensor of outputs. """ assert (y is not None) == ( self.num_classes is not None ), "must specify y if and only if the model is class-conditional" hs = []
# dummy replace def convert_module_to_f16(x): pass def convert_module_to_f32(x): pass ## go class AttentionPool2d(nn.Module): """ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py """ def __init__( self, spacial_dim: int, embed_dim: int, num_heads_channels: int, output_dim: int = None, ): super().__init__() self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5) self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1) self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1) self.num_heads = embed_dim // num_heads_channels self.attention = QKVAttention(self.num_heads) def forward(self, x): b, c, *_spatial = x.shape x = x.reshape(b, c, -1) # NC(HW) x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1) x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1) x = self.qkv_proj(x) x = self.attention(x) x = self.c_proj(x) return x[:, :, 0] class TimestepBlock(nn.Module): """ Any module where forward() takes timestep embeddings as a second argument. """ @abstractmethod def forward(self, x, emb): """ Apply the module to `x` given `emb` timestep embeddings. """ class TimestepEmbedSequential(nn.Sequential, TimestepBlock): """ A sequential module that passes timestep embeddings to the children that support it as an extra input. """ def forward(self, x, emb, context=None): for layer in self: if isinstance(layer, TimestepBlock): x = layer(x, emb) elif isinstance(layer, SpatialTransformer): x = layer(x, context) else: x = layer(x) return x class Upsample(nn.Module): """ An upsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then upsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims if use_conv: self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding) def forward(self, x): assert x.shape[1] == self.channels if self.dims == 3: x = F.interpolate( x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest" ) else: x = F.interpolate(x, scale_factor=2, mode="nearest") if self.use_conv: x = self.conv(x) return x class TransposedUpsample(nn.Module): 'Learned 2x upsampling without padding' def __init__(self, channels, out_channels=None, ks=5): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2) def forward(self,x): return self.up(x) class Downsample(nn.Module): """ A downsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then downsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims stride = 2 if dims != 3 else (1, 2, 2) if use_conv: self.op = conv_nd( dims, self.channels, self.out_channels, 3, stride=stride, padding=padding ) else: assert self.channels == self.out_channels self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) def forward(self, x): assert x.shape[1] == self.channels return self.op(x) class ResBlock(TimestepBlock): """ A residual block that can optionally change the number of channels. :param channels: the number of input channels. :param emb_channels: the number of timestep embedding channels. :param dropout: the rate of dropout. :param out_channels: if specified, the number of out channels. :param use_conv: if True and out_channels is specified, use a spatial convolution instead of a smaller 1x1 convolution to change the channels in the skip connection. :param dims: determines if the signal is 1D, 2D, or 3D. :param use_checkpoint: if True, use gradient checkpointing on this module. :param up: if True, use this block for upsampling. :param down: if True, use this block for downsampling. """ def __init__( self, channels, emb_channels, dropout, out_channels=None, use_conv=False, use_scale_shift_norm=False, dims=2, use_checkpoint=False, up=False, down=False, ): super().__init__() self.channels = channels self.emb_channels = emb_channels self.dropout = dropout self.out_channels = out_channels or channels self.use_conv = use_conv self.use_checkpoint = use_checkpoint self.use_scale_shift_norm = use_scale_shift_norm self.in_layers = nn.Sequential( normalization(channels), nn.SiLU(), conv_nd(dims, channels, self.out_channels, 3, padding=1), ) self.updown = up or down if up: self.h_upd = Upsample(channels, False, dims) self.x_upd = Upsample(channels, False, dims) elif down: self.h_upd = Downsample(channels, False, dims) self.x_upd = Downsample(channels, False, dims) else: self.h_upd = self.x_upd = nn.Identity() self.emb_layers = nn.Sequential( nn.SiLU(), linear( emb_channels, 2 * self.out_channels if use_scale_shift_norm else self.out_channels, ), ) self.out_layers = nn.Sequential( normalization(self.out_channels), nn.SiLU(), nn.Dropout(p=dropout), zero_module( conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1) ), ) if self.out_channels == channels: self.skip_connection = nn.Identity() elif use_conv: self.skip_connection = conv_nd( dims, channels, self.out_channels, 3, padding=1 ) else: self.skip_connection = conv_nd(dims, channels, self.out_channels, 1) def forward(self, x, emb): """ Apply the block to a Tensor, conditioned on a timestep embedding. :param x: an [N x C x ...] Tensor of features. :param emb: an [N x emb_channels] Tensor of timestep embeddings. :return: an [N x C x ...] Tensor of outputs. """ return checkpoint( self._forward, (x, emb), self.parameters(), self.use_checkpoint ) def _forward(self, x, emb): if self.updown: in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] h = in_rest(x) h = self.h_upd(h) x = self.x_upd(x) h = in_conv(h) else: h = self.in_layers(x) emb_out = self.emb_layers(emb).type(h.dtype) while len(emb_out.shape) < len(h.shape): emb_out = emb_out[..., None] if self.use_scale_shift_norm: out_norm, out_rest = self.out_layers[0], self.out_layers[1:] scale, shift = th.chunk(emb_out, 2, dim=1) h = out_norm(h) * (1 + scale) + shift h = out_rest(h) else: h = h + emb_out h = self.out_layers(h) return self.skip_connection(x) + h class AttentionBlock(nn.Module): """ An attention block that allows spatial positions to attend to each other. Originally ported from here, but adapted to the N-d case. https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66. """ def __init__( self, channels, num_heads=1, num_head_channels=-1, use_checkpoint=False, use_new_attention_order=False, ): super().__init__() self.channels = channels if num_head_channels == -1: self.num_heads = num_heads else: assert ( channels % num_head_channels == 0 ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" self.num_heads = channels // num_head_channels self.use_checkpoint = use_checkpoint self.norm = normalization(channels) self.qkv = conv_nd(1, channels, channels * 3, 1) if use_new_attention_order: # split qkv before split heads self.attention = QKVAttention(self.num_heads) else: # split heads before split qkv self.attention = QKVAttentionLegacy(self.num_heads) self.proj_out = zero_module(conv_nd(1, channels, channels, 1)) def forward(self, x): return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!! #return pt_checkpoint(self._forward, x) # pytorch def _forward(self, x): b, c, *spatial = x.shape x = x.reshape(b, c, -1) qkv = self.qkv(self.norm(x)) h = self.attention(qkv) h = self.proj_out(h) return (x + h).reshape(b, c, *spatial) def count_flops_attn(model, _x, y): """ A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, ) """ b, c, *spatial = y[0].shape num_spatial = int(np.prod(spatial)) # We perform two matmuls with the same number of ops. # The first computes the weight matrix, the second computes # the combination of the value vectors. matmul_ops = 2 * b * (num_spatial ** 2) * c model.total_ops += th.DoubleTensor([matmul_ops]) class QKVAttentionLegacy(nn.Module): """ A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping """ def __init__(self, n_heads): super().__init__() self.n_heads = n_heads def forward(self, qkv): """ Apply QKV attention. :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention. """ bs, width, length = qkv.shape assert width % (3 * self.n_heads) == 0 ch = width // (3 * self.n_heads) q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) scale = 1 / math.sqrt(math.sqrt(ch)) weight = th.einsum( "bct,bcs->bts", q * scale, k * scale ) # More stable with f16 than dividing afterwards weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) a = th.einsum("bts,bcs->bct", weight, v) return a.reshape(bs, -1, length) @staticmethod def count_flops(model, _x, y): return count_flops_attn(model, _x, y) class QKVAttention(nn.Module): """ A module which performs QKV attention and splits in a different order. """ def __init__(self, n_heads): super().__init__() self.n_heads = n_heads def forward(self, qkv): """ Apply QKV attention. :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention. """ bs, width, length = qkv.shape assert width % (3 * self.n_heads) == 0 ch = width // (3 * self.n_heads) q, k, v = qkv.chunk(3, dim=1) scale = 1 / math.sqrt(math.sqrt(ch)) weight = th.einsum( "bct,bcs->bts", (q * scale).view(bs * self.n_heads, ch, length), (k * scale).view(bs * self.n_heads, ch, length), ) # More stable with f16 than dividing afterwards weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length)) return a.reshape(bs, -1, length) @staticmethod def count_flops(model, _x, y): return count_flops_attn(model, _x, y) class UNetModel(nn.Module): """ The full UNet model with attention and timestep embedding. :param in_channels: channels in the input Tensor. :param model_channels: base channel count for the model. :param out_channels: channels in the output Tensor. :param num_res_blocks: number of residual blocks per downsample. :param attention_resolutions: a collection of downsample rates at which attention will take place. May be a set, list, or tuple. For example, if this contains 4, then at 4x downsampling, attention will be used. :param dropout: the dropout probability. :param channel_mult: channel multiplier for each level of the UNet. :param conv_resample: if True, use learned convolutions for upsampling and downsampling. :param dims: determines if the signal is 1D, 2D, or 3D. :param num_classes: if specified (as an int), then this model will be class-conditional with `num_classes` classes. :param use_checkpoint: use gradient checkpointing to reduce memory usage. :param num_heads: the number of attention heads in each attention layer. :param num_heads_channels: if specified, ignore num_heads and instead use a fixed channel width per attention head. :param num_heads_upsample: works with num_heads to set a different number of heads for upsampling. Deprecated. :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. :param resblock_updown: use residual blocks for up/downsampling. :param use_new_attention_order: use a different attention pattern for potentially increased efficiency. """ def __init__( self, image_size, in_channels, model_channels, out_channels, num_res_blocks, attention_resolutions, dropout=0, channel_mult=(1, 2, 4, 8), conv_resample=True, dims=2, num_classes=None, use_checkpoint=False, use_fp16=False, num_heads=-1, num_head_channels=-1, num_heads_upsample=-1, use_scale_shift_norm=False, resblock_updown=False, use_new_attention_order=False, use_spatial_transformer=False, # custom transformer support transformer_depth=1, # custom transformer support context_dim=None, # custom transformer support n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model legacy=True, ): super().__init__() if use_spatial_transformer: assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...' if context_dim is not None: assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...' if type(context_dim) == ListConfig: context_dim = list(context_dim) if num_heads_upsample == -1: num_heads_upsample = num_heads if num_heads == -1: assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' if num_head_channels == -1: assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' self.image_size = image_size self.in_channels = in_channels self.model_channels = model_channels self.out_channels = out_channels self.num_res_blocks = num_res_blocks self.attention_resolutions = attention_resolutions self.dropout = dropout self.channel_mult = channel_mult self.conv_resample = conv_resample self.num_classes = num_classes self.use_checkpoint = use_checkpoint self.dtype = th.float16 if use_fp16 else th.float32 self.num_heads = num_heads self.num_head_channels = num_head_channels self.num_heads_upsample = num_heads_upsample self.predict_codebook_ids = n_embed is not None time_embed_dim = model_channels * 4 self.time_embed = nn.Sequential( linear(model_channels, time_embed_dim), nn.SiLU(), linear(time_embed_dim, time_embed_dim), ) if self.num_classes is not None: self.label_emb = nn.Embedding(num_classes, time_embed_dim) self.input_blocks = nn.ModuleList( [ TimestepEmbedSequential( conv_nd(dims, in_channels, model_channels, 3, padding=1) ) ] ) self._feature_size = model_channels input_block_chans = [model_channels] ch = model_channels ds = 1 for level, mult in enumerate(channel_mult): for _ in range(num_res_blocks): layers = [ ResBlock( ch, time_embed_dim, dropout, out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = mult * model_channels if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels layers.append( AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_checkpoint=use_checkpoint, ) ) self.input_blocks.append(TimestepEmbedSequential(*layers)) self._feature_size += ch input_block_chans.append(ch) if level != len(channel_mult) - 1: out_ch = ch self.input_blocks.append( TimestepEmbedSequential( ResBlock( ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, down=True, ) if resblock_updown else Downsample( ch, conv_resample, dims=dims, out_channels=out_ch ) ) ) ch = out_ch input_block_chans.append(ch) ds *= 2 self._feature_size += ch if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels self.middle_block = TimestepEmbedSequential( ResBlock( ch, time_embed_dim, dropout, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ), AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_checkpoint=use_checkpoint, ), ResBlock( ch, time_embed_dim, dropout, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ), ) self._feature_size += ch self.output_blocks = nn.ModuleList([]) for level, mult in list(enumerate(channel_mult))[::-1]: for i in range(num_res_blocks + 1): ich = input_block_chans.pop() layers = [ ResBlock( ch + ich, time_embed_dim, dropout, out_channels=model_channels * mult, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = model_channels * mult if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels layers.append( AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads_upsample, num_head_channels=dim_head, use_new_attention_order=use_new_attention_order, ) if not use_spatial_transformer else SpatialTransformer( ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_checkpoint=use_checkpoint, ) ) if level and i == num_res_blocks: out_ch = ch layers.append( ResBlock( ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, up=True, ) if resblock_updown else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) ) ds //= 2 self.output_blocks.append(TimestepEmbedSequential(*layers)) self._feature_size += ch self.out = nn.Sequential( normalization(ch), nn.SiLU(), zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)), ) if self.predict_codebook_ids: self.id_predictor = nn.Sequential( normalization(ch), conv_nd(dims, model_channels, n_embed, 1), #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits ) def convert_to_fp16(self): """ Convert the torso of the model to float16. """ self.input_blocks.apply(convert_module_to_f16) self.middle_block.apply(convert_module_to_f16) self.output_blocks.apply(convert_module_to_f16) def convert_to_fp32(self): """ Convert the torso of the model to float32. """ self.input_blocks.apply(convert_module_to_f32) self.middle_block.apply(convert_module_to_f32) self.output_blocks.apply(convert_module_to_f32) def forward(self, x, timesteps=None, context=None, y=None,**kwargs): """ Apply the model to an input batch. :param x: an [N x C x ...] Tensor of inputs. :param timesteps: a 1-D batch of timesteps. :param context: conditioning plugged in via crossattn :param y: an [N] Tensor of labels, if class-conditional. :return: an [N x C x ...] Tensor of outputs. """ assert (y is not None) == ( self.num_classes is not None ), "must specify y if and only if the model is class-conditional" hs = []
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
6
2023-10-10 09:40:10+00:00
8k
seriaati/hoyo-buddy
hoyo_buddy/hoyo/genshin/ambr.py
[ { "identifier": "WEEKDAYS", "path": "hoyo_buddy/bot/constants.py", "snippet": "WEEKDAYS: dict[int, str] = {\n 0: \"Monday\",\n 1: \"Tuesday\",\n 2: \"Wednesday\",\n 3: \"Thursday\",\n 4: \"Friday\",\n 5: \"Saturday\",\n 6: \"Sunday\",\n}" }, { "identifier": "COMFORT_ICON", ...
import re import ambr import discord.utils as dutils from collections import defaultdict from enum import StrEnum from typing import TYPE_CHECKING, Any from ambr.client import Language from discord import Locale from ...bot.constants import WEEKDAYS from ...bot.emojis import COMFORT_ICON, DICE_EMOJIS, LOAD_ICON, get_element_emoji from ...bot.translator import LocaleStr, Translator from ...embeds import DefaultEmbed from ...utils import create_bullet_list, shorten from types import TracebackType
4,945
key="weapon_embed_title", ), description=( f"{weapon.rarity}★ {weapon.type}\n{main_stat_name}: {round(main_stat_value)}" ), ) if sub_stat_name and sub_stat_value: if embed.description is None: msg = "Embed description is None" raise AssertionError(msg) embed.description += f"\n{sub_stat_name}: {sub_stat_value}" if weapon.affix: embed.add_field( name=LocaleStr("Refinement {r}", r=refinement, key="refinement_indicator"), value=weapon.affix.upgrades[refinement - 1].description, ) embed.set_thumbnail(url=weapon.icon) embed.set_footer(text=weapon.description) return embed def get_namecard_embed(self, namecard: ambr.NamecardDetail) -> DefaultEmbed: embed = DefaultEmbed( self.locale, self.translator, title=namecard.name, description=namecard.description, ) embed.set_thumbnail(url=namecard.icon) embed.set_image(url=namecard.picture) if namecard.source: embed.set_footer(text=namecard.source) return embed def get_artifact_embed( self, artifact_set: ambr.ArtifactSetDetail, artifact: ambr.Artifact ) -> DefaultEmbed: description = self.translator.translate( LocaleStr( "2-Pieces: {bonus_2}", bonus_2=artifact_set.affix_list[0].effect, key="artifact_set_two_piece_embed_description", ), self.locale, ) if len(artifact_set.affix_list) == 2: four_piece = LocaleStr( "4-Pieces: {bonus_4}", bonus_4=artifact_set.affix_list[1].effect, key="artifact_set_four_piece_embed_description", ) description += "\n" + self.translator.translate(four_piece, self.locale) embed = DefaultEmbed( self.locale, self.translator, title=artifact.name, description=description ) embed.set_author(name=artifact_set.name, icon_url=artifact_set.icon) embed.set_footer(text=artifact.description) embed.set_thumbnail(url=artifact.icon) return embed def get_food_embed(self, food: ambr.FoodDetail) -> DefaultEmbed: description = create_bullet_list([s.name for s in food.sources]) if isinstance(food.recipe, ambr.FoodRecipe): description += f"\n{create_bullet_list([e.description for e in food.recipe.effects])}" embed = DefaultEmbed( self.locale, self.translator, title=food.name, description=description, ) embed.set_thumbnail(url=food.icon) embed.set_footer(text=food.description) return embed def get_material_embed(self, material: ambr.MaterialDetail) -> DefaultEmbed: if material.sources: names: list[str] = [] for source in material.sources: if source.days: days_str = ", ".join( [self.translator.translate(WEEKDAYS[d], self.locale) for d in source.days] ) names.append(f"{source.name} ({days_str})") else: names.append(source.name) description = create_bullet_list(names) else: description = material.description embed = DefaultEmbed( self.locale, self.translator, title=f"{material.name}\n{'★' * material.rarity}", description=description, ) embed.set_thumbnail(url=material.icon) embed.set_author(name=material.type) if material.sources: embed.set_footer(text=material.description) return embed def get_furniture_embed(self, furniture: ambr.FurnitureDetail) -> DefaultEmbed: embed = DefaultEmbed( self.locale, self.translator, title=f"{furniture.name}\n{'★' * furniture.rarity}", description=LocaleStr( "{comfort_icon} Comfort: {comfort}\n" "{load_icon} Load: {load}\n" "Trust: {trust}\n" "Creation Time: {hour}h", key="furniture_embed_description", comfort_icon=COMFORT_ICON,
__all__ = ("LOCALE_TO_LANG", "AmbrAPIClient", "ItemCategory", "AUDIO_LANGUAGES") if TYPE_CHECKING: LOCALE_TO_LANG: dict[Locale, Language] = { Locale.taiwan_chinese: Language.CHT, Locale.chinese: Language.CHS, Locale.german: Language.DE, Locale.american_english: Language.EN, Locale.spain_spanish: Language.ES, Locale.french: Language.FR, Locale.indonesian: Language.ID, Locale.japanese: Language.JP, Locale.korean: Language.KR, Locale.brazil_portuguese: Language.PT, Locale.russian: Language.RU, Locale.thai: Language.TH, Locale.vietnamese: Language.VI, Locale.italian: Language.IT, Locale.turkish: Language.TR, } PERCENTAGE_FIGHT_PROPS = ( "FIGHT_PROP_HP_PERCENT", "FIGHT_PROP_ATTACK_PERCENT", "FIGHT_PROP_DEFENSE_PERCENT", "FIGHT_PROP_SPEED_PERCENT", "FIGHT_PROP_CRITICAL", "FIGHT_PROP_CRITICAL_HURT", "FIGHT_PROP_CHARGE_EFFICIENCY", "FIGHT_PROP_ADD_HURT", "FIGHT_PROP_HEAL_ADD", "FIGHT_PROP_HEALED_ADD", "FIGHT_PROP_FIRE_ADD_HURT", "FIGHT_PROP_WATER_ADD_HURT", "FIGHT_PROP_GRASS_ADD_HURT", "FIGHT_PROP_ELEC_ADD_HURT", "FIGHT_PROP_ICE_ADD_HURT", "FIGHT_PROP_WIND_ADD_HURT", "FIGHT_PROP_PHYSICAL_ADD_HURT", "FIGHT_PROP_ROCK_ADD_HURT", "FIGHT_PROP_SKILL_CD_MINUS_RATIO", "FIGHT_PROP_ATTACK_PERCENT_A", "FIGHT_PROP_DEFENSE_PERCENT_A", "FIGHT_PROP_HP_PERCENT_A", ) AUDIO_LANGUAGES = ("EN", "CHS", "JP", "KR") class ItemCategory(StrEnum): CHARACTERS = "Characters" WEAPONS = "Weapons" ARTIFACT_SETS = "Artifact Sets" FOOD = "Food" MATERIALS = "Materials" FURNISHINGS = "Furnishings" FURNISHING_SETS = "Furnishing Sets" NAMECARDS = "Namecards" LIVING_BEINGS = "Living Beings" BOOKS = "Books" TCG = "TCG" class AmbrAPIClient(ambr.AmbrAPI): # noqa: PLR0904 def __init__(self, locale: Locale, translator: Translator) -> None: super().__init__(LOCALE_TO_LANG.get(locale, Language.EN)) self.locale = locale self.translator = translator async def __aenter__(self) -> "AmbrAPIClient": return self async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: "TracebackType | None", ) -> None: return await super().close() @staticmethod def _format_num(digits: int, calculation: int | float) -> str: return f"{calculation:.{digits}f}" @staticmethod def _calculate_upgrade_stat_values( upgrade_data: ambr.CharacterUpgrade | ambr.WeaponUpgrade, curve_data: dict[str, dict[str, dict[str, float]]], level: int, ascended: bool, ) -> dict[str, float]: result: defaultdict[str, float] = defaultdict(float) for stat in upgrade_data.base_stats: if stat.prop_type is None: continue result[stat.prop_type] = ( stat.init_value * curve_data[str(level)]["curveInfos"][stat.growth_type] ) for promote in reversed(upgrade_data.promotes): if promote.add_stats is None: continue if (level == promote.unlock_max_level and ascended) or level > promote.unlock_max_level: for stat in promote.add_stats: if stat.value != 0: result[stat.id] += stat.value if stat.id in { "FIGHT_PROP_CRITICAL_HURT", "FIGHT_PROP_CRITICAL", }: result[stat.id] += 0.5 break return result @staticmethod def _format_stat_values(stat_values: dict[str, float]) -> dict[str, str]: result: dict[str, str] = {} for fight_prop, value in stat_values.items(): if fight_prop in PERCENTAGE_FIGHT_PROPS: result[fight_prop] = f"{round(value * 100, 1)}%" else: result[fight_prop] = str(round(value)) return result @staticmethod def _replace_fight_prop_with_name( stat_values: dict[str, Any], manual_weapon: dict[str, str] ) -> dict[str, Any]: result: dict[str, Any] = {} for fight_prop, value in stat_values.items(): fight_prop_name = manual_weapon.get(fight_prop, fight_prop) result[fight_prop_name] = value return result @staticmethod def _format_layout(text: str) -> str: if "LAYOUT" in text: brackets = re.findall(r"{LAYOUT.*?}", text) word_to_replace = re.findall(r"{LAYOUT.*?#(.*?)}", brackets[0])[0] text = text.replace("".join(brackets), word_to_replace) return text def _get_params(self, text: str, param_list: list[int | float]) -> list[str]: params: list[str] = re.findall(r"{[^}]*}", text) for item in params: if "param" not in item: continue param_text = re.findall(r"{param(\d+):([^}]*)}", item)[0] param, value = param_text if value in {"F1P", "F2P"}: result = self._format_num(int(value[1]), param_list[int(param) - 1] * 100) text = re.sub(re.escape(item), f"{result}%", text) elif value in {"F1", "F2"}: result = self._format_num(int(value[1]), param_list[int(param) - 1]) text = re.sub(re.escape(item), result, text) elif value == "P": result = self._format_num(0, param_list[int(param) - 1] * 100) text = re.sub(re.escape(item), f"{result}%", text) elif value == "I": result = int(param_list[int(param) - 1]) text = re.sub(re.escape(item), str(round(result)), text) text = self._format_layout(text) text = text.replace("{NON_BREAK_SPACE}", "") text = text.replace("#", "") return text.split("|") def _get_skill_attributes(self, descriptions: list[str], params: list[int | float]) -> str: result = "" for desc in descriptions: try: k, v = self._get_params(desc, params) except ValueError: continue result += f"{k}: {v}\n" return result async def fetch_items(self, item_category: ItemCategory) -> list[Any]: # noqa: PLR0911 match item_category: case ItemCategory.CHARACTERS: return await self.fetch_characters() case ItemCategory.WEAPONS: return await self.fetch_weapons() case ItemCategory.ARTIFACT_SETS: return await self.fetch_artifact_sets() case ItemCategory.FOOD: return await self.fetch_foods() case ItemCategory.MATERIALS: return await self.fetch_materials() case ItemCategory.FURNISHINGS: return await self.fetch_furnitures() case ItemCategory.FURNISHING_SETS: return await self.fetch_furniture_sets() case ItemCategory.NAMECARDS: return await self.fetch_namecards() case ItemCategory.LIVING_BEINGS: return await self.fetch_monsters() case ItemCategory.BOOKS: return await self.fetch_books() case ItemCategory.TCG: return await self.fetch_tcg_cards() def get_character_embed( self, character: ambr.CharacterDetail, level: int, avatar_curve: dict[str, dict[str, dict[str, float]]], manual_weapon: dict[str, str], ) -> DefaultEmbed: stat_values = self._calculate_upgrade_stat_values( character.upgrade, avatar_curve, level, True ) formatted_stat_values = self._format_stat_values(stat_values) named_stat_values = self._replace_fight_prop_with_name(formatted_stat_values, manual_weapon) embed = DefaultEmbed( self.locale, self.translator, title=character.name, description=LocaleStr( ( "{rarity}★ {element}\n" "Birthday: {birthday}\n" "Constellation: {constellation}\n" "Affiliation: {affiliation}\n" ), key="character_embed_description", rarity=character.rarity, element=get_element_emoji(character.element.name), birthday=f"{character.birthday.month}/{character.birthday.day}", constellation=character.info.constellation, affiliation=character.info.native, ), ) level_str = self.translator.translate( LocaleStr( "Lv. {level}", key="level_str", level=level, ), self.locale, ) embed.add_field( name=f"Stats ({level_str})", value="\n".join(f"{k}: {v}" for k, v in named_stat_values.items()), ) embed.set_footer(text=character.info.detail) embed.set_thumbnail(url=character.icon) embed.set_image(url=character.gacha) return embed def get_character_talent_embed(self, talent: ambr.Talent, level: int) -> DefaultEmbed: embed = DefaultEmbed( self.locale, self.translator, title=talent.name, description=self._format_layout(talent.description).replace("#", ""), ) if talent.upgrades: try: level_upgrade = talent.upgrades[level - 1] except IndexError: level_upgrade = talent.upgrades[-1] level = level_upgrade.level level_str = self.translator.translate( LocaleStr( "Lv. {level}", key="level_str", level=level, ), self.locale, ) embed.add_field( name=f"Skill Attributes ({level_str})", value=self._get_skill_attributes(level_upgrade.description, level_upgrade.params), ) embed.set_thumbnail(url=talent.icon) return embed def get_character_constellation_embed(self, constellation: ambr.Constellation) -> DefaultEmbed: embed = DefaultEmbed( self.locale, self.translator, title=constellation.name, description=constellation.description, ) embed.set_thumbnail(url=constellation.icon) return embed def get_character_story_embed(self, story: ambr.Story) -> DefaultEmbed: embed = DefaultEmbed( self.locale, self.translator, title=story.title, description=story.text, ) if story.tips: embed.set_footer(text=story.tips) return embed def get_character_quote_embed(self, quote: ambr.Quote, character_id: str) -> DefaultEmbed: embed = DefaultEmbed( self.locale, self.translator, title=quote.title, description=f"{quote.text}\n\n" + " ".join( f"[{lang}](https://api.ambr.top/assets/Audio/{lang}/{character_id}/{quote.audio_id}.ogg)" for lang in AUDIO_LANGUAGES ), ) if quote.tips: embed.set_footer(text=quote.tips) return embed def get_weapon_embed( self, weapon: ambr.WeaponDetail, level: int, refinement: int, weapon_curve: dict[str, dict[str, dict[str, float]]], manual_weapon: dict[str, str], ) -> DefaultEmbed: stat_values = self._calculate_upgrade_stat_values(weapon.upgrade, weapon_curve, level, True) main_stat = weapon.upgrade.base_stats[0] if main_stat.prop_type is None: msg = "Weapon has no main stat" raise AssertionError(msg) main_stat_name = manual_weapon[main_stat.prop_type] main_stat_value = stat_values[main_stat.prop_type] sub_stat = weapon.upgrade.base_stats[1] sub_stat_name = manual_weapon[sub_stat.prop_type] if sub_stat.prop_type else None sub_stat_value = stat_values[sub_stat.prop_type] if sub_stat.prop_type else None if sub_stat_value is not None and sub_stat.prop_type in PERCENTAGE_FIGHT_PROPS: sub_stat_value *= 100 sub_stat_value = round(sub_stat_value, 1) sub_stat_value = f"{sub_stat_value}%" embed = DefaultEmbed( self.locale, self.translator, title=LocaleStr( "{weapon_name} ({level_str})", weapon_name=weapon.name, level_str=LocaleStr( "Lv. {level}", key="level_str", level=level, ), key="weapon_embed_title", ), description=( f"{weapon.rarity}★ {weapon.type}\n{main_stat_name}: {round(main_stat_value)}" ), ) if sub_stat_name and sub_stat_value: if embed.description is None: msg = "Embed description is None" raise AssertionError(msg) embed.description += f"\n{sub_stat_name}: {sub_stat_value}" if weapon.affix: embed.add_field( name=LocaleStr("Refinement {r}", r=refinement, key="refinement_indicator"), value=weapon.affix.upgrades[refinement - 1].description, ) embed.set_thumbnail(url=weapon.icon) embed.set_footer(text=weapon.description) return embed def get_namecard_embed(self, namecard: ambr.NamecardDetail) -> DefaultEmbed: embed = DefaultEmbed( self.locale, self.translator, title=namecard.name, description=namecard.description, ) embed.set_thumbnail(url=namecard.icon) embed.set_image(url=namecard.picture) if namecard.source: embed.set_footer(text=namecard.source) return embed def get_artifact_embed( self, artifact_set: ambr.ArtifactSetDetail, artifact: ambr.Artifact ) -> DefaultEmbed: description = self.translator.translate( LocaleStr( "2-Pieces: {bonus_2}", bonus_2=artifact_set.affix_list[0].effect, key="artifact_set_two_piece_embed_description", ), self.locale, ) if len(artifact_set.affix_list) == 2: four_piece = LocaleStr( "4-Pieces: {bonus_4}", bonus_4=artifact_set.affix_list[1].effect, key="artifact_set_four_piece_embed_description", ) description += "\n" + self.translator.translate(four_piece, self.locale) embed = DefaultEmbed( self.locale, self.translator, title=artifact.name, description=description ) embed.set_author(name=artifact_set.name, icon_url=artifact_set.icon) embed.set_footer(text=artifact.description) embed.set_thumbnail(url=artifact.icon) return embed def get_food_embed(self, food: ambr.FoodDetail) -> DefaultEmbed: description = create_bullet_list([s.name for s in food.sources]) if isinstance(food.recipe, ambr.FoodRecipe): description += f"\n{create_bullet_list([e.description for e in food.recipe.effects])}" embed = DefaultEmbed( self.locale, self.translator, title=food.name, description=description, ) embed.set_thumbnail(url=food.icon) embed.set_footer(text=food.description) return embed def get_material_embed(self, material: ambr.MaterialDetail) -> DefaultEmbed: if material.sources: names: list[str] = [] for source in material.sources: if source.days: days_str = ", ".join( [self.translator.translate(WEEKDAYS[d], self.locale) for d in source.days] ) names.append(f"{source.name} ({days_str})") else: names.append(source.name) description = create_bullet_list(names) else: description = material.description embed = DefaultEmbed( self.locale, self.translator, title=f"{material.name}\n{'★' * material.rarity}", description=description, ) embed.set_thumbnail(url=material.icon) embed.set_author(name=material.type) if material.sources: embed.set_footer(text=material.description) return embed def get_furniture_embed(self, furniture: ambr.FurnitureDetail) -> DefaultEmbed: embed = DefaultEmbed( self.locale, self.translator, title=f"{furniture.name}\n{'★' * furniture.rarity}", description=LocaleStr( "{comfort_icon} Comfort: {comfort}\n" "{load_icon} Load: {load}\n" "Trust: {trust}\n" "Creation Time: {hour}h", key="furniture_embed_description", comfort_icon=COMFORT_ICON,
load_icon=LOAD_ICON,
3
2023-10-13 09:45:52+00:00
8k
kayprogrammer/socialnet-v2
apps/accounts/views.py
[ { "identifier": "ErrorCode", "path": "apps/common/error.py", "snippet": "class ErrorCode:\n UNAUTHORIZED_USER = \"unauthorized_user\"\n NETWORK_FAILURE = \"network_failure\"\n SERVER_ERROR = \"server_error\"\n INVALID_ENTRY = \"invalid_entry\"\n INCORRECT_EMAIL = \"incorrect_email\"\n ...
from ninja import Router from apps.common.error import ErrorCode from apps.common.responses import CustomResponse from apps.common.utils import AuthUser from apps.common.schemas import ResponseSchema from .schemas import ( LoginUserSchema, RefreshTokensSchema, RegisterResponseSchema, RegisterUserSchema, RequestOtpSchema, SetNewPasswordSchema, TokensResponseSchema, VerifyOtpSchema, ) from .auth import Authentication from .emails import Util from .models import Otp, User from apps.common.exceptions import RequestError
4,349
@auth_router.post( "/set-new-password/", summary="Set New Password", description="This endpoint verifies the password reset otp", response=ResponseSchema, ) async def set_new_password(request, data: SetNewPasswordSchema): email = data.email code = data.otp password = data.password user = await User.objects.aget_or_none(email=email) if not user: raise RequestError( err_code=ErrorCode.INCORRECT_EMAIL, err_msg="Incorrect Email", status_code=404, ) otp = await Otp.objects.aget_or_none(user=user) if not otp or otp.code != code: raise RequestError( err_code=ErrorCode.INCORRECT_OTP, err_msg="Incorrect Otp", status_code=404, ) if otp.check_expiration(): raise RequestError( err_code=ErrorCode.EXPIRED_OTP, err_msg="Expired Otp", status_code=498 ) user.set_password(password) await user.asave() # Send password reset success email Util.password_reset_confirmation(user) return CustomResponse.success(message="Password reset successful") @auth_router.post( "/login/", summary="Login a user", description="This endpoint generates new access and refresh tokens for authentication", response={201: TokensResponseSchema}, ) async def login(request, data: LoginUserSchema): email = data.email password = data.password user = await User.objects.aget_or_none(email=email) if not user or not user.check_password(password): raise RequestError( err_code=ErrorCode.INVALID_CREDENTIALS, err_msg="Invalid credentials", status_code=401, ) if not user.is_email_verified: raise RequestError( err_code=ErrorCode.UNVERIFIED_USER, err_msg="Verify your email first", status_code=401, ) # Create tokens and store in jwt model access = Authentication.create_access_token( {"user_id": str(user.id), "username": user.username} ) refresh = Authentication.create_refresh_token() user.access = access user.refresh = refresh await user.asave() return CustomResponse.success( message="Login successful", data={"access": access, "refresh": refresh}, status_code=201, ) @auth_router.post( "/refresh/", summary="Refresh tokens", description="This endpoint refresh tokens by generating new access and refresh tokens for a user", response={201: TokensResponseSchema}, ) async def refresh(request, data: RefreshTokensSchema): token = data.refresh user = await User.objects.aget_or_none(refresh=token) if not user or not Authentication.decode_jwt(token): raise RequestError( err_code=ErrorCode.INVALID_TOKEN, err_msg="Refresh token is invalid or expired", status_code=401, ) access = Authentication.create_access_token( {"user_id": str(user.id), "username": user.username} ) refresh = Authentication.create_refresh_token() user.access = access user.refresh = refresh await user.asave() return CustomResponse.success( message="Tokens refresh successful", data={"access": access, "refresh": refresh}, status_code=201, ) @auth_router.get( "/logout/", summary="Logout a user", description="This endpoint logs a user out from our application", response=ResponseSchema,
auth_router = Router(tags=["Auth"]) @auth_router.post( "/register/", summary="Register a new user", description="This endpoint registers new users into our application", response={201: RegisterResponseSchema}, ) async def register(request, data: RegisterUserSchema): # Check for existing user existing_user = await User.objects.aget_or_none(email=data.email) if existing_user: raise RequestError( err_code=ErrorCode.INVALID_ENTRY, err_msg="Invalid Entry", status_code=422, data={"email": "Email already registered!"}, ) # Create user user = await User.objects.acreate_user(**data.dict()) # Send verification email await Util.send_activation_otp(user) return CustomResponse.success( message="Registration successful", data={"email": data.email}, status_code=201 ) @auth_router.post( "/verify-email/", summary="Verify a user's email", description="This endpoint verifies a user's email", response=ResponseSchema, ) async def verify_email(request, data: VerifyOtpSchema): email = data.email otp_code = data.otp user = await User.objects.aget_or_none(email=email) if not user: raise RequestError( err_code=ErrorCode.INCORRECT_EMAIL, err_msg="Incorrect Email", status_code=404, ) if user.is_email_verified: return CustomResponse.success(message="Email already verified") otp = await Otp.objects.aget_or_none(user=user) if not otp or otp.code != otp_code: raise RequestError( err_code=ErrorCode.INCORRECT_OTP, err_msg="Incorrect Otp", status_code=404 ) if otp.check_expiration(): raise RequestError( err_code=ErrorCode.EXPIRED_OTP, err_msg="Expired Otp", status_code=498 ) user.is_email_verified = True await user.asave() await otp.adelete() # Send welcome email Util.welcome_email(user) return CustomResponse.success(message="Account verification successful") @auth_router.post( "/resend-verification-email/", summary="Resend Verification Email", description="This endpoint resends new otp to the user's email", response=ResponseSchema, ) async def resend_verification_email(request, data: RequestOtpSchema): email = data.email user = await User.objects.aget_or_none(email=email) if not user: raise RequestError( err_code=ErrorCode.INCORRECT_EMAIL, err_msg="Incorrect Email", status_code=404, ) if user.is_email_verified: return CustomResponse.success(message="Email already verified") # Send verification email await Util.send_activation_otp(user) return CustomResponse.success(message="Verification email sent") @auth_router.post( "/send-password-reset-otp/", summary="Send Password Reset Otp", description="This endpoint sends new password reset otp to the user's email", response=ResponseSchema, ) async def send_password_reset_otp(request, data: RequestOtpSchema): email = data.email user = await User.objects.aget_or_none(email=email) if not user: raise RequestError( err_code=ErrorCode.INCORRECT_EMAIL, err_msg="Incorrect Email", status_code=404, ) # Send password reset email await Util.send_password_change_otp(user) return CustomResponse.success(message="Password otp sent") @auth_router.post( "/set-new-password/", summary="Set New Password", description="This endpoint verifies the password reset otp", response=ResponseSchema, ) async def set_new_password(request, data: SetNewPasswordSchema): email = data.email code = data.otp password = data.password user = await User.objects.aget_or_none(email=email) if not user: raise RequestError( err_code=ErrorCode.INCORRECT_EMAIL, err_msg="Incorrect Email", status_code=404, ) otp = await Otp.objects.aget_or_none(user=user) if not otp or otp.code != code: raise RequestError( err_code=ErrorCode.INCORRECT_OTP, err_msg="Incorrect Otp", status_code=404, ) if otp.check_expiration(): raise RequestError( err_code=ErrorCode.EXPIRED_OTP, err_msg="Expired Otp", status_code=498 ) user.set_password(password) await user.asave() # Send password reset success email Util.password_reset_confirmation(user) return CustomResponse.success(message="Password reset successful") @auth_router.post( "/login/", summary="Login a user", description="This endpoint generates new access and refresh tokens for authentication", response={201: TokensResponseSchema}, ) async def login(request, data: LoginUserSchema): email = data.email password = data.password user = await User.objects.aget_or_none(email=email) if not user or not user.check_password(password): raise RequestError( err_code=ErrorCode.INVALID_CREDENTIALS, err_msg="Invalid credentials", status_code=401, ) if not user.is_email_verified: raise RequestError( err_code=ErrorCode.UNVERIFIED_USER, err_msg="Verify your email first", status_code=401, ) # Create tokens and store in jwt model access = Authentication.create_access_token( {"user_id": str(user.id), "username": user.username} ) refresh = Authentication.create_refresh_token() user.access = access user.refresh = refresh await user.asave() return CustomResponse.success( message="Login successful", data={"access": access, "refresh": refresh}, status_code=201, ) @auth_router.post( "/refresh/", summary="Refresh tokens", description="This endpoint refresh tokens by generating new access and refresh tokens for a user", response={201: TokensResponseSchema}, ) async def refresh(request, data: RefreshTokensSchema): token = data.refresh user = await User.objects.aget_or_none(refresh=token) if not user or not Authentication.decode_jwt(token): raise RequestError( err_code=ErrorCode.INVALID_TOKEN, err_msg="Refresh token is invalid or expired", status_code=401, ) access = Authentication.create_access_token( {"user_id": str(user.id), "username": user.username} ) refresh = Authentication.create_refresh_token() user.access = access user.refresh = refresh await user.asave() return CustomResponse.success( message="Tokens refresh successful", data={"access": access, "refresh": refresh}, status_code=201, ) @auth_router.get( "/logout/", summary="Logout a user", description="This endpoint logs a user out from our application", response=ResponseSchema,
auth=AuthUser(),
2
2023-10-10 19:21:49+00:00
8k
casszhao/PruneHall
summac/train_summac.py
[ { "identifier": "select_freer_gpu", "path": "summac/utils_misc.py", "snippet": "def select_freer_gpu():\n freer_gpu = str(get_freer_gpu())\n print(\"Will use GPU: %s\" % (freer_gpu))\n os.environ['CUDA_LAUNCH_BLOCKING'] = \"1\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"+freer_gpu\n ret...
from .utils_misc import select_freer_gpu from torch.utils.data import DataLoader, RandomSampler from .utils_optim import build_optimizer from .benchmark import SummaCBenchmark, load_factcc from .model_summac import SummaCConv, model_map import torch, tqdm, nltk, numpy as np, argparse, json import os, time
6,911
select_freer_gpu() def train(model="mnli", granularity="sentence", nli_labels="e", pre_file="", num_epochs=5, optimizer="adam", train_batch_size=32, learning_rate=0.1, bins="even50", silent=False, norm_histo=False): experiment = "%s_%s_%s_%s" % (model, granularity, bins, nli_labels) if not silent: print("Experiment name: %s" % (experiment)) if len(pre_file) == 0: standard_pre_file = "/home/phillab/data/summac_cache/train_%s_%s.jsonl" % (model, granularity) if os.path.isfile(standard_pre_file): pre_file = standard_pre_file precomputed = len(pre_file) > 0 device = "cpu" if precomputed else "cuda" if model == "multi": models = ["mnli", "anli", "vitc"] elif model == "multi2": models = ["mnli", "vitc", "vitc-only", "vitc-base"] else: models = [model] model = SummaCConv(models=models, granularity=granularity, nli_labels=nli_labels, device=device, bins=bins, norm_histo=norm_histo)
select_freer_gpu() def train(model="mnli", granularity="sentence", nli_labels="e", pre_file="", num_epochs=5, optimizer="adam", train_batch_size=32, learning_rate=0.1, bins="even50", silent=False, norm_histo=False): experiment = "%s_%s_%s_%s" % (model, granularity, bins, nli_labels) if not silent: print("Experiment name: %s" % (experiment)) if len(pre_file) == 0: standard_pre_file = "/home/phillab/data/summac_cache/train_%s_%s.jsonl" % (model, granularity) if os.path.isfile(standard_pre_file): pre_file = standard_pre_file precomputed = len(pre_file) > 0 device = "cpu" if precomputed else "cuda" if model == "multi": models = ["mnli", "anli", "vitc"] elif model == "multi2": models = ["mnli", "vitc", "vitc-only", "vitc-base"] else: models = [model] model = SummaCConv(models=models, granularity=granularity, nli_labels=nli_labels, device=device, bins=bins, norm_histo=norm_histo)
optimizer = build_optimizer(model, learning_rate=learning_rate, optimizer_name=optimizer)
1
2023-10-13 11:29:39+00:00
8k
jtonglet/SEER
preprocess.py
[ { "identifier": "load_file", "path": "utils.py", "snippet": "def load_file(path,encoding='utf-8'):\n #Load json file from path\n if '.jsonl' in path:\n with open(path, 'r', encoding=encoding) as f:\n data = [json.loads(line) for line in f]\n else:\n file = open(path,enc...
from utils import load_file, retrieve_top_k_text_facts_finqa, retrieve_top_k_text_facts_tatqa from generate_dataframe import create_question_dataframe_finqa, create_question_dataframe_tatqa from seer import compute_similarity_matrix
3,908
#First script preprocessing if __name__=='__main__': #Load datasets #FinQA finqa_train = load_file('datasets/finqa/train.json') finqa_dev = load_file('datasets/finqa/dev.json') finqa_test = load_file('datasets/finqa/test.json') #TAT-QA tatqa_train = load_file('datasets/tatqa/train.json') tatqa_test = load_file('datasets/tatqa/dev.json') #New dev split from TAT-QA train ctx_idx_dev = [1, 4, 6, 13, 14, 23, 30, 39, 43, 51, 54, 61, 64, 65, 88, 93, 96, 102, 103, 110, 114, 117, 118, 119, 120, 124, 130, 131, 135, 138, 141, 142, 145, 146, 154, 161, 163, 175, 178, 186, 189, 191, 193, 198, 200, 201, 206, 209, 217, 223, 224, 228, 229, 234, 247, 255, 257, 262, 270, 283, 285, 287, 292, 313, 317, 318, 322, 323, 326, 327, 330, 333, 334, 337, 338, 340, 350, 365, 375, 388, 389, 392, 393, 407, 411, 429, 432, 433, 435, 437, 438, 440, 445, 447, 449, 451, 457, 460, 466, 468, 469, 471, 476, 484, 487, 490, 493, 497, 501, 505, 507, 509, 511, 514, 538, 539, 541, 542, 543, 546, 548, 552, 563, 569, 570, 584, 592, 600, 601, 607, 611, 629, 638, 642, 644, 646, 663, 664, 676, 689, 692, 694, 696, 704, 725, 727, 735, 740, 741, 743, 747, 758, 764, 765, 775, 776, 777, 778, 781, 788, 799, 810, 817, 821, 824, 832, 833, 841, 859, 864, 865, 866, 867, 877, 882, 890, 897, 907, 918, 919, 924, 928, 929, 931, 939, 940, 946, 947, 956, 958, 968, 973, 976, 985, 994, 995, 996, 1000, 1010, 1022, 1025, 1029, 1034, 1039, 1043, 1052, 1059, 1080, 1083, 1086, 1087, 1090, 1093, 1098, 1099, 1103, 1104, 1107, 1116, 1125, 1130, 1133, 1134, 1140, 1149, 1150, 1154, 1158, 1159, 1161, 1167, 1168, 1182, 1186, 1188, 1195, 1197, 1206, 1209, 1213, 1220, 1221, 1232, 1236, 1244, 1245, 1247, 1256, 1265, 1266, 1272, 1276, 1282, 1283, 1287, 1291, 1293, 1309, 1316, 1319, 1326, 1327, 1330, 1333, 1334, 1338, 1341, 1345, 1346, 1350, 1352, 1354, 1355, 1358, 1359, 1360, 1362, 1365] #1. Create dataframes #FinQA finqa_train_df = create_question_dataframe_finqa(finqa_train,preprocess=True,ner_mask=True) finqa_dev_df = create_question_dataframe_finqa(finqa_dev,preprocess=True,ner_mask=True) finqa_test_df = create_question_dataframe_finqa(finqa_test,preprocess=True,ner_mask=True) finqa_train_df.to_csv('data_cache/finqa/metadata/finqa_train_df.csv',index=False) finqa_dev_df.to_csv('data_cache/finqa/metadata/finqa_dev_df.csv',index=False) finqa_test_df.to_csv('data_cache/finqa/metadata/finqa_test_df.csv',index=False) #TAT-QA tatqa_train_df = create_question_dataframe_tatqa(tatqa_train,preprocess=True,ner_mask=True) tatqa_train_df['dev_split'] = tatqa_train_df['context_index'].apply(lambda row : True if row in ctx_idx_dev else False) tatqa_dev_df = tatqa_train_df[tatqa_train_df.dev_split==True].reset_index(drop=True) tatqa_train_df = tatqa_train_df[tatqa_train_df.dev_split==False].reset_index(drop=True) tatqa_test_df = create_question_dataframe_tatqa(tatqa_test,preprocess=True,ner_mask=True) tatqa_train_df.to_csv('data_cache/tatqa/metadata/tatqa_train_df.csv',index=False) tatqa_dev_df.to_csv('data_cache/tatqa/metadata/tatqa_dev_df.csv',index=False) tatqa_test_df.to_csv('data_cache/tatqa/metadata/tatqa_test_df.csv',index=False) #2. Apply text retriever #FinQA
#First script preprocessing if __name__=='__main__': #Load datasets #FinQA finqa_train = load_file('datasets/finqa/train.json') finqa_dev = load_file('datasets/finqa/dev.json') finqa_test = load_file('datasets/finqa/test.json') #TAT-QA tatqa_train = load_file('datasets/tatqa/train.json') tatqa_test = load_file('datasets/tatqa/dev.json') #New dev split from TAT-QA train ctx_idx_dev = [1, 4, 6, 13, 14, 23, 30, 39, 43, 51, 54, 61, 64, 65, 88, 93, 96, 102, 103, 110, 114, 117, 118, 119, 120, 124, 130, 131, 135, 138, 141, 142, 145, 146, 154, 161, 163, 175, 178, 186, 189, 191, 193, 198, 200, 201, 206, 209, 217, 223, 224, 228, 229, 234, 247, 255, 257, 262, 270, 283, 285, 287, 292, 313, 317, 318, 322, 323, 326, 327, 330, 333, 334, 337, 338, 340, 350, 365, 375, 388, 389, 392, 393, 407, 411, 429, 432, 433, 435, 437, 438, 440, 445, 447, 449, 451, 457, 460, 466, 468, 469, 471, 476, 484, 487, 490, 493, 497, 501, 505, 507, 509, 511, 514, 538, 539, 541, 542, 543, 546, 548, 552, 563, 569, 570, 584, 592, 600, 601, 607, 611, 629, 638, 642, 644, 646, 663, 664, 676, 689, 692, 694, 696, 704, 725, 727, 735, 740, 741, 743, 747, 758, 764, 765, 775, 776, 777, 778, 781, 788, 799, 810, 817, 821, 824, 832, 833, 841, 859, 864, 865, 866, 867, 877, 882, 890, 897, 907, 918, 919, 924, 928, 929, 931, 939, 940, 946, 947, 956, 958, 968, 973, 976, 985, 994, 995, 996, 1000, 1010, 1022, 1025, 1029, 1034, 1039, 1043, 1052, 1059, 1080, 1083, 1086, 1087, 1090, 1093, 1098, 1099, 1103, 1104, 1107, 1116, 1125, 1130, 1133, 1134, 1140, 1149, 1150, 1154, 1158, 1159, 1161, 1167, 1168, 1182, 1186, 1188, 1195, 1197, 1206, 1209, 1213, 1220, 1221, 1232, 1236, 1244, 1245, 1247, 1256, 1265, 1266, 1272, 1276, 1282, 1283, 1287, 1291, 1293, 1309, 1316, 1319, 1326, 1327, 1330, 1333, 1334, 1338, 1341, 1345, 1346, 1350, 1352, 1354, 1355, 1358, 1359, 1360, 1362, 1365] #1. Create dataframes #FinQA finqa_train_df = create_question_dataframe_finqa(finqa_train,preprocess=True,ner_mask=True) finqa_dev_df = create_question_dataframe_finqa(finqa_dev,preprocess=True,ner_mask=True) finqa_test_df = create_question_dataframe_finqa(finqa_test,preprocess=True,ner_mask=True) finqa_train_df.to_csv('data_cache/finqa/metadata/finqa_train_df.csv',index=False) finqa_dev_df.to_csv('data_cache/finqa/metadata/finqa_dev_df.csv',index=False) finqa_test_df.to_csv('data_cache/finqa/metadata/finqa_test_df.csv',index=False) #TAT-QA tatqa_train_df = create_question_dataframe_tatqa(tatqa_train,preprocess=True,ner_mask=True) tatqa_train_df['dev_split'] = tatqa_train_df['context_index'].apply(lambda row : True if row in ctx_idx_dev else False) tatqa_dev_df = tatqa_train_df[tatqa_train_df.dev_split==True].reset_index(drop=True) tatqa_train_df = tatqa_train_df[tatqa_train_df.dev_split==False].reset_index(drop=True) tatqa_test_df = create_question_dataframe_tatqa(tatqa_test,preprocess=True,ner_mask=True) tatqa_train_df.to_csv('data_cache/tatqa/metadata/tatqa_train_df.csv',index=False) tatqa_dev_df.to_csv('data_cache/tatqa/metadata/tatqa_dev_df.csv',index=False) tatqa_test_df.to_csv('data_cache/tatqa/metadata/tatqa_test_df.csv',index=False) #2. Apply text retriever #FinQA
retrieved_text_finqa_dev = retrieve_top_k_text_facts_finqa(finqa_test,k=10)
1
2023-10-11 16:49:37+00:00
8k
sergerdn/py-bas-automation
tests/functional/task/test_storage.py
[ { "identifier": "BasActionBrowserProxy", "path": "pybas_automation/bas_actions/browser/proxy/models.py", "snippet": "class BasActionBrowserProxy(BaseModel):\n \"\"\"BasActionBrowserProxy is used to specify a proxy for a browser profile.\"\"\"\n\n model_config = default_model_config\n\n server: ...
import os import tempfile import pytest from typing import List from uuid import UUID, uuid4 from _pytest.monkeypatch import MonkeyPatch from pydantic import DirectoryPath, FilePath from pybas_automation.bas_actions.browser.proxy import BasActionBrowserProxy, BasActionBrowserProxyTypeEnum from pybas_automation.browser_profile import BrowserProfileStorage from pybas_automation.browser_profile.models import BrowserProfile from pybas_automation.task import BasTask, TaskDuplicateError, TaskStorage, TaskStorageModeEnum
4,559
def create_task(profiles_dir: DirectoryPath, fingerprint_str: str, with_proxy: bool = False) -> BasTask: """Creates a temporary directory for a browser profile""" one_profile_dir = DirectoryPath(tempfile.mkdtemp(prefix="profile_", dir=profiles_dir)) browser_profile = BrowserProfile(profile_dir=one_profile_dir) task = BasTask() # Set the fingerprint for the browser profile browser_profile.fingerprint_raw = fingerprint_str browser_profile_storage = BrowserProfileStorage() if with_proxy: proxy = BasActionBrowserProxy( server="127.0.0.1", port=9999, type=BasActionBrowserProxyTypeEnum.HTTP, login="user", password="pass", ) browser_profile.proxy = proxy # Save the browser profile browser_profile_storage.save(browser_profile=browser_profile) task.browser_settings.profile.profile_folder_path = browser_profile.profile_dir task.browser_settings.proxy = browser_profile.proxy return task class TestTaskStorage: def test_fail_storage_dir(self) -> None: """ # Test if initializing TaskStorage with an invalid directory raises a ValueError """ storage_dir = DirectoryPath("some_dir") with pytest.raises(ValueError):
def create_task(profiles_dir: DirectoryPath, fingerprint_str: str, with_proxy: bool = False) -> BasTask: """Creates a temporary directory for a browser profile""" one_profile_dir = DirectoryPath(tempfile.mkdtemp(prefix="profile_", dir=profiles_dir)) browser_profile = BrowserProfile(profile_dir=one_profile_dir) task = BasTask() # Set the fingerprint for the browser profile browser_profile.fingerprint_raw = fingerprint_str browser_profile_storage = BrowserProfileStorage() if with_proxy: proxy = BasActionBrowserProxy( server="127.0.0.1", port=9999, type=BasActionBrowserProxyTypeEnum.HTTP, login="user", password="pass", ) browser_profile.proxy = proxy # Save the browser profile browser_profile_storage.save(browser_profile=browser_profile) task.browser_settings.profile.profile_folder_path = browser_profile.profile_dir task.browser_settings.proxy = browser_profile.proxy return task class TestTaskStorage: def test_fail_storage_dir(self) -> None: """ # Test if initializing TaskStorage with an invalid directory raises a ValueError """ storage_dir = DirectoryPath("some_dir") with pytest.raises(ValueError):
TaskStorage(storage_dir=storage_dir)
6
2023-10-09 08:35:31+00:00
8k
xuefeng-zhu5/SPT
lib/models/spt/head.py
[ { "identifier": "FrozenBatchNorm2d", "path": "lib/models/spt/backbone.py", "snippet": "class FrozenBatchNorm2d(torch.nn.Module):\n \"\"\"\n BatchNorm2d where the batch statistics and the affine parameters are fixed.\n\n Copy-paste from torchvision.misc.ops with added eps before rqsrt,\n with...
import torch.nn as nn import torch import torch.nn.functional as F from lib.models.spt.backbone import FrozenBatchNorm2d from lib.models.spt.repvgg import RepVGGBlock
4,224
self.conv4_br = conv(channel // 4, channel // 8, freeze_bn=freeze_bn) self.conv5_br = nn.Conv2d(channel // 8, 1, kernel_size=1) '''about coordinates and indexs''' with torch.no_grad(): self.indice = torch.arange(0, self.feat_sz).view(-1, 1) * self.stride # generate mesh-grid self.coord_x = self.indice.repeat((self.feat_sz, 1)) \ .view((self.feat_sz * self.feat_sz,)).float().cuda() self.coord_y = self.indice.repeat((1, self.feat_sz)) \ .view((self.feat_sz * self.feat_sz,)).float().cuda() def forward(self, x, return_dist=False, softmax=True): """ Forward pass with input x. """ score_map_tl, score_map_br = self.get_score_map(x) if return_dist: coorx_tl, coory_tl, prob_vec_tl = self.soft_argmax(score_map_tl, return_dist=True, softmax=softmax) coorx_br, coory_br, prob_vec_br = self.soft_argmax(score_map_br, return_dist=True, softmax=softmax) return torch.stack((coorx_tl, coory_tl, coorx_br, coory_br), dim=1) / self.img_sz, prob_vec_tl, prob_vec_br else: coorx_tl, coory_tl = self.soft_argmax(score_map_tl) coorx_br, coory_br = self.soft_argmax(score_map_br) return torch.stack((coorx_tl, coory_tl, coorx_br, coory_br), dim=1) / self.img_sz def get_score_map(self, x): # top-left branch x_tl1 = self.conv1_tl(x) x_tl2 = self.conv2_tl(x_tl1) x_tl3 = self.conv3_tl(x_tl2) x_tl4 = self.conv4_tl(x_tl3) score_map_tl = self.conv5_tl(x_tl4) # bottom-right branch x_br1 = self.conv1_br(x) x_br2 = self.conv2_br(x_br1) x_br3 = self.conv3_br(x_br2) x_br4 = self.conv4_br(x_br3) score_map_br = self.conv5_br(x_br4) return score_map_tl, score_map_br def soft_argmax(self, score_map, return_dist=False, softmax=True): """ get soft-argmax coordinate for a given heatmap """ score_vec = score_map.view((-1, self.feat_sz * self.feat_sz)) # (batch, feat_sz * feat_sz) prob_vec = nn.functional.softmax(score_vec, dim=1) exp_x = torch.sum((self.coord_x * prob_vec), dim=1) exp_y = torch.sum((self.coord_y * prob_vec), dim=1) if return_dist: if softmax: return exp_x, exp_y, prob_vec else: return exp_x, exp_y, score_vec else: return exp_x, exp_y class Corner_Predictor_Lite(nn.Module): """ Corner Predictor module (Lite version)""" def __init__(self, inplanes=64, channel=256, feat_sz=20, stride=16): super(Corner_Predictor_Lite, self).__init__() self.feat_sz = feat_sz self.stride = stride self.img_sz = self.feat_sz * self.stride '''convolution tower for two corners''' self.conv_tower = nn.Sequential(conv(inplanes, channel), conv(channel, channel // 2), conv(channel // 2, channel // 4), conv(channel // 4, channel // 8), nn.Conv2d(channel // 8, 2, kernel_size=3, padding=1)) '''about coordinates and indexs''' with torch.no_grad(): self.indice = (torch.arange(0, self.feat_sz).view(-1, 1) + 0.5) * self.stride # here we can add a 0.5 # generate mesh-grid self.coord_x = self.indice.repeat((self.feat_sz, 1)) \ .view((self.feat_sz * self.feat_sz,)).float().cuda() self.coord_y = self.indice.repeat((1, self.feat_sz)) \ .view((self.feat_sz * self.feat_sz,)).float().cuda() def forward(self, x, return_dist=False, softmax=True): """ Forward pass with input x. """ score_map_tl, score_map_br = self.get_score_map(x) if return_dist: coorx_tl, coory_tl, prob_vec_tl = self.soft_argmax(score_map_tl, return_dist=True, softmax=softmax) coorx_br, coory_br, prob_vec_br = self.soft_argmax(score_map_br, return_dist=True, softmax=softmax) return torch.stack((coorx_tl, coory_tl, coorx_br, coory_br), dim=1) / self.img_sz, prob_vec_tl, prob_vec_br else: coorx_tl, coory_tl = self.soft_argmax(score_map_tl) coorx_br, coory_br = self.soft_argmax(score_map_br) return torch.stack((coorx_tl, coory_tl, coorx_br, coory_br), dim=1) / self.img_sz def get_score_map(self, x): score_map = self.conv_tower(x) # (B,2,H,W) return score_map[:, 0, :, :], score_map[:, 1, :, :] def soft_argmax(self, score_map, return_dist=False, softmax=True): """ get soft-argmax coordinate for a given heatmap """ score_vec = score_map.view((-1, self.feat_sz * self.feat_sz)) # (batch, feat_sz * feat_sz) prob_vec = nn.functional.softmax(score_vec, dim=1) exp_x = torch.sum((self.coord_x * prob_vec), dim=1) exp_y = torch.sum((self.coord_y * prob_vec), dim=1) if return_dist: if softmax: return exp_x, exp_y, prob_vec else: return exp_x, exp_y, score_vec else: return exp_x, exp_y class Corner_Predictor_Lite_Rep(nn.Module): """ Corner Predictor module (Lite version with repvgg style)""" def __init__(self, inplanes=64, channel=256, feat_sz=20, stride=16): super(Corner_Predictor_Lite_Rep, self).__init__() self.feat_sz = feat_sz self.feat_len = feat_sz ** 2 self.stride = stride self.img_sz = self.feat_sz * self.stride '''convolution tower for two corners'''
# import time def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1, freeze_bn=False): if freeze_bn: return nn.Sequential( nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=True), FrozenBatchNorm2d(out_planes), nn.ReLU(inplace=True)) else: return nn.Sequential( nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, bias=True), nn.BatchNorm2d(out_planes), nn.ReLU(inplace=True)) class Corner_Predictor(nn.Module): """ Corner Predictor module""" def __init__(self, inplanes=64, channel=256, feat_sz=20, stride=16, freeze_bn=False): super(Corner_Predictor, self).__init__() self.feat_sz = feat_sz self.stride = stride self.img_sz = self.feat_sz * self.stride '''top-left corner''' self.conv1_tl = conv(inplanes, channel, freeze_bn=freeze_bn) self.conv2_tl = conv(channel, channel // 2, freeze_bn=freeze_bn) self.conv3_tl = conv(channel // 2, channel // 4, freeze_bn=freeze_bn) self.conv4_tl = conv(channel // 4, channel // 8, freeze_bn=freeze_bn) self.conv5_tl = nn.Conv2d(channel // 8, 1, kernel_size=1) '''bottom-right corner''' self.conv1_br = conv(inplanes, channel, freeze_bn=freeze_bn) self.conv2_br = conv(channel, channel // 2, freeze_bn=freeze_bn) self.conv3_br = conv(channel // 2, channel // 4, freeze_bn=freeze_bn) self.conv4_br = conv(channel // 4, channel // 8, freeze_bn=freeze_bn) self.conv5_br = nn.Conv2d(channel // 8, 1, kernel_size=1) '''about coordinates and indexs''' with torch.no_grad(): self.indice = torch.arange(0, self.feat_sz).view(-1, 1) * self.stride # generate mesh-grid self.coord_x = self.indice.repeat((self.feat_sz, 1)) \ .view((self.feat_sz * self.feat_sz,)).float().cuda() self.coord_y = self.indice.repeat((1, self.feat_sz)) \ .view((self.feat_sz * self.feat_sz,)).float().cuda() def forward(self, x, return_dist=False, softmax=True): """ Forward pass with input x. """ score_map_tl, score_map_br = self.get_score_map(x) if return_dist: coorx_tl, coory_tl, prob_vec_tl = self.soft_argmax(score_map_tl, return_dist=True, softmax=softmax) coorx_br, coory_br, prob_vec_br = self.soft_argmax(score_map_br, return_dist=True, softmax=softmax) return torch.stack((coorx_tl, coory_tl, coorx_br, coory_br), dim=1) / self.img_sz, prob_vec_tl, prob_vec_br else: coorx_tl, coory_tl = self.soft_argmax(score_map_tl) coorx_br, coory_br = self.soft_argmax(score_map_br) return torch.stack((coorx_tl, coory_tl, coorx_br, coory_br), dim=1) / self.img_sz def get_score_map(self, x): # top-left branch x_tl1 = self.conv1_tl(x) x_tl2 = self.conv2_tl(x_tl1) x_tl3 = self.conv3_tl(x_tl2) x_tl4 = self.conv4_tl(x_tl3) score_map_tl = self.conv5_tl(x_tl4) # bottom-right branch x_br1 = self.conv1_br(x) x_br2 = self.conv2_br(x_br1) x_br3 = self.conv3_br(x_br2) x_br4 = self.conv4_br(x_br3) score_map_br = self.conv5_br(x_br4) return score_map_tl, score_map_br def soft_argmax(self, score_map, return_dist=False, softmax=True): """ get soft-argmax coordinate for a given heatmap """ score_vec = score_map.view((-1, self.feat_sz * self.feat_sz)) # (batch, feat_sz * feat_sz) prob_vec = nn.functional.softmax(score_vec, dim=1) exp_x = torch.sum((self.coord_x * prob_vec), dim=1) exp_y = torch.sum((self.coord_y * prob_vec), dim=1) if return_dist: if softmax: return exp_x, exp_y, prob_vec else: return exp_x, exp_y, score_vec else: return exp_x, exp_y class Corner_Predictor_Lite(nn.Module): """ Corner Predictor module (Lite version)""" def __init__(self, inplanes=64, channel=256, feat_sz=20, stride=16): super(Corner_Predictor_Lite, self).__init__() self.feat_sz = feat_sz self.stride = stride self.img_sz = self.feat_sz * self.stride '''convolution tower for two corners''' self.conv_tower = nn.Sequential(conv(inplanes, channel), conv(channel, channel // 2), conv(channel // 2, channel // 4), conv(channel // 4, channel // 8), nn.Conv2d(channel // 8, 2, kernel_size=3, padding=1)) '''about coordinates and indexs''' with torch.no_grad(): self.indice = (torch.arange(0, self.feat_sz).view(-1, 1) + 0.5) * self.stride # here we can add a 0.5 # generate mesh-grid self.coord_x = self.indice.repeat((self.feat_sz, 1)) \ .view((self.feat_sz * self.feat_sz,)).float().cuda() self.coord_y = self.indice.repeat((1, self.feat_sz)) \ .view((self.feat_sz * self.feat_sz,)).float().cuda() def forward(self, x, return_dist=False, softmax=True): """ Forward pass with input x. """ score_map_tl, score_map_br = self.get_score_map(x) if return_dist: coorx_tl, coory_tl, prob_vec_tl = self.soft_argmax(score_map_tl, return_dist=True, softmax=softmax) coorx_br, coory_br, prob_vec_br = self.soft_argmax(score_map_br, return_dist=True, softmax=softmax) return torch.stack((coorx_tl, coory_tl, coorx_br, coory_br), dim=1) / self.img_sz, prob_vec_tl, prob_vec_br else: coorx_tl, coory_tl = self.soft_argmax(score_map_tl) coorx_br, coory_br = self.soft_argmax(score_map_br) return torch.stack((coorx_tl, coory_tl, coorx_br, coory_br), dim=1) / self.img_sz def get_score_map(self, x): score_map = self.conv_tower(x) # (B,2,H,W) return score_map[:, 0, :, :], score_map[:, 1, :, :] def soft_argmax(self, score_map, return_dist=False, softmax=True): """ get soft-argmax coordinate for a given heatmap """ score_vec = score_map.view((-1, self.feat_sz * self.feat_sz)) # (batch, feat_sz * feat_sz) prob_vec = nn.functional.softmax(score_vec, dim=1) exp_x = torch.sum((self.coord_x * prob_vec), dim=1) exp_y = torch.sum((self.coord_y * prob_vec), dim=1) if return_dist: if softmax: return exp_x, exp_y, prob_vec else: return exp_x, exp_y, score_vec else: return exp_x, exp_y class Corner_Predictor_Lite_Rep(nn.Module): """ Corner Predictor module (Lite version with repvgg style)""" def __init__(self, inplanes=64, channel=256, feat_sz=20, stride=16): super(Corner_Predictor_Lite_Rep, self).__init__() self.feat_sz = feat_sz self.feat_len = feat_sz ** 2 self.stride = stride self.img_sz = self.feat_sz * self.stride '''convolution tower for two corners'''
self.conv_tower = nn.Sequential(RepVGGBlock(inplanes, channel, kernel_size=3, padding=1),
1
2023-10-07 22:25:52+00:00
8k
cumulo-autumn/StreamDiffusion
src/streamdiffusion/acceleration/tensorrt/utilities.py
[ { "identifier": "CLIP", "path": "src/streamdiffusion/acceleration/tensorrt/models.py", "snippet": "class CLIP(BaseModel):\n def __init__(self, device, max_batch_size, embedding_dim, min_batch_size=1):\n super(CLIP, self).__init__(\n device=device,\n max_batch_size=max_bat...
import gc import numpy as np import onnx import onnx_graphsurgeon as gs import tensorrt as trt import torch from collections import OrderedDict from typing import * from cuda import cudart from PIL import Image from polygraphy import cuda from polygraphy.backend.common import bytes_from_path from polygraphy.backend.trt import ( CreateConfig, Profile, engine_from_bytes, engine_from_network, network_from_onnx_path, save_engine, ) from polygraphy.backend.trt import util as trt_util from .models import CLIP, VAE, BaseModel, UNet, VAEEncoder
6,235
for idx in range(trt_util.get_bindings_per_profile(self.engine)): binding = self.engine[idx] if shape_dict and binding in shape_dict: shape = shape_dict[binding] else: shape = self.engine.get_binding_shape(binding) dtype = trt.nptype(self.engine.get_binding_dtype(binding)) if self.engine.binding_is_input(binding): self.context.set_binding_shape(idx, shape) tensor = torch.empty(tuple(shape), dtype=numpy_to_torch_dtype_dict[dtype]).to(device=device) self.tensors[binding] = tensor def infer(self, feed_dict, stream, use_cuda_graph=False): for name, buf in feed_dict.items(): self.tensors[name].copy_(buf) for name, tensor in self.tensors.items(): self.context.set_tensor_address(name, tensor.data_ptr()) if use_cuda_graph: if self.cuda_graph_instance is not None: CUASSERT(cudart.cudaGraphLaunch(self.cuda_graph_instance, stream.ptr)) CUASSERT(cudart.cudaStreamSynchronize(stream.ptr)) else: # do inference before CUDA graph capture noerror = self.context.execute_async_v3(stream.ptr) if not noerror: raise ValueError("ERROR: inference failed.") # capture cuda graph CUASSERT( cudart.cudaStreamBeginCapture(stream.ptr, cudart.cudaStreamCaptureMode.cudaStreamCaptureModeGlobal) ) self.context.execute_async_v3(stream.ptr) self.graph = CUASSERT(cudart.cudaStreamEndCapture(stream.ptr)) self.cuda_graph_instance = CUASSERT(cudart.cudaGraphInstantiate(self.graph, 0)) else: noerror = self.context.execute_async_v3(stream.ptr) if not noerror: raise ValueError("ERROR: inference failed.") return self.tensors def decode_images(images: torch.Tensor): images = ( ((images + 1) * 255 / 2).clamp(0, 255).detach().permute(0, 2, 3, 1).round().type(torch.uint8).cpu().numpy() ) return [Image.fromarray(x) for x in images] def preprocess_image(image: Image.Image): w, h = image.size w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32 image = image.resize((w, h)) init_image = np.array(image).astype(np.float32) / 255.0 init_image = init_image[None].transpose(0, 3, 1, 2) init_image = torch.from_numpy(init_image).contiguous() return 2.0 * init_image - 1.0 def prepare_mask_and_masked_image(image: Image.Image, mask: Image.Image): if isinstance(image, Image.Image): image = np.array(image.convert("RGB")) image = image[None].transpose(0, 3, 1, 2) image = torch.from_numpy(image).to(dtype=torch.float32).contiguous() / 127.5 - 1.0 if isinstance(mask, Image.Image): mask = np.array(mask.convert("L")) mask = mask.astype(np.float32) / 255.0 mask = mask[None, None] mask[mask < 0.5] = 0 mask[mask >= 0.5] = 1 mask = torch.from_numpy(mask).to(dtype=torch.float32).contiguous() masked_image = image * (mask < 0.5) return mask, masked_image def create_models( model_id: str, use_auth_token: Optional[str], device: Union[str, torch.device], max_batch_size: int, unet_in_channels: int = 4, embedding_dim: int = 768, ): models = { "clip": CLIP( hf_token=use_auth_token, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim, ), "unet": UNet( hf_token=use_auth_token, fp16=True, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim, unet_dim=unet_in_channels, ), "vae": VAE( hf_token=use_auth_token, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim, ), "vae_encoder": VAEEncoder( hf_token=use_auth_token, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim, ), } return models def build_engine( engine_path: str, onnx_opt_path: str,
#! fork: https://github.com/NVIDIA/TensorRT/blob/main/demo/Diffusion/utilities.py # # Copyright 2022 The HuggingFace Inc. team. # SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # 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. # TRT_LOGGER = trt.Logger(trt.Logger.ERROR) # Map of numpy dtype -> torch dtype numpy_to_torch_dtype_dict = { np.uint8: torch.uint8, np.int8: torch.int8, np.int16: torch.int16, np.int32: torch.int32, np.int64: torch.int64, np.float16: torch.float16, np.float32: torch.float32, np.float64: torch.float64, np.complex64: torch.complex64, np.complex128: torch.complex128, } if np.version.full_version >= "1.24.0": numpy_to_torch_dtype_dict[np.bool_] = torch.bool else: numpy_to_torch_dtype_dict[np.bool] = torch.bool # Map of torch dtype -> numpy dtype torch_to_numpy_dtype_dict = {value: key for (key, value) in numpy_to_torch_dtype_dict.items()} def CUASSERT(cuda_ret): err = cuda_ret[0] if err != cudart.cudaError_t.cudaSuccess: raise RuntimeError( f"CUDA ERROR: {err}, error code reference: https://nvidia.github.io/cuda-python/module/cudart.html#cuda.cudart.cudaError_t" ) if len(cuda_ret) > 1: return cuda_ret[1] return None class Engine: def __init__( self, engine_path, ): self.engine_path = engine_path self.engine = None self.context = None self.buffers = OrderedDict() self.tensors = OrderedDict() self.cuda_graph_instance = None # cuda graph def __del__(self): [buf.free() for buf in self.buffers.values() if isinstance(buf, cuda.DeviceArray)] del self.engine del self.context del self.buffers del self.tensors def refit(self, onnx_path, onnx_refit_path): def convert_int64(arr): # TODO: smarter conversion if len(arr.shape) == 0: return np.int32(arr) return arr def add_to_map(refit_dict, name, values): if name in refit_dict: assert refit_dict[name] is None if values.dtype == np.int64: values = convert_int64(values) refit_dict[name] = values print(f"Refitting TensorRT engine with {onnx_refit_path} weights") refit_nodes = gs.import_onnx(onnx.load(onnx_refit_path)).toposort().nodes # Construct mapping from weight names in refit model -> original model name_map = {} for n, node in enumerate(gs.import_onnx(onnx.load(onnx_path)).toposort().nodes): refit_node = refit_nodes[n] assert node.op == refit_node.op # Constant nodes in ONNX do not have inputs but have a constant output if node.op == "Constant": name_map[refit_node.outputs[0].name] = node.outputs[0].name # Handle scale and bias weights elif node.op == "Conv": if node.inputs[1].__class__ == gs.Constant: name_map[refit_node.name + "_TRTKERNEL"] = node.name + "_TRTKERNEL" if node.inputs[2].__class__ == gs.Constant: name_map[refit_node.name + "_TRTBIAS"] = node.name + "_TRTBIAS" # For all other nodes: find node inputs that are initializers (gs.Constant) else: for i, inp in enumerate(node.inputs): if inp.__class__ == gs.Constant: name_map[refit_node.inputs[i].name] = inp.name def map_name(name): if name in name_map: return name_map[name] return name # Construct refit dictionary refit_dict = {} refitter = trt.Refitter(self.engine, TRT_LOGGER) all_weights = refitter.get_all() for layer_name, role in zip(all_weights[0], all_weights[1]): # for speciailized roles, use a unique name in the map: if role == trt.WeightsRole.KERNEL: name = layer_name + "_TRTKERNEL" elif role == trt.WeightsRole.BIAS: name = layer_name + "_TRTBIAS" else: name = layer_name assert name not in refit_dict, "Found duplicate layer: " + name refit_dict[name] = None for n in refit_nodes: # Constant nodes in ONNX do not have inputs but have a constant output if n.op == "Constant": name = map_name(n.outputs[0].name) print(f"Add Constant {name}\n") add_to_map(refit_dict, name, n.outputs[0].values) # Handle scale and bias weights elif n.op == "Conv": if n.inputs[1].__class__ == gs.Constant: name = map_name(n.name + "_TRTKERNEL") add_to_map(refit_dict, name, n.inputs[1].values) if n.inputs[2].__class__ == gs.Constant: name = map_name(n.name + "_TRTBIAS") add_to_map(refit_dict, name, n.inputs[2].values) # For all other nodes: find node inputs that are initializers (AKA gs.Constant) else: for inp in n.inputs: name = map_name(inp.name) if inp.__class__ == gs.Constant: add_to_map(refit_dict, name, inp.values) for layer_name, weights_role in zip(all_weights[0], all_weights[1]): if weights_role == trt.WeightsRole.KERNEL: custom_name = layer_name + "_TRTKERNEL" elif weights_role == trt.WeightsRole.BIAS: custom_name = layer_name + "_TRTBIAS" else: custom_name = layer_name # Skip refitting Trilu for now; scalar weights of type int64 value 1 - for clip model if layer_name.startswith("onnx::Trilu"): continue if refit_dict[custom_name] is not None: refitter.set_weights(layer_name, weights_role, refit_dict[custom_name]) else: print(f"[W] No refit weights for layer: {layer_name}") if not refitter.refit_cuda_engine(): print("Failed to refit!") exit(0) def build( self, onnx_path, fp16, input_profile=None, enable_refit=False, enable_all_tactics=False, timing_cache=None, workspace_size=0, ): print(f"Building TensorRT engine for {onnx_path}: {self.engine_path}") p = Profile() if input_profile: for name, dims in input_profile.items(): assert len(dims) == 3 p.add(name, min=dims[0], opt=dims[1], max=dims[2]) config_kwargs = {} if workspace_size > 0: config_kwargs["memory_pool_limits"] = {trt.MemoryPoolType.WORKSPACE: workspace_size} if not enable_all_tactics: config_kwargs["tactic_sources"] = [] engine = engine_from_network( network_from_onnx_path(onnx_path, flags=[trt.OnnxParserFlag.NATIVE_INSTANCENORM]), config=CreateConfig( fp16=fp16, refittable=enable_refit, profiles=[p], load_timing_cache=timing_cache, **config_kwargs ), save_timing_cache=timing_cache, ) save_engine(engine, path=self.engine_path) def load(self): print(f"Loading TensorRT engine: {self.engine_path}") self.engine = engine_from_bytes(bytes_from_path(self.engine_path)) def activate(self, reuse_device_memory=None): if reuse_device_memory: self.context = self.engine.create_execution_context_without_device_memory() self.context.device_memory = reuse_device_memory else: self.context = self.engine.create_execution_context() def allocate_buffers(self, shape_dict=None, device="cuda"): for idx in range(trt_util.get_bindings_per_profile(self.engine)): binding = self.engine[idx] if shape_dict and binding in shape_dict: shape = shape_dict[binding] else: shape = self.engine.get_binding_shape(binding) dtype = trt.nptype(self.engine.get_binding_dtype(binding)) if self.engine.binding_is_input(binding): self.context.set_binding_shape(idx, shape) tensor = torch.empty(tuple(shape), dtype=numpy_to_torch_dtype_dict[dtype]).to(device=device) self.tensors[binding] = tensor def infer(self, feed_dict, stream, use_cuda_graph=False): for name, buf in feed_dict.items(): self.tensors[name].copy_(buf) for name, tensor in self.tensors.items(): self.context.set_tensor_address(name, tensor.data_ptr()) if use_cuda_graph: if self.cuda_graph_instance is not None: CUASSERT(cudart.cudaGraphLaunch(self.cuda_graph_instance, stream.ptr)) CUASSERT(cudart.cudaStreamSynchronize(stream.ptr)) else: # do inference before CUDA graph capture noerror = self.context.execute_async_v3(stream.ptr) if not noerror: raise ValueError("ERROR: inference failed.") # capture cuda graph CUASSERT( cudart.cudaStreamBeginCapture(stream.ptr, cudart.cudaStreamCaptureMode.cudaStreamCaptureModeGlobal) ) self.context.execute_async_v3(stream.ptr) self.graph = CUASSERT(cudart.cudaStreamEndCapture(stream.ptr)) self.cuda_graph_instance = CUASSERT(cudart.cudaGraphInstantiate(self.graph, 0)) else: noerror = self.context.execute_async_v3(stream.ptr) if not noerror: raise ValueError("ERROR: inference failed.") return self.tensors def decode_images(images: torch.Tensor): images = ( ((images + 1) * 255 / 2).clamp(0, 255).detach().permute(0, 2, 3, 1).round().type(torch.uint8).cpu().numpy() ) return [Image.fromarray(x) for x in images] def preprocess_image(image: Image.Image): w, h = image.size w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32 image = image.resize((w, h)) init_image = np.array(image).astype(np.float32) / 255.0 init_image = init_image[None].transpose(0, 3, 1, 2) init_image = torch.from_numpy(init_image).contiguous() return 2.0 * init_image - 1.0 def prepare_mask_and_masked_image(image: Image.Image, mask: Image.Image): if isinstance(image, Image.Image): image = np.array(image.convert("RGB")) image = image[None].transpose(0, 3, 1, 2) image = torch.from_numpy(image).to(dtype=torch.float32).contiguous() / 127.5 - 1.0 if isinstance(mask, Image.Image): mask = np.array(mask.convert("L")) mask = mask.astype(np.float32) / 255.0 mask = mask[None, None] mask[mask < 0.5] = 0 mask[mask >= 0.5] = 1 mask = torch.from_numpy(mask).to(dtype=torch.float32).contiguous() masked_image = image * (mask < 0.5) return mask, masked_image def create_models( model_id: str, use_auth_token: Optional[str], device: Union[str, torch.device], max_batch_size: int, unet_in_channels: int = 4, embedding_dim: int = 768, ): models = { "clip": CLIP( hf_token=use_auth_token, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim, ), "unet": UNet( hf_token=use_auth_token, fp16=True, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim, unet_dim=unet_in_channels, ), "vae": VAE( hf_token=use_auth_token, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim, ), "vae_encoder": VAEEncoder( hf_token=use_auth_token, device=device, max_batch_size=max_batch_size, embedding_dim=embedding_dim, ), } return models def build_engine( engine_path: str, onnx_opt_path: str,
model_data: BaseModel,
2
2023-11-28 13:40:30+00:00
8k
state-spaces/mamba
mamba_ssm/models/mixer_seq_simple.py
[ { "identifier": "MambaConfig", "path": "mamba_ssm/models/config_mamba.py", "snippet": "class MambaConfig:\n\n d_model: int = 2560\n n_layer: int = 64\n vocab_size: int = 50277\n ssm_cfg: dict = field(default_factory=dict)\n rms_norm: bool = True\n residual_in_fp32: bool = True\n fus...
import math import json import os import torch import torch.nn as nn from functools import partial from collections import namedtuple from mamba_ssm.models.config_mamba import MambaConfig from mamba_ssm.modules.mamba_simple import Mamba, Block from mamba_ssm.utils.generation import GenerationMixin from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn
4,349
# Copyright (c) 2023, Albert Gu, Tri Dao. try: except ImportError: RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None def create_block( d_model, ssm_cfg=None, norm_epsilon=1e-5, rms_norm=False, residual_in_fp32=False, fused_add_norm=False, layer_idx=None, device=None, dtype=None, ): if ssm_cfg is None: ssm_cfg = {} factory_kwargs = {"device": device, "dtype": dtype}
# Copyright (c) 2023, Albert Gu, Tri Dao. try: except ImportError: RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None def create_block( d_model, ssm_cfg=None, norm_epsilon=1e-5, rms_norm=False, residual_in_fp32=False, fused_add_norm=False, layer_idx=None, device=None, dtype=None, ): if ssm_cfg is None: ssm_cfg = {} factory_kwargs = {"device": device, "dtype": dtype}
mixer_cls = partial(Mamba, layer_idx=layer_idx, **ssm_cfg, **factory_kwargs)
1
2023-12-01 01:17:39+00:00
8k
ml-explore/mlx-examples
whisper/whisper/transcribe.py
[ { "identifier": "FRAMES_PER_SECOND", "path": "whisper/whisper/audio.py", "snippet": "FRAMES_PER_SECOND = SAMPLE_RATE // HOP_LENGTH # 10ms per audio frame" }, { "identifier": "HOP_LENGTH", "path": "whisper/whisper/audio.py", "snippet": "HOP_LENGTH = 160" }, { "identifier": "N_FRA...
import sys import warnings import mlx.core as mx import numpy as np import tqdm from typing import List, Optional, Tuple, Union from .audio import ( FRAMES_PER_SECOND, HOP_LENGTH, N_FRAMES, N_SAMPLES, SAMPLE_RATE, log_mel_spectrogram, pad_or_trim, ) from .decoding import DecodingOptions, DecodingResult from .load_models import load_model from .timing import add_word_timestamps from .tokenizer import LANGUAGES, get_tokenizer
5,271
minutes = milliseconds // 60_000 milliseconds -= minutes * 60_000 seconds = milliseconds // 1_000 milliseconds -= seconds * 1_000 hours_marker = f"{hours:02d}:" if hours > 0 else "" return f"{hours_marker}{minutes:02d}:{seconds:02d}.{milliseconds:03d}" def _get_end(segments: List[dict]) -> Optional[float]: return next( (w["end"] for s in reversed(segments) for w in reversed(s["words"])), segments[-1]["end"] if segments else None, ) class ModelHolder: model = None model_path = None @classmethod def get_model(cls, model_path: str, dtype: mx.Dtype): if cls.model is None or model_path != cls.model_path: cls.model = load_model(model_path, dtype=dtype) cls.model_path = model_path return cls.model def transcribe( audio: Union[str, np.ndarray, mx.array], *, path_or_hf_repo: str = "mlx-community/whisper-tiny", verbose: Optional[bool] = None, temperature: Union[float, Tuple[float, ...]] = (0.0, 0.2, 0.4, 0.6, 0.8, 1.0), compression_ratio_threshold: Optional[float] = 2.4, logprob_threshold: Optional[float] = -1.0, no_speech_threshold: Optional[float] = 0.6, condition_on_previous_text: bool = True, initial_prompt: Optional[str] = None, word_timestamps: bool = False, prepend_punctuations: str = "\"'“¿([{-", append_punctuations: str = "\"'.。,,!!??::”)]}、", clip_timestamps: Union[str, List[float]] = "0", hallucination_silence_threshold: Optional[float] = None, **decode_options, ): """ Transcribe an audio file using Whisper Parameters ---------- audio: Union[str, np.ndarray, mx.array] The path to the audio file to open, or the audio waveform path_or_hf_repo: str The localpath to the Whisper model or HF Hub repo with the MLX converted weights. verbose: bool Whether to display the text being decoded to the console. If True, displays all the details, If False, displays minimal details. If None, does not display anything temperature: Union[float, Tuple[float, ...]] Temperature for sampling. It can be a tuple of temperatures, which will be successively used upon failures according to either `compression_ratio_threshold` or `logprob_threshold`. compression_ratio_threshold: float If the gzip compression ratio is above this value, treat as failed logprob_threshold: float If the average log probability over sampled tokens is below this value, treat as failed no_speech_threshold: float If the no_speech probability is higher than this value AND the average log probability over sampled tokens is below `logprob_threshold`, consider the segment as silent condition_on_previous_text: bool if True, the previous output of the model is provided as a prompt for the next window; disabling may make the text inconsistent across windows, but the model becomes less prone to getting stuck in a failure loop, such as repetition looping or timestamps going out of sync. word_timestamps: bool Extract word-level timestamps using the cross-attention pattern and dynamic time warping, and include the timestamps for each word in each segment. prepend_punctuations: str If word_timestamps is True, merge these punctuation symbols with the next word append_punctuations: str If word_timestamps is True, merge these punctuation symbols with the previous word initial_prompt: Optional[str] Optional text to provide as a prompt for the first window. This can be used to provide, or "prompt-engineer" a context for transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those word correctly. decode_options: dict Keyword arguments to construct `DecodingOptions` instances clip_timestamps: Union[str, List[float]] Comma-separated list start,end,start,end,... timestamps (in seconds) of clips to process. The last end timestamp defaults to the end of the file. hallucination_silence_threshold: Optional[float] When word_timestamps is True, skip silent periods longer than this threshold (in seconds) when a possible hallucination is detected Returns ------- A dictionary containing the resulting text ("text") and segment-level details ("segments"), and the spoken language ("language"), which is detected when `decode_options["language"]` is None. """ dtype = mx.float16 if decode_options.get("fp16", True) else mx.float32 model = ModelHolder.get_model(path_or_hf_repo, dtype) # Pad 30-seconds of silence to the input audio, for slicing mel = log_mel_spectrogram(audio, n_mels=model.dims.n_mels, padding=N_SAMPLES) content_frames = mel.shape[-2] - N_FRAMES
# Copyright © 2023 Apple Inc. def _format_timestamp(seconds: float): assert seconds >= 0, "non-negative timestamp expected" milliseconds = round(seconds * 1000.0) hours = milliseconds // 3_600_000 milliseconds -= hours * 3_600_000 minutes = milliseconds // 60_000 milliseconds -= minutes * 60_000 seconds = milliseconds // 1_000 milliseconds -= seconds * 1_000 hours_marker = f"{hours:02d}:" if hours > 0 else "" return f"{hours_marker}{minutes:02d}:{seconds:02d}.{milliseconds:03d}" def _get_end(segments: List[dict]) -> Optional[float]: return next( (w["end"] for s in reversed(segments) for w in reversed(s["words"])), segments[-1]["end"] if segments else None, ) class ModelHolder: model = None model_path = None @classmethod def get_model(cls, model_path: str, dtype: mx.Dtype): if cls.model is None or model_path != cls.model_path: cls.model = load_model(model_path, dtype=dtype) cls.model_path = model_path return cls.model def transcribe( audio: Union[str, np.ndarray, mx.array], *, path_or_hf_repo: str = "mlx-community/whisper-tiny", verbose: Optional[bool] = None, temperature: Union[float, Tuple[float, ...]] = (0.0, 0.2, 0.4, 0.6, 0.8, 1.0), compression_ratio_threshold: Optional[float] = 2.4, logprob_threshold: Optional[float] = -1.0, no_speech_threshold: Optional[float] = 0.6, condition_on_previous_text: bool = True, initial_prompt: Optional[str] = None, word_timestamps: bool = False, prepend_punctuations: str = "\"'“¿([{-", append_punctuations: str = "\"'.。,,!!??::”)]}、", clip_timestamps: Union[str, List[float]] = "0", hallucination_silence_threshold: Optional[float] = None, **decode_options, ): """ Transcribe an audio file using Whisper Parameters ---------- audio: Union[str, np.ndarray, mx.array] The path to the audio file to open, or the audio waveform path_or_hf_repo: str The localpath to the Whisper model or HF Hub repo with the MLX converted weights. verbose: bool Whether to display the text being decoded to the console. If True, displays all the details, If False, displays minimal details. If None, does not display anything temperature: Union[float, Tuple[float, ...]] Temperature for sampling. It can be a tuple of temperatures, which will be successively used upon failures according to either `compression_ratio_threshold` or `logprob_threshold`. compression_ratio_threshold: float If the gzip compression ratio is above this value, treat as failed logprob_threshold: float If the average log probability over sampled tokens is below this value, treat as failed no_speech_threshold: float If the no_speech probability is higher than this value AND the average log probability over sampled tokens is below `logprob_threshold`, consider the segment as silent condition_on_previous_text: bool if True, the previous output of the model is provided as a prompt for the next window; disabling may make the text inconsistent across windows, but the model becomes less prone to getting stuck in a failure loop, such as repetition looping or timestamps going out of sync. word_timestamps: bool Extract word-level timestamps using the cross-attention pattern and dynamic time warping, and include the timestamps for each word in each segment. prepend_punctuations: str If word_timestamps is True, merge these punctuation symbols with the next word append_punctuations: str If word_timestamps is True, merge these punctuation symbols with the previous word initial_prompt: Optional[str] Optional text to provide as a prompt for the first window. This can be used to provide, or "prompt-engineer" a context for transcription, e.g. custom vocabularies or proper nouns to make it more likely to predict those word correctly. decode_options: dict Keyword arguments to construct `DecodingOptions` instances clip_timestamps: Union[str, List[float]] Comma-separated list start,end,start,end,... timestamps (in seconds) of clips to process. The last end timestamp defaults to the end of the file. hallucination_silence_threshold: Optional[float] When word_timestamps is True, skip silent periods longer than this threshold (in seconds) when a possible hallucination is detected Returns ------- A dictionary containing the resulting text ("text") and segment-level details ("segments"), and the spoken language ("language"), which is detected when `decode_options["language"]` is None. """ dtype = mx.float16 if decode_options.get("fp16", True) else mx.float32 model = ModelHolder.get_model(path_or_hf_repo, dtype) # Pad 30-seconds of silence to the input audio, for slicing mel = log_mel_spectrogram(audio, n_mels=model.dims.n_mels, padding=N_SAMPLES) content_frames = mel.shape[-2] - N_FRAMES
content_duration = float(content_frames * HOP_LENGTH / SAMPLE_RATE)
4
2023-11-28 23:37:49+00:00
8k
unslothai/unsloth
unsloth/models/loader.py
[ { "identifier": "FastLlamaModel", "path": "unsloth/models/llama.py", "snippet": "def original_apply_qkv(self, X):\ndef original_apply_o(self, X):\ndef LlamaAttention_fast_forward_inference(\n self,\n hidden_states: torch.Tensor,\n past_key_value: Optional[Tuple[torch.Tensor]],\n position_id...
from .llama import FastLlamaModel, logger from .mistral import FastMistralModel from transformers import AutoConfig from transformers import __version__ as transformers_version from peft import PeftConfig, PeftModel from .mapper import INT_TO_FLOAT_MAPPER, FLOAT_TO_INT_MAPPER
3,796
# Copyright 2023-present Daniel Han-Chen & the Unsloth 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. # https://github.com/huggingface/transformers/pull/26037 allows 4 bit loading! major, minor = transformers_version.split(".")[:2] major, minor = int(major), int(minor) SUPPORTS_FOURBIT = (major > 4) or (major == 4 and minor >= 37) del major, minor def _get_model_name(model_name, load_in_4bit = True): if not SUPPORTS_FOURBIT and model_name in INT_TO_FLOAT_MAPPER: model_name = INT_TO_FLOAT_MAPPER[model_name] logger.warning_once( f"Unsloth: Your transformers version of {transformers_version} does not support native "\ f"4bit loading.\nThe minimum required version is 4.37.\n"\ f'Try `pip install "git+https://github.com/huggingface/transformers.git"`\n'\ f"to obtain the latest transformers build, then restart this session.\n"\ f"For now, we shall load `{model_name}` instead (still 4bit, just slower downloading)." ) elif not load_in_4bit and model_name in INT_TO_FLOAT_MAPPER: new_model_name = INT_TO_FLOAT_MAPPER[model_name] logger.warning_once( f"Unsloth: You passed in `{model_name}` which is a 4bit model, yet you set\n"\ f"`load_in_4bit = False`. We shall load `{new_model_name}` instead." ) model_name = new_model_name
# Copyright 2023-present Daniel Han-Chen & the Unsloth 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. # https://github.com/huggingface/transformers/pull/26037 allows 4 bit loading! major, minor = transformers_version.split(".")[:2] major, minor = int(major), int(minor) SUPPORTS_FOURBIT = (major > 4) or (major == 4 and minor >= 37) del major, minor def _get_model_name(model_name, load_in_4bit = True): if not SUPPORTS_FOURBIT and model_name in INT_TO_FLOAT_MAPPER: model_name = INT_TO_FLOAT_MAPPER[model_name] logger.warning_once( f"Unsloth: Your transformers version of {transformers_version} does not support native "\ f"4bit loading.\nThe minimum required version is 4.37.\n"\ f'Try `pip install "git+https://github.com/huggingface/transformers.git"`\n'\ f"to obtain the latest transformers build, then restart this session.\n"\ f"For now, we shall load `{model_name}` instead (still 4bit, just slower downloading)." ) elif not load_in_4bit and model_name in INT_TO_FLOAT_MAPPER: new_model_name = INT_TO_FLOAT_MAPPER[model_name] logger.warning_once( f"Unsloth: You passed in `{model_name}` which is a 4bit model, yet you set\n"\ f"`load_in_4bit = False`. We shall load `{new_model_name}` instead." ) model_name = new_model_name
elif load_in_4bit and SUPPORTS_FOURBIT and model_name in FLOAT_TO_INT_MAPPER:
3
2023-11-29 16:50:09+00:00
8k
prs-eth/Marigold
marigold/marigold_pipeline.py
[ { "identifier": "chw2hwc", "path": "marigold/util/image_util.py", "snippet": "def chw2hwc(chw):\n assert 3 == len(chw.shape)\n if isinstance(chw, torch.Tensor):\n hwc = torch.permute(chw, (1, 2, 0))\n elif isinstance(chw, np.ndarray):\n hwc = np.moveaxis(chw, 0, -1)\n return hw...
from typing import Dict, Union from torch.utils.data import DataLoader, TensorDataset from tqdm.auto import tqdm from PIL import Image from diffusers import ( DiffusionPipeline, DDIMScheduler, UNet2DConditionModel, AutoencoderKL, ) from diffusers.utils import BaseOutput from transformers import CLIPTextModel, CLIPTokenizer from .util.image_util import chw2hwc, colorize_depth_maps, resize_max_res from .util.batchsize import find_batch_size from .util.ensemble import ensemble_depths import torch import numpy as np
3,704
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) Args: unet (`UNet2DConditionModel`): Conditional U-Net to denoise the depth latent, conditioned on image latent. vae (`AutoencoderKL`): Variational Auto-Encoder (VAE) Model to encode and decode images and depth maps to and from latent representations. scheduler (`DDIMScheduler`): A scheduler to be used in combination with `unet` to denoise the encoded image latents. text_encoder (`CLIPTextModel`): Text-encoder, for empty text embedding. tokenizer (`CLIPTokenizer`): CLIP tokenizer. """ rgb_latent_scale_factor = 0.18215 depth_latent_scale_factor = 0.18215 def __init__( self, unet: UNet2DConditionModel, vae: AutoencoderKL, scheduler: DDIMScheduler, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, ): super().__init__() self.register_modules( unet=unet, vae=vae, scheduler=scheduler, text_encoder=text_encoder, tokenizer=tokenizer, ) self.empty_text_embed = None @torch.no_grad() def __call__( self, input_image: Image, denoising_steps: int = 10, ensemble_size: int = 10, processing_res: int = 768, match_input_res: bool = True, batch_size: int = 0, color_map: str = "Spectral", show_progress_bar: bool = True, ensemble_kwargs: Dict = None, ) -> MarigoldDepthOutput: """ Function invoked when calling the pipeline. Args: input_image (`Image`): Input RGB (or gray-scale) image. processing_res (`int`, *optional*, defaults to `768`): Maximum resolution of processing. If set to 0: will not resize at all. match_input_res (`bool`, *optional*, defaults to `True`): Resize depth prediction to match input resolution. Only valid if `limit_input_res` is not None. denoising_steps (`int`, *optional*, defaults to `10`): Number of diffusion denoising steps (DDIM) during inference. ensemble_size (`int`, *optional*, defaults to `10`): Number of predictions to be ensembled. batch_size (`int`, *optional*, defaults to `0`): Inference batch size, no bigger than `num_ensemble`. If set to 0, the script will automatically decide the proper batch size. show_progress_bar (`bool`, *optional*, defaults to `True`): Display a progress bar of diffusion denoising. color_map (`str`, *optional*, defaults to `"Spectral"`): Colormap used to colorize the depth map. ensemble_kwargs (`dict`, *optional*, defaults to `None`): Arguments for detailed ensembling settings. Returns: `MarigoldDepthOutput`: Output class for Marigold monocular depth prediction pipeline, including: - **depth_np** (`np.ndarray`) Predicted depth map, with depth values in the range of [0, 1] - **depth_colored** (`PIL.Image.Image`) Colorized depth map, with the shape of [3, H, W] and values in [0, 1] - **uncertainty** (`None` or `np.ndarray`) Uncalibrated uncertainty(MAD, median absolute deviation) coming from ensembling. None if `ensemble_size = 1` """ device = self.device input_size = input_image.size if not match_input_res: assert ( processing_res is not None ), "Value error: `resize_output_back` is only valid with " assert processing_res >= 0 assert denoising_steps >= 1 assert ensemble_size >= 1 # ----------------- Image Preprocess ----------------- # Resize image if processing_res > 0: input_image = resize_max_res( input_image, max_edge_resolution=processing_res ) # Convert the image to RGB, to 1.remove the alpha channel 2.convert B&W to 3-channel input_image = input_image.convert("RGB") image = np.asarray(input_image) # Normalize rgb values rgb = np.transpose(image, (2, 0, 1)) # [H, W, rgb] -> [rgb, H, W] rgb_norm = rgb / 255.0 rgb_norm = torch.from_numpy(rgb_norm).to(self.dtype) rgb_norm = rgb_norm.to(device) assert rgb_norm.min() >= 0.0 and rgb_norm.max() <= 1.0 # ----------------- Predicting depth ----------------- # Batch repeated input image duplicated_rgb = torch.stack([rgb_norm] * ensemble_size) single_rgb_dataset = TensorDataset(duplicated_rgb) if batch_size > 0: _bs = batch_size else:
# Copyright 2023 Bingxin Ke, ETH Zurich. 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. # -------------------------------------------------------------------------- # If you find this code useful, we kindly ask you to cite our paper in your work. # Please find bibtex at: https://github.com/prs-eth/Marigold#-citation # More information about the method can be found at https://marigoldmonodepth.github.io # -------------------------------------------------------------------------- class MarigoldDepthOutput(BaseOutput): """ Output class for Marigold monocular depth prediction pipeline. Args: depth_np (`np.ndarray`): Predicted depth map, with depth values in the range of [0, 1]. depth_colored (`PIL.Image.Image`): Colorized depth map, with the shape of [3, H, W] and values in [0, 1]. uncertainty (`None` or `np.ndarray`): Uncalibrated uncertainty(MAD, median absolute deviation) coming from ensembling. """ depth_np: np.ndarray depth_colored: Image.Image uncertainty: Union[None, np.ndarray] class MarigoldPipeline(DiffusionPipeline): """ Pipeline for monocular depth estimation using Marigold: https://marigoldmonodepth.github.io. This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) Args: unet (`UNet2DConditionModel`): Conditional U-Net to denoise the depth latent, conditioned on image latent. vae (`AutoencoderKL`): Variational Auto-Encoder (VAE) Model to encode and decode images and depth maps to and from latent representations. scheduler (`DDIMScheduler`): A scheduler to be used in combination with `unet` to denoise the encoded image latents. text_encoder (`CLIPTextModel`): Text-encoder, for empty text embedding. tokenizer (`CLIPTokenizer`): CLIP tokenizer. """ rgb_latent_scale_factor = 0.18215 depth_latent_scale_factor = 0.18215 def __init__( self, unet: UNet2DConditionModel, vae: AutoencoderKL, scheduler: DDIMScheduler, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, ): super().__init__() self.register_modules( unet=unet, vae=vae, scheduler=scheduler, text_encoder=text_encoder, tokenizer=tokenizer, ) self.empty_text_embed = None @torch.no_grad() def __call__( self, input_image: Image, denoising_steps: int = 10, ensemble_size: int = 10, processing_res: int = 768, match_input_res: bool = True, batch_size: int = 0, color_map: str = "Spectral", show_progress_bar: bool = True, ensemble_kwargs: Dict = None, ) -> MarigoldDepthOutput: """ Function invoked when calling the pipeline. Args: input_image (`Image`): Input RGB (or gray-scale) image. processing_res (`int`, *optional*, defaults to `768`): Maximum resolution of processing. If set to 0: will not resize at all. match_input_res (`bool`, *optional*, defaults to `True`): Resize depth prediction to match input resolution. Only valid if `limit_input_res` is not None. denoising_steps (`int`, *optional*, defaults to `10`): Number of diffusion denoising steps (DDIM) during inference. ensemble_size (`int`, *optional*, defaults to `10`): Number of predictions to be ensembled. batch_size (`int`, *optional*, defaults to `0`): Inference batch size, no bigger than `num_ensemble`. If set to 0, the script will automatically decide the proper batch size. show_progress_bar (`bool`, *optional*, defaults to `True`): Display a progress bar of diffusion denoising. color_map (`str`, *optional*, defaults to `"Spectral"`): Colormap used to colorize the depth map. ensemble_kwargs (`dict`, *optional*, defaults to `None`): Arguments for detailed ensembling settings. Returns: `MarigoldDepthOutput`: Output class for Marigold monocular depth prediction pipeline, including: - **depth_np** (`np.ndarray`) Predicted depth map, with depth values in the range of [0, 1] - **depth_colored** (`PIL.Image.Image`) Colorized depth map, with the shape of [3, H, W] and values in [0, 1] - **uncertainty** (`None` or `np.ndarray`) Uncalibrated uncertainty(MAD, median absolute deviation) coming from ensembling. None if `ensemble_size = 1` """ device = self.device input_size = input_image.size if not match_input_res: assert ( processing_res is not None ), "Value error: `resize_output_back` is only valid with " assert processing_res >= 0 assert denoising_steps >= 1 assert ensemble_size >= 1 # ----------------- Image Preprocess ----------------- # Resize image if processing_res > 0: input_image = resize_max_res( input_image, max_edge_resolution=processing_res ) # Convert the image to RGB, to 1.remove the alpha channel 2.convert B&W to 3-channel input_image = input_image.convert("RGB") image = np.asarray(input_image) # Normalize rgb values rgb = np.transpose(image, (2, 0, 1)) # [H, W, rgb] -> [rgb, H, W] rgb_norm = rgb / 255.0 rgb_norm = torch.from_numpy(rgb_norm).to(self.dtype) rgb_norm = rgb_norm.to(device) assert rgb_norm.min() >= 0.0 and rgb_norm.max() <= 1.0 # ----------------- Predicting depth ----------------- # Batch repeated input image duplicated_rgb = torch.stack([rgb_norm] * ensemble_size) single_rgb_dataset = TensorDataset(duplicated_rgb) if batch_size > 0: _bs = batch_size else:
_bs = find_batch_size(
3
2023-11-27 21:25:00+00:00
8k
spla-tam/SplaTAM
utils/eval_helpers.py
[ { "identifier": "relative_transformation", "path": "datasets/gradslam_datasets/geometryutils.py", "snippet": "def relative_transformation(\n trans_01: torch.Tensor, trans_02: torch.Tensor, orthogonal_rotations: bool = False\n) -> torch.Tensor:\n r\"\"\"Function that computes the relative homogenou...
import cv2 import os import torch import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm from datasets.gradslam_datasets.geometryutils import relative_transformation from utils.recon_helpers import setup_camera from utils.slam_external import build_rotation,calc_psnr from utils.slam_helpers import transform_to_frame, transformed_params2rendervar, transformed_params2depthplussilhouette from diff_gaussian_rasterization import GaussianRasterizer as Renderer from pytorch_msssim import ms_ssim from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
4,784
else: frame_opt_loss_dict = {} for k, v in loss_dict.items(): frame_opt_loss_dict[f"Per Iteration Current Frame Optimization/{k}"] = v frame_opt_loss_dict['Per Iteration Current Frame Optimization/step'] = wandb_step wandb_run.log(frame_opt_loss_dict) # Increment wandb step wandb_step += 1 return wandb_step def plot_rgbd_silhouette(color, depth, rastered_color, rastered_depth, presence_sil_mask, diff_depth_l1, psnr, depth_l1, fig_title, plot_dir=None, plot_name=None, save_plot=False, wandb_run=None, wandb_step=None, wandb_title=None, diff_rgb=None): # Determine Plot Aspect Ratio aspect_ratio = color.shape[2] / color.shape[1] fig_height = 8 fig_width = 14/1.55 fig_width = fig_width * aspect_ratio # Plot the Ground Truth and Rasterized RGB & Depth, along with Diff Depth & Silhouette fig, axs = plt.subplots(2, 3, figsize=(fig_width, fig_height)) axs[0, 0].imshow(color.cpu().permute(1, 2, 0)) axs[0, 0].set_title("Ground Truth RGB") axs[0, 1].imshow(depth[0, :, :].cpu(), cmap='jet', vmin=0, vmax=6) axs[0, 1].set_title("Ground Truth Depth") rastered_color = torch.clamp(rastered_color, 0, 1) axs[1, 0].imshow(rastered_color.cpu().permute(1, 2, 0)) axs[1, 0].set_title("Rasterized RGB, PSNR: {:.2f}".format(psnr)) axs[1, 1].imshow(rastered_depth[0, :, :].cpu(), cmap='jet', vmin=0, vmax=6) axs[1, 1].set_title("Rasterized Depth, L1: {:.2f}".format(depth_l1)) if diff_rgb is not None: axs[0, 2].imshow(diff_rgb.cpu(), cmap='jet', vmin=0, vmax=6) axs[0, 2].set_title("Diff RGB L1") else: axs[0, 2].imshow(presence_sil_mask, cmap='gray') axs[0, 2].set_title("Rasterized Silhouette") diff_depth_l1 = diff_depth_l1.cpu().squeeze(0) axs[1, 2].imshow(diff_depth_l1, cmap='jet', vmin=0, vmax=6) axs[1, 2].set_title("Diff Depth L1") for ax in axs.flatten(): ax.axis('off') fig.suptitle(fig_title, y=0.95, fontsize=16) fig.tight_layout() if save_plot: save_path = os.path.join(plot_dir, f"{plot_name}.png") plt.savefig(save_path, bbox_inches='tight') if wandb_run is not None: if wandb_step is None: wandb_run.log({wandb_title: fig}) else: wandb_run.log({wandb_title: fig}, step=wandb_step) plt.close() def report_progress(params, data, i, progress_bar, iter_time_idx, sil_thres, every_i=1, qual_every_i=1, tracking=False, mapping=False, wandb_run=None, wandb_step=None, wandb_save_qual=False, online_time_idx=None, global_logging=True): if i % every_i == 0 or i == 1: if wandb_run is not None: if tracking: stage = "Tracking" elif mapping: stage = "Mapping" else: stage = "Current Frame Optimization" if not global_logging: stage = "Per Iteration " + stage if tracking: # Get list of gt poses gt_w2c_list = data['iter_gt_w2c_list'] valid_gt_w2c_list = [] # Get latest trajectory latest_est_w2c = data['w2c'] latest_est_w2c_list = [] latest_est_w2c_list.append(latest_est_w2c) valid_gt_w2c_list.append(gt_w2c_list[0]) for idx in range(1, iter_time_idx+1): # Check if gt pose is not nan for this time step if torch.isnan(gt_w2c_list[idx]).sum() > 0: continue interm_cam_rot = F.normalize(params['cam_unnorm_rots'][..., idx].detach()) interm_cam_trans = params['cam_trans'][..., idx].detach() intermrel_w2c = torch.eye(4).cuda().float() intermrel_w2c[:3, :3] = build_rotation(interm_cam_rot) intermrel_w2c[:3, 3] = interm_cam_trans latest_est_w2c = intermrel_w2c latest_est_w2c_list.append(latest_est_w2c) valid_gt_w2c_list.append(gt_w2c_list[idx]) # Get latest gt pose gt_w2c_list = valid_gt_w2c_list iter_gt_w2c = gt_w2c_list[-1] # Get euclidean distance error between latest and gt pose iter_pt_error = torch.sqrt((latest_est_w2c[0,3] - iter_gt_w2c[0,3])**2 + (latest_est_w2c[1,3] - iter_gt_w2c[1,3])**2 + (latest_est_w2c[2,3] - iter_gt_w2c[2,3])**2) if iter_time_idx > 0: # Calculate relative pose error rel_gt_w2c = relative_transformation(gt_w2c_list[-2], gt_w2c_list[-1]) rel_est_w2c = relative_transformation(latest_est_w2c_list[-2], latest_est_w2c_list[-1]) rel_pt_error = torch.sqrt((rel_gt_w2c[0,3] - rel_est_w2c[0,3])**2 + (rel_gt_w2c[1,3] - rel_est_w2c[1,3])**2 + (rel_gt_w2c[2,3] - rel_est_w2c[2,3])**2) else: rel_pt_error = torch.zeros(1).float() # Calculate ATE RMSE ate_rmse = evaluate_ate(gt_w2c_list, latest_est_w2c_list) ate_rmse = np.round(ate_rmse, decimals=6) if wandb_run is not None: tracking_log = {f"{stage}/Latest Pose Error":iter_pt_error, f"{stage}/Latest Relative Pose Error":rel_pt_error, f"{stage}/ATE RMSE":ate_rmse} # Get current frame Gaussians transformed_pts = transform_to_frame(params, iter_time_idx, gaussians_grad=False, camera_grad=False) # Initialize Render Variables rendervar = transformed_params2rendervar(params, transformed_pts)
loss_fn_alex = LearnedPerceptualImagePatchSimilarity(net_type='alex', normalize=True).cuda() def align(model, data): """Align two trajectories using the method of Horn (closed-form). Args: model -- first trajectory (3xn) data -- second trajectory (3xn) Returns: rot -- rotation matrix (3x3) trans -- translation vector (3x1) trans_error -- translational error per point (1xn) """ np.set_printoptions(precision=3, suppress=True) model_zerocentered = model - model.mean(1).reshape((3,-1)) data_zerocentered = data - data.mean(1).reshape((3,-1)) W = np.zeros((3, 3)) for column in range(model.shape[1]): W += np.outer(model_zerocentered[:, column], data_zerocentered[:, column]) U, d, Vh = np.linalg.linalg.svd(W.transpose()) S = np.matrix(np.identity(3)) if (np.linalg.det(U) * np.linalg.det(Vh) < 0): S[2, 2] = -1 rot = U*S*Vh trans = data.mean(1).reshape((3,-1)) - rot * model.mean(1).reshape((3,-1)) model_aligned = rot * model + trans alignment_error = model_aligned - data trans_error = np.sqrt(np.sum(np.multiply( alignment_error, alignment_error), 0)).A[0] return rot, trans, trans_error def evaluate_ate(gt_traj, est_traj): """ Input : gt_traj: list of 4x4 matrices est_traj: list of 4x4 matrices len(gt_traj) == len(est_traj) """ gt_traj_pts = [gt_traj[idx][:3,3] for idx in range(len(gt_traj))] est_traj_pts = [est_traj[idx][:3,3] for idx in range(len(est_traj))] gt_traj_pts = torch.stack(gt_traj_pts).detach().cpu().numpy().T est_traj_pts = torch.stack(est_traj_pts).detach().cpu().numpy().T _, _, trans_error = align(gt_traj_pts, est_traj_pts) avg_trans_error = trans_error.mean() return avg_trans_error def report_loss(losses, wandb_run, wandb_step, tracking=False, mapping=False): # Update loss dict loss_dict = {'Loss': losses['loss'].item(), 'Image Loss': losses['im'].item(), 'Depth Loss': losses['depth'].item(),} if tracking: tracking_loss_dict = {} for k, v in loss_dict.items(): tracking_loss_dict[f"Per Iteration Tracking/{k}"] = v tracking_loss_dict['Per Iteration Tracking/step'] = wandb_step wandb_run.log(tracking_loss_dict) elif mapping: mapping_loss_dict = {} for k, v in loss_dict.items(): mapping_loss_dict[f"Per Iteration Mapping/{k}"] = v mapping_loss_dict['Per Iteration Mapping/step'] = wandb_step wandb_run.log(mapping_loss_dict) else: frame_opt_loss_dict = {} for k, v in loss_dict.items(): frame_opt_loss_dict[f"Per Iteration Current Frame Optimization/{k}"] = v frame_opt_loss_dict['Per Iteration Current Frame Optimization/step'] = wandb_step wandb_run.log(frame_opt_loss_dict) # Increment wandb step wandb_step += 1 return wandb_step def plot_rgbd_silhouette(color, depth, rastered_color, rastered_depth, presence_sil_mask, diff_depth_l1, psnr, depth_l1, fig_title, plot_dir=None, plot_name=None, save_plot=False, wandb_run=None, wandb_step=None, wandb_title=None, diff_rgb=None): # Determine Plot Aspect Ratio aspect_ratio = color.shape[2] / color.shape[1] fig_height = 8 fig_width = 14/1.55 fig_width = fig_width * aspect_ratio # Plot the Ground Truth and Rasterized RGB & Depth, along with Diff Depth & Silhouette fig, axs = plt.subplots(2, 3, figsize=(fig_width, fig_height)) axs[0, 0].imshow(color.cpu().permute(1, 2, 0)) axs[0, 0].set_title("Ground Truth RGB") axs[0, 1].imshow(depth[0, :, :].cpu(), cmap='jet', vmin=0, vmax=6) axs[0, 1].set_title("Ground Truth Depth") rastered_color = torch.clamp(rastered_color, 0, 1) axs[1, 0].imshow(rastered_color.cpu().permute(1, 2, 0)) axs[1, 0].set_title("Rasterized RGB, PSNR: {:.2f}".format(psnr)) axs[1, 1].imshow(rastered_depth[0, :, :].cpu(), cmap='jet', vmin=0, vmax=6) axs[1, 1].set_title("Rasterized Depth, L1: {:.2f}".format(depth_l1)) if diff_rgb is not None: axs[0, 2].imshow(diff_rgb.cpu(), cmap='jet', vmin=0, vmax=6) axs[0, 2].set_title("Diff RGB L1") else: axs[0, 2].imshow(presence_sil_mask, cmap='gray') axs[0, 2].set_title("Rasterized Silhouette") diff_depth_l1 = diff_depth_l1.cpu().squeeze(0) axs[1, 2].imshow(diff_depth_l1, cmap='jet', vmin=0, vmax=6) axs[1, 2].set_title("Diff Depth L1") for ax in axs.flatten(): ax.axis('off') fig.suptitle(fig_title, y=0.95, fontsize=16) fig.tight_layout() if save_plot: save_path = os.path.join(plot_dir, f"{plot_name}.png") plt.savefig(save_path, bbox_inches='tight') if wandb_run is not None: if wandb_step is None: wandb_run.log({wandb_title: fig}) else: wandb_run.log({wandb_title: fig}, step=wandb_step) plt.close() def report_progress(params, data, i, progress_bar, iter_time_idx, sil_thres, every_i=1, qual_every_i=1, tracking=False, mapping=False, wandb_run=None, wandb_step=None, wandb_save_qual=False, online_time_idx=None, global_logging=True): if i % every_i == 0 or i == 1: if wandb_run is not None: if tracking: stage = "Tracking" elif mapping: stage = "Mapping" else: stage = "Current Frame Optimization" if not global_logging: stage = "Per Iteration " + stage if tracking: # Get list of gt poses gt_w2c_list = data['iter_gt_w2c_list'] valid_gt_w2c_list = [] # Get latest trajectory latest_est_w2c = data['w2c'] latest_est_w2c_list = [] latest_est_w2c_list.append(latest_est_w2c) valid_gt_w2c_list.append(gt_w2c_list[0]) for idx in range(1, iter_time_idx+1): # Check if gt pose is not nan for this time step if torch.isnan(gt_w2c_list[idx]).sum() > 0: continue interm_cam_rot = F.normalize(params['cam_unnorm_rots'][..., idx].detach()) interm_cam_trans = params['cam_trans'][..., idx].detach() intermrel_w2c = torch.eye(4).cuda().float() intermrel_w2c[:3, :3] = build_rotation(interm_cam_rot) intermrel_w2c[:3, 3] = interm_cam_trans latest_est_w2c = intermrel_w2c latest_est_w2c_list.append(latest_est_w2c) valid_gt_w2c_list.append(gt_w2c_list[idx]) # Get latest gt pose gt_w2c_list = valid_gt_w2c_list iter_gt_w2c = gt_w2c_list[-1] # Get euclidean distance error between latest and gt pose iter_pt_error = torch.sqrt((latest_est_w2c[0,3] - iter_gt_w2c[0,3])**2 + (latest_est_w2c[1,3] - iter_gt_w2c[1,3])**2 + (latest_est_w2c[2,3] - iter_gt_w2c[2,3])**2) if iter_time_idx > 0: # Calculate relative pose error rel_gt_w2c = relative_transformation(gt_w2c_list[-2], gt_w2c_list[-1]) rel_est_w2c = relative_transformation(latest_est_w2c_list[-2], latest_est_w2c_list[-1]) rel_pt_error = torch.sqrt((rel_gt_w2c[0,3] - rel_est_w2c[0,3])**2 + (rel_gt_w2c[1,3] - rel_est_w2c[1,3])**2 + (rel_gt_w2c[2,3] - rel_est_w2c[2,3])**2) else: rel_pt_error = torch.zeros(1).float() # Calculate ATE RMSE ate_rmse = evaluate_ate(gt_w2c_list, latest_est_w2c_list) ate_rmse = np.round(ate_rmse, decimals=6) if wandb_run is not None: tracking_log = {f"{stage}/Latest Pose Error":iter_pt_error, f"{stage}/Latest Relative Pose Error":rel_pt_error, f"{stage}/ATE RMSE":ate_rmse} # Get current frame Gaussians transformed_pts = transform_to_frame(params, iter_time_idx, gaussians_grad=False, camera_grad=False) # Initialize Render Variables rendervar = transformed_params2rendervar(params, transformed_pts)
depth_sil_rendervar = transformed_params2depthplussilhouette(params, data['w2c'],
6
2023-11-30 20:26:47+00:00
8k
zhyever/PatchFusion
zoedepth/trainers/base_trainer.py
[ { "identifier": "flatten", "path": "zoedepth/utils/config.py", "snippet": "def flatten(config, except_keys=('bin_conf')):\n def recurse(inp):\n if isinstance(inp, dict):\n for key, value in inp.items():\n if key in except_keys:\n yield (key, value)\...
import os import uuid import warnings import matplotlib.pyplot as plt import numpy as np import torch import torch.distributed as dist import torch.nn as nn import torch.optim as optim import wandb import glob import os from datetime import datetime as dt from typing import Dict from tqdm import tqdm from zoedepth.utils.config import flatten from zoedepth.utils.misc import RunningAverageDict, colorize, colors from zoedepth.models.model_io import load_wts
3,987
self.should_write = ((not self.config.distributed) or self.config.rank == 0) self.should_log = self.should_write # and logging if self.should_log: tags = self.config.tags.split( ',') if self.config.tags != '' else None wandb.init(project=self.config.project, name=self.config.experiment_id, config=flatten(self.config), dir=self.config.root, tags=tags, notes=self.config.notes, settings=wandb.Settings(start_method="fork")) self.model.train() self.step = 0 best_loss = np.inf validate_every = int(self.config.validate_every * self.iters_per_epoch) if self.config.prefetch: for i, batch in tqdm(enumerate(self.train_loader), desc=f"Prefetching...", total=self.iters_per_epoch) if is_rank_zero(self.config) else enumerate(self.train_loader): pass losses = {} def stringify_losses(L): return "; ".join(map( lambda kv: f"{colors.fg.purple}{kv[0]}{colors.reset}: {round(kv[1].item(),3):.4e}", L.items())) for epoch in range(self.config.epochs): if self.should_early_stop(): break self.epoch = epoch # self.model.eval() # metrics, test_losses = self.validate() # print(metrics) # exit(100) ################################# Train loop ########################################################## if self.should_log: wandb.log({"Epoch": epoch}, step=self.step) pbar = tqdm(enumerate(self.train_loader), desc=f"Epoch: {epoch + 1}/{self.config.epochs}. Loop: Train", total=self.iters_per_epoch) if is_rank_zero(self.config) else enumerate(self.train_loader) for i, batch in pbar: if self.should_early_stop(): print("Early stopping") break # print(f"Batch {self.step+1} on rank {self.config.rank}") losses = self.train_on_batch(batch, i) # print(f"trained batch {self.step+1} on rank {self.config.rank}") self.raise_if_nan(losses) if is_rank_zero(self.config) and self.config.print_losses: pbar.set_description( f"Epoch: {epoch + 1}/{self.config.epochs}. Loop: Train. Losses: {stringify_losses(losses)}") self.scheduler.step() if self.should_log and self.step % 50 == 0: wandb.log({f"Train/{name}": loss.item() for name, loss in losses.items()}, step=self.step) # current_lr = self.optimizer.param_groups[0]['lr'] current_lr = self.scheduler.get_last_lr()[0] wandb.log({f"Train/LR": current_lr}, step=self.step) momentum = self.optimizer.param_groups[0]['betas'][0] wandb.log({f"Train/momentum": momentum}, step=self.step) self.step += 1 ######################################################################################################## if self.test_loader: if (self.step % validate_every) == 0: self.model.eval() if self.should_write: self.save_checkpoint( f"{self.config.experiment_id}_latest.pt") ################################# Validation loop ################################################## # validate on the entire validation set in every process but save only from rank 0, I know, inefficient, but avoids divergence of processes metrics, test_losses = self.validate() # print("Validated: {}".format(metrics)) if self.should_log: wandb.log( {f"Test/{name}": tloss for name, tloss in test_losses.items()}, step=self.step) wandb.log({f"Metrics/{k}": v for k, v in metrics.items()}, step=self.step) if (metrics[self.metric_criterion] < best_loss) and self.should_write: self.save_checkpoint( f"{self.config.experiment_id}_best.pt") best_loss = metrics[self.metric_criterion] self.model.train() if self.config.distributed: dist.barrier() # print(f"Validated: {metrics} on device {self.config.rank}") # print(f"Finished step {self.step} on device {self.config.rank}") ################################################################################################# # Save / validate at the end self.step += 1 # log as final point self.model.eval() self.save_checkpoint(f"{self.config.experiment_id}_latest.pt") if self.test_loader: ################################# Validation loop ################################################## metrics, test_losses = self.validate() # print("Validated: {}".format(metrics)) if self.should_log: wandb.log({f"Test/{name}": tloss for name, tloss in test_losses.items()}, step=self.step) wandb.log({f"Metrics/{k}": v for k, v in metrics.items()}, step=self.step) if (metrics[self.metric_criterion] < best_loss) and self.should_write: self.save_checkpoint( f"{self.config.experiment_id}_best.pt") best_loss = metrics[self.metric_criterion] self.model.train() def validate(self): with torch.no_grad():
# MIT License # Copyright (c) 2022 Intelligent Systems Lab Org # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # File author: Shariq Farooq Bhat # This file may include modifications from author Zhenyu Li def is_rank_zero(args): return args.rank == 0 class BaseTrainer: def __init__(self, config, model, train_loader, test_loader=None, device=None): """ Base Trainer class for training a model.""" self.config = config self.metric_criterion = "abs_rel" if device is None: device = torch.device( 'cuda') if torch.cuda.is_available() else torch.device('cpu') self.device = device self.model = model self.train_loader = train_loader self.test_loader = test_loader self.optimizer = self.init_optimizer() self.scheduler = self.init_scheduler() # import matplotlib.pyplot as plt # lrs = [] # momentums = [] # for e in range(self.config.epochs): # for s in range(len(self.train_loader)): # self.scheduler.step() # self.optimizer.step() # lr = self.scheduler.get_last_lr()[2] # lrs.append(lr) # print(self.optimizer.param_groups[0]['betas']) # momentum = self.optimizer.param_groups[0]['betas'][0] # momentums.append(momentum) # step = [_ for _ in range(len(lrs))] # plt.scatter(step, momentums) # plt.savefig("debug.png") # exit(100) def resize_to_target(self, prediction, target): if prediction.shape[2:] != target.shape[-2:]: prediction = nn.functional.interpolate( prediction, size=target.shape[-2:], mode="bilinear", align_corners=True ) return prediction def load_ckpt(self, checkpoint_dir="./checkpoints", ckpt_type="best"): if hasattr(self.config, "checkpoint"): checkpoint = self.config.checkpoint elif hasattr(self.config, "ckpt_pattern"): pattern = self.config.ckpt_pattern matches = glob.glob(os.path.join( checkpoint_dir, f"*{pattern}*{ckpt_type}*")) if not (len(matches) > 0): raise ValueError(f"No matches found for the pattern {pattern}") checkpoint = matches[0] else: return model = load_wts(self.model, checkpoint) # TODO : Resuming training is not properly supported in this repo. Implement loading / saving of optimizer and scheduler to support it. print("Loaded weights from {0}".format(checkpoint)) warnings.warn( "Resuming training is not properly supported in this repo. Implement loading / saving of optimizer and scheduler to support it.") self.model = model def init_optimizer(self): m = self.model.module if self.config.multigpu else self.model if self.config.same_lr: print("Using same LR") if hasattr(m, 'core'): m.core.unfreeze() params = self.model.parameters() else: print("Using diff LR") if not hasattr(m, 'get_lr_params'): raise NotImplementedError( f"Model {m.__class__.__name__} does not implement get_lr_params. Please implement it or use the same LR for all parameters.") params = m.get_lr_params(self.config.lr) return optim.AdamW(params, lr=self.config.lr, weight_decay=self.config.wd) def init_scheduler(self): lrs = [l['lr'] for l in self.optimizer.param_groups] return optim.lr_scheduler.OneCycleLR(self.optimizer, lrs, epochs=self.config.epochs, steps_per_epoch=len(self.train_loader), cycle_momentum=self.config.cycle_momentum, base_momentum=self.config.get('base_momentum', 0.85), max_momentum=self.config.get('max_momentum', 0.95), div_factor=self.config.div_factor, final_div_factor=self.config.final_div_factor, pct_start=self.config.pct_start, three_phase=self.config.three_phase) def train_on_batch(self, batch, train_step): raise NotImplementedError def validate_on_batch(self, batch, val_step): raise NotImplementedError def raise_if_nan(self, losses): for key, value in losses.items(): if torch.isnan(value): raise ValueError(f"{key} is NaN, Stopping training") @property def iters_per_epoch(self): return len(self.train_loader) @property def total_iters(self): return self.config.epochs * self.iters_per_epoch def should_early_stop(self): if self.config.get('early_stop', False) and self.step > self.config.early_stop: return True def train(self): print(f"Training {self.config.name}") if self.config.uid is None: self.config.uid = str(uuid.uuid4()).split('-')[-1] run_id = f"{dt.now().strftime('%d-%h_%H-%M')}-{self.config.uid}" self.config.run_id = run_id self.config.experiment_id = f"{self.config.name}{self.config.version_name}_{run_id}" self.should_write = ((not self.config.distributed) or self.config.rank == 0) self.should_log = self.should_write # and logging if self.should_log: tags = self.config.tags.split( ',') if self.config.tags != '' else None wandb.init(project=self.config.project, name=self.config.experiment_id, config=flatten(self.config), dir=self.config.root, tags=tags, notes=self.config.notes, settings=wandb.Settings(start_method="fork")) self.model.train() self.step = 0 best_loss = np.inf validate_every = int(self.config.validate_every * self.iters_per_epoch) if self.config.prefetch: for i, batch in tqdm(enumerate(self.train_loader), desc=f"Prefetching...", total=self.iters_per_epoch) if is_rank_zero(self.config) else enumerate(self.train_loader): pass losses = {} def stringify_losses(L): return "; ".join(map( lambda kv: f"{colors.fg.purple}{kv[0]}{colors.reset}: {round(kv[1].item(),3):.4e}", L.items())) for epoch in range(self.config.epochs): if self.should_early_stop(): break self.epoch = epoch # self.model.eval() # metrics, test_losses = self.validate() # print(metrics) # exit(100) ################################# Train loop ########################################################## if self.should_log: wandb.log({"Epoch": epoch}, step=self.step) pbar = tqdm(enumerate(self.train_loader), desc=f"Epoch: {epoch + 1}/{self.config.epochs}. Loop: Train", total=self.iters_per_epoch) if is_rank_zero(self.config) else enumerate(self.train_loader) for i, batch in pbar: if self.should_early_stop(): print("Early stopping") break # print(f"Batch {self.step+1} on rank {self.config.rank}") losses = self.train_on_batch(batch, i) # print(f"trained batch {self.step+1} on rank {self.config.rank}") self.raise_if_nan(losses) if is_rank_zero(self.config) and self.config.print_losses: pbar.set_description( f"Epoch: {epoch + 1}/{self.config.epochs}. Loop: Train. Losses: {stringify_losses(losses)}") self.scheduler.step() if self.should_log and self.step % 50 == 0: wandb.log({f"Train/{name}": loss.item() for name, loss in losses.items()}, step=self.step) # current_lr = self.optimizer.param_groups[0]['lr'] current_lr = self.scheduler.get_last_lr()[0] wandb.log({f"Train/LR": current_lr}, step=self.step) momentum = self.optimizer.param_groups[0]['betas'][0] wandb.log({f"Train/momentum": momentum}, step=self.step) self.step += 1 ######################################################################################################## if self.test_loader: if (self.step % validate_every) == 0: self.model.eval() if self.should_write: self.save_checkpoint( f"{self.config.experiment_id}_latest.pt") ################################# Validation loop ################################################## # validate on the entire validation set in every process but save only from rank 0, I know, inefficient, but avoids divergence of processes metrics, test_losses = self.validate() # print("Validated: {}".format(metrics)) if self.should_log: wandb.log( {f"Test/{name}": tloss for name, tloss in test_losses.items()}, step=self.step) wandb.log({f"Metrics/{k}": v for k, v in metrics.items()}, step=self.step) if (metrics[self.metric_criterion] < best_loss) and self.should_write: self.save_checkpoint( f"{self.config.experiment_id}_best.pt") best_loss = metrics[self.metric_criterion] self.model.train() if self.config.distributed: dist.barrier() # print(f"Validated: {metrics} on device {self.config.rank}") # print(f"Finished step {self.step} on device {self.config.rank}") ################################################################################################# # Save / validate at the end self.step += 1 # log as final point self.model.eval() self.save_checkpoint(f"{self.config.experiment_id}_latest.pt") if self.test_loader: ################################# Validation loop ################################################## metrics, test_losses = self.validate() # print("Validated: {}".format(metrics)) if self.should_log: wandb.log({f"Test/{name}": tloss for name, tloss in test_losses.items()}, step=self.step) wandb.log({f"Metrics/{k}": v for k, v in metrics.items()}, step=self.step) if (metrics[self.metric_criterion] < best_loss) and self.should_write: self.save_checkpoint( f"{self.config.experiment_id}_best.pt") best_loss = metrics[self.metric_criterion] self.model.train() def validate(self): with torch.no_grad():
losses_avg = RunningAverageDict()
1
2023-12-04 08:43:15+00:00
8k
dangeng/visual_anagrams
visual_anagrams/views/view_jigsaw.py
[ { "identifier": "make_jigsaw_perm", "path": "visual_anagrams/views/permutations.py", "snippet": "def make_jigsaw_perm(size, seed=0):\n '''\n Returns a permutation of pixels that is a jigsaw permutation\n\n There are 3 types of pieces: corner, edge, and inner pieces. These were\n created ...
import numpy as np import torch from PIL import Image from einops import einsum, rearrange from .permutations import make_jigsaw_perm, get_inv_perm from .view_permute import PermuteView from .jigsaw_helpers import get_jigsaw_pieces
4,482
im_piece = np.concatenate([im, piece_mask[:,:,None] * 255], axis=2) # Get extents of piece, and crop x_min = np.nonzero(im_piece[:,:,-1].sum(0))[0].min() x_max = np.nonzero(im_piece[:,:,-1].sum(0))[0].max() y_min = np.nonzero(im_piece[:,:,-1].sum(1))[0].min() y_max = np.nonzero(im_piece[:,:,-1].sum(1))[0].max() im_piece = im_piece[y_min:y_max+1, x_min:x_max+1] pieces.append(Image.fromarray(im_piece)) return pieces def paste_piece(self, piece, x, y, theta, xc, yc, canvas_size=384): ''' Given a PIL Image of a piece, place it so that it's center is at (x,y) and it's rotate about that center at theta degrees x (float) : x coordinate to place piece at y (float) : y coordinate to place piece at theta (float) : degrees to rotate piece about center xc (float) : x coordinate of center of piece yc (float) : y coordinate of center of piece ''' # Make canvas canvas = Image.new("RGBA", (canvas_size, canvas_size), (255, 255, 255, 0)) # Past piece so center is at (x, y) canvas.paste(piece, (x-xc,y-yc), piece) # Rotate about (x, y) canvas = canvas.rotate(theta, resample=Image.BILINEAR, center=(x, y)) return canvas def make_frame(self, im, t, canvas_size=384, knot_seed=0): ''' This function returns a PIL image of a frame animating a jigsaw permutation. Pieces move and rotate from the identity view (t = 0) to the rearranged view (t = 1) along splines. The approach is as follows: 1. Extract all 16 pieces 2. Figure out start locations for each of these pieces (t=0) 3. Figure out how these pieces permute 4. Using these permutations, figure out end locations (t=1) 5. Make knots for splines, randomly offset normally from the midpoint of the start and end locations 6. Paste pieces into correct locations, determined by spline interpolation im (PIL.Image) : PIL image representing the jigsaw illusion t (float) : Interpolation parameter in [0,1] indicating what frame of the animation to generate canvas_size (int) : Side length of the frame knot_seed (int) : Seed for random offsets for the knots ''' im_size = im.size[0] # Extract 16 jigsaw pieces pieces = self.extract_pieces(im) # Rotate all pieces to "base" piece orientation pieces = [p.rotate(90 * (i % 4), resample=Image.BILINEAR, expand=1) for i, p in enumerate(pieces)] # Get (hardcoded) start locations for each base piece, on a # 4x4 grid centered on the origin. corner_start_loc = np.array([-1.5, -1.5]) inner_start_loc = np.array([-0.5, -0.5]) edge_e_start_loc = np.array([-1.5, -0.5]) edge_f_start_loc = np.array([-1.5, 0.5]) base_start_locs = np.stack([corner_start_loc, inner_start_loc, edge_e_start_loc, edge_f_start_loc]) # Construct all start locations by rotating around (0,0) # by 90 degrees, 4 times, and concatenating the results rot_mats = [] for theta in -np.arange(4) * 90 / 180 * np.pi: rot_mat = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) rot_mats.append(rot_mat) rot_mats = np.stack(rot_mats) start_locs = einsum(base_start_locs, rot_mats, 'start i, rot j i -> start rot j') start_locs = rearrange(start_locs, 'start rot j -> (start rot) j') # Add rotation information to start locations thetas = np.tile(np.arange(4) * -90, 4)[:, None] start_locs = np.concatenate([start_locs, thetas], axis=1) # Get explicit permutation of pieces from permutation metadata perm = self.piece_perms + np.repeat(np.arange(4), 4) * 4 for edge_idx, to_swap in enumerate(self.edge_swaps): if to_swap: # Make swap permutation array swap_perm = np.arange(16) swap_perm[8 + edge_idx], swap_perm[12 + edge_idx] = \ swap_perm[12 + edge_idx], swap_perm[8 + edge_idx] # Apply swap permutation after perm perm = np.array([swap_perm[perm[i]] for i in range(16)]) # Get inverse perm (the actual permutation needed)...
class JigsawView(PermuteView): ''' Implements a 4x4 jigsaw puzzle view... ''' def __init__(self, seed=11): ''' ''' # Get pixel permutations, corresponding to jigsaw permutations self.perm_64, _ = make_jigsaw_perm(64, seed=seed) self.perm_256, (jigsaw_perm) = make_jigsaw_perm(256, seed=seed) # keep track of jigsaw permutation as well self.piece_perms, self.edge_swaps = jigsaw_perm # Init parent PermuteView, with above pixel perms super().__init__(self.perm_64, self.perm_256) def extract_pieces(self, im): ''' Given an image, extract jigsaw puzzle pieces from it im (PIL.Image) : PIL Image of the jigsaw illusion ''' im = np.array(im) size = im.shape[0] pieces = [] # Get jigsaw pieces piece_masks = get_jigsaw_pieces(size) # Save pieces for piece_mask in piece_masks: # Add mask as alpha mask to image im_piece = np.concatenate([im, piece_mask[:,:,None] * 255], axis=2) # Get extents of piece, and crop x_min = np.nonzero(im_piece[:,:,-1].sum(0))[0].min() x_max = np.nonzero(im_piece[:,:,-1].sum(0))[0].max() y_min = np.nonzero(im_piece[:,:,-1].sum(1))[0].min() y_max = np.nonzero(im_piece[:,:,-1].sum(1))[0].max() im_piece = im_piece[y_min:y_max+1, x_min:x_max+1] pieces.append(Image.fromarray(im_piece)) return pieces def paste_piece(self, piece, x, y, theta, xc, yc, canvas_size=384): ''' Given a PIL Image of a piece, place it so that it's center is at (x,y) and it's rotate about that center at theta degrees x (float) : x coordinate to place piece at y (float) : y coordinate to place piece at theta (float) : degrees to rotate piece about center xc (float) : x coordinate of center of piece yc (float) : y coordinate of center of piece ''' # Make canvas canvas = Image.new("RGBA", (canvas_size, canvas_size), (255, 255, 255, 0)) # Past piece so center is at (x, y) canvas.paste(piece, (x-xc,y-yc), piece) # Rotate about (x, y) canvas = canvas.rotate(theta, resample=Image.BILINEAR, center=(x, y)) return canvas def make_frame(self, im, t, canvas_size=384, knot_seed=0): ''' This function returns a PIL image of a frame animating a jigsaw permutation. Pieces move and rotate from the identity view (t = 0) to the rearranged view (t = 1) along splines. The approach is as follows: 1. Extract all 16 pieces 2. Figure out start locations for each of these pieces (t=0) 3. Figure out how these pieces permute 4. Using these permutations, figure out end locations (t=1) 5. Make knots for splines, randomly offset normally from the midpoint of the start and end locations 6. Paste pieces into correct locations, determined by spline interpolation im (PIL.Image) : PIL image representing the jigsaw illusion t (float) : Interpolation parameter in [0,1] indicating what frame of the animation to generate canvas_size (int) : Side length of the frame knot_seed (int) : Seed for random offsets for the knots ''' im_size = im.size[0] # Extract 16 jigsaw pieces pieces = self.extract_pieces(im) # Rotate all pieces to "base" piece orientation pieces = [p.rotate(90 * (i % 4), resample=Image.BILINEAR, expand=1) for i, p in enumerate(pieces)] # Get (hardcoded) start locations for each base piece, on a # 4x4 grid centered on the origin. corner_start_loc = np.array([-1.5, -1.5]) inner_start_loc = np.array([-0.5, -0.5]) edge_e_start_loc = np.array([-1.5, -0.5]) edge_f_start_loc = np.array([-1.5, 0.5]) base_start_locs = np.stack([corner_start_loc, inner_start_loc, edge_e_start_loc, edge_f_start_loc]) # Construct all start locations by rotating around (0,0) # by 90 degrees, 4 times, and concatenating the results rot_mats = [] for theta in -np.arange(4) * 90 / 180 * np.pi: rot_mat = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) rot_mats.append(rot_mat) rot_mats = np.stack(rot_mats) start_locs = einsum(base_start_locs, rot_mats, 'start i, rot j i -> start rot j') start_locs = rearrange(start_locs, 'start rot j -> (start rot) j') # Add rotation information to start locations thetas = np.tile(np.arange(4) * -90, 4)[:, None] start_locs = np.concatenate([start_locs, thetas], axis=1) # Get explicit permutation of pieces from permutation metadata perm = self.piece_perms + np.repeat(np.arange(4), 4) * 4 for edge_idx, to_swap in enumerate(self.edge_swaps): if to_swap: # Make swap permutation array swap_perm = np.arange(16) swap_perm[8 + edge_idx], swap_perm[12 + edge_idx] = \ swap_perm[12 + edge_idx], swap_perm[8 + edge_idx] # Apply swap permutation after perm perm = np.array([swap_perm[perm[i]] for i in range(16)]) # Get inverse perm (the actual permutation needed)...
perm_inv = get_inv_perm(torch.tensor(perm))
1
2023-11-29 15:26:04+00:00
8k
LTH14/rcg
rdm/models/diffusion/ddpm.py
[ { "identifier": "exists", "path": "rdm/util.py", "snippet": "def exists(x):\n return x is not None" }, { "identifier": "default", "path": "rdm/util.py", "snippet": "def default(val, d):\n if exists(val):\n return val\n return d() if isfunction(d) else d" }, { "ide...
import torch import torch.nn as nn import numpy as np import pretrained_enc.models_pretrained_enc as models_pretrained_enc from einops import rearrange, repeat from contextlib import contextmanager from functools import partial from tqdm import tqdm from torchvision.utils import make_grid from pytorch_lightning.utilities.distributed import rank_zero_only from rdm.util import exists, default, count_params, instantiate_from_config from rdm.modules.ema import LitEma from rdm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
4,216
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) try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print("Deleting key {} from state_dict.".format(k)) del sd[k] missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: print(f"Missing Keys: {missing}") if len(unexpected) > 0: print(f"Unexpected Keys: {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop((batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None):
__conditioning_keys__ = {'concat': 'c_concat', 'crossattn': 'c_crossattn', 'adm': 'y'} def disabled_train(self, mode=True): """Overwrite model.train with this function to make sure train/eval mode does not change anymore.""" return self def uniform_on_device(r1, r2, shape, device): return (r1 - r2) * torch.rand(*shape, device=device) + r2 class DDPM(nn.Module): # 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, 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, learn_logvar=False, logvar_init=0., ): super().__init__() assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"' self.parameterization = parameterization print(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode") self.cond_stage_model = None self.clip_denoised = clip_denoised self.log_every_t = log_every_t self.first_stage_key = first_stage_key self.image_size = image_size # try conv? self.channels = channels self.model = DiffusionWrapper(unet_config, conditioning_key) count_params(self.model, verbose=True) self.use_ema = use_ema if self.use_ema: self.model_ema = LitEma(self.model) print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") self.use_scheduler = scheduler_config is not None if self.use_scheduler: self.scheduler_config = scheduler_config self.v_posterior = v_posterior self.original_elbo_weight = original_elbo_weight self.l_simple_weight = l_simple_weight if 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) try: yield None finally: if self.use_ema: self.model_ema.restore(self.model.parameters()) def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): sd = torch.load(path, map_location="cpu") if "state_dict" in list(sd.keys()): sd = sd["state_dict"] keys = list(sd.keys()) for k in keys: for ik in ignore_keys: if k.startswith(ik): print("Deleting key {} from state_dict.".format(k)) del sd[k] missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict( sd, strict=False) print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys") if len(missing) > 0: print(f"Missing Keys: {missing}") if len(unexpected) > 0: print(f"Unexpected Keys: {unexpected}") def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start) variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape) return mean, variance, log_variance def predict_start_from_noise(self, x_t, t, noise): return ( extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise ) def q_posterior(self, x_start, x_t, t): posterior_mean = ( extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance(self, x, t, clip_denoised: bool): model_out = self.model(x, t) if self.parameterization == "eps": x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) elif self.parameterization == "x0": x_recon = model_out if clip_denoised: x_recon.clamp_(-1., 1.) model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t) return model_mean, posterior_variance, posterior_log_variance @torch.no_grad() def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): b, *_, device = *x.shape, x.device model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised) noise = noise_like(x.shape, device, repeat_noise) # no noise when t == 0 nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise @torch.no_grad() def p_sample_loop(self, shape, return_intermediates=False): device = self.betas.device b = shape[0] img = torch.randn(shape, device=device) intermediates = [img] for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), clip_denoised=self.clip_denoised) if i % self.log_every_t == 0 or i == self.num_timesteps - 1: intermediates.append(img) if return_intermediates: return img, intermediates return img @torch.no_grad() def sample(self, batch_size=16, return_intermediates=False): image_size = self.image_size channels = self.channels return self.p_sample_loop((batch_size, channels, image_size, image_size), return_intermediates=return_intermediates) def q_sample(self, x_start, t, noise=None):
noise = default(noise, lambda: torch.randn_like(x_start))
1
2023-12-01 02:08:50+00:00
8k
autonomousvision/mip-splatting
scene/dataset_readers.py
[ { "identifier": "read_extrinsics_text", "path": "scene/colmap_loader.py", "snippet": "def read_extrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n images = {}\n with open(path, \"r\") as fid:\n while T...
import os import sys import numpy as np import json from PIL import Image from typing import NamedTuple from scene.colmap_loader import read_extrinsics_text, read_intrinsics_text, qvec2rotmat, \ read_extrinsics_binary, read_intrinsics_binary, read_points3D_binary, read_points3D_text from utils.graphics_utils import getWorld2View2, focal2fov, fov2focal from pathlib import Path from plyfile import PlyData, PlyElement from utils.sh_utils import SH2RGB from scene.gaussian_model import BasicPointCloud
4,621
ply_path: str def getNerfppNorm(cam_info): def get_center_and_diag(cam_centers): cam_centers = np.hstack(cam_centers) avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True) center = avg_cam_center dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True) diagonal = np.max(dist) return center.flatten(), diagonal cam_centers = [] for cam in cam_info: W2C = getWorld2View2(cam.R, cam.T) C2W = np.linalg.inv(W2C) cam_centers.append(C2W[:3, 3:4]) center, diagonal = get_center_and_diag(cam_centers) radius = diagonal * 1.1 translate = -center return {"translate": translate, "radius": radius} def readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder): cam_infos = [] for idx, key in enumerate(cam_extrinsics): sys.stdout.write('\r') # the exact output you're looking for: sys.stdout.write("Reading camera {}/{}".format(idx+1, len(cam_extrinsics))) sys.stdout.flush() extr = cam_extrinsics[key] intr = cam_intrinsics[extr.camera_id] height = intr.height width = intr.width uid = intr.id R = np.transpose(qvec2rotmat(extr.qvec)) T = np.array(extr.tvec) if intr.model=="SIMPLE_PINHOLE": focal_length_x = intr.params[0] FovY = focal2fov(focal_length_x, height) FovX = focal2fov(focal_length_x, width) elif intr.model=="PINHOLE": focal_length_x = intr.params[0] focal_length_y = intr.params[1] FovY = focal2fov(focal_length_y, height) FovX = focal2fov(focal_length_x, width) else: assert False, "Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!" image_path = os.path.join(images_folder, os.path.basename(extr.name)) image_name = os.path.basename(image_path).split(".")[0] image = Image.open(image_path) cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height) cam_infos.append(cam_info) sys.stdout.write('\n') return cam_infos def fetchPly(path): plydata = PlyData.read(path) vertices = plydata['vertex'] positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0 normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T return BasicPointCloud(points=positions, colors=colors, normals=normals) def storePly(path, xyz, rgb): # Define the dtype for the structured array dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')] normals = np.zeros_like(xyz) elements = np.empty(xyz.shape[0], dtype=dtype) attributes = np.concatenate((xyz, normals, rgb), axis=1) elements[:] = list(map(tuple, attributes)) # Create the PlyData object and write to file vertex_element = PlyElement.describe(elements, 'vertex') ply_data = PlyData([vertex_element]) ply_data.write(path) def readColmapSceneInfo(path, images, eval, llffhold=8): try: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.bin") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.bin") cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file) cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file) except: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.txt") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.txt") cam_extrinsics = read_extrinsics_text(cameras_extrinsic_file) cam_intrinsics = read_intrinsics_text(cameras_intrinsic_file) reading_dir = "images" if images == None else images cam_infos_unsorted = readColmapCameras(cam_extrinsics=cam_extrinsics, cam_intrinsics=cam_intrinsics, images_folder=os.path.join(path, reading_dir)) cam_infos = sorted(cam_infos_unsorted.copy(), key = lambda x : x.image_name) if eval: train_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold != 0] test_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold == 0] else: train_cam_infos = cam_infos test_cam_infos = [] nerf_normalization = getNerfppNorm(train_cam_infos) ply_path = os.path.join(path, "sparse/0/points3D.ply") bin_path = os.path.join(path, "sparse/0/points3D.bin") txt_path = os.path.join(path, "sparse/0/points3D.txt") if not os.path.exists(ply_path): print("Converting point3d.bin to .ply, will happen only the first time you open the scene.") try:
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # class CameraInfo(NamedTuple): uid: int R: np.array T: np.array FovY: np.array FovX: np.array image: np.array image_path: str image_name: str width: int height: int class SceneInfo(NamedTuple): point_cloud: BasicPointCloud train_cameras: list test_cameras: list nerf_normalization: dict ply_path: str def getNerfppNorm(cam_info): def get_center_and_diag(cam_centers): cam_centers = np.hstack(cam_centers) avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True) center = avg_cam_center dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True) diagonal = np.max(dist) return center.flatten(), diagonal cam_centers = [] for cam in cam_info: W2C = getWorld2View2(cam.R, cam.T) C2W = np.linalg.inv(W2C) cam_centers.append(C2W[:3, 3:4]) center, diagonal = get_center_and_diag(cam_centers) radius = diagonal * 1.1 translate = -center return {"translate": translate, "radius": radius} def readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder): cam_infos = [] for idx, key in enumerate(cam_extrinsics): sys.stdout.write('\r') # the exact output you're looking for: sys.stdout.write("Reading camera {}/{}".format(idx+1, len(cam_extrinsics))) sys.stdout.flush() extr = cam_extrinsics[key] intr = cam_intrinsics[extr.camera_id] height = intr.height width = intr.width uid = intr.id R = np.transpose(qvec2rotmat(extr.qvec)) T = np.array(extr.tvec) if intr.model=="SIMPLE_PINHOLE": focal_length_x = intr.params[0] FovY = focal2fov(focal_length_x, height) FovX = focal2fov(focal_length_x, width) elif intr.model=="PINHOLE": focal_length_x = intr.params[0] focal_length_y = intr.params[1] FovY = focal2fov(focal_length_y, height) FovX = focal2fov(focal_length_x, width) else: assert False, "Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!" image_path = os.path.join(images_folder, os.path.basename(extr.name)) image_name = os.path.basename(image_path).split(".")[0] image = Image.open(image_path) cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height) cam_infos.append(cam_info) sys.stdout.write('\n') return cam_infos def fetchPly(path): plydata = PlyData.read(path) vertices = plydata['vertex'] positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0 normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T return BasicPointCloud(points=positions, colors=colors, normals=normals) def storePly(path, xyz, rgb): # Define the dtype for the structured array dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')] normals = np.zeros_like(xyz) elements = np.empty(xyz.shape[0], dtype=dtype) attributes = np.concatenate((xyz, normals, rgb), axis=1) elements[:] = list(map(tuple, attributes)) # Create the PlyData object and write to file vertex_element = PlyElement.describe(elements, 'vertex') ply_data = PlyData([vertex_element]) ply_data.write(path) def readColmapSceneInfo(path, images, eval, llffhold=8): try: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.bin") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.bin") cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file) cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file) except: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.txt") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.txt") cam_extrinsics = read_extrinsics_text(cameras_extrinsic_file) cam_intrinsics = read_intrinsics_text(cameras_intrinsic_file) reading_dir = "images" if images == None else images cam_infos_unsorted = readColmapCameras(cam_extrinsics=cam_extrinsics, cam_intrinsics=cam_intrinsics, images_folder=os.path.join(path, reading_dir)) cam_infos = sorted(cam_infos_unsorted.copy(), key = lambda x : x.image_name) if eval: train_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold != 0] test_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold == 0] else: train_cam_infos = cam_infos test_cam_infos = [] nerf_normalization = getNerfppNorm(train_cam_infos) ply_path = os.path.join(path, "sparse/0/points3D.ply") bin_path = os.path.join(path, "sparse/0/points3D.bin") txt_path = os.path.join(path, "sparse/0/points3D.txt") if not os.path.exists(ply_path): print("Converting point3d.bin to .ply, will happen only the first time you open the scene.") try:
xyz, rgb, _ = read_points3D_binary(bin_path)
5
2023-11-27 16:49:03+00:00
8k
baaivision/GeoDream
threestudio/models/renderers/nerf_volume_renderer.py
[ { "identifier": "BaseBackground", "path": "threestudio/models/background/base.py", "snippet": "class BaseBackground(BaseModule):\n @dataclass\n class Config(BaseModule.Config):\n pass\n\n cfg: Config\n\n def configure(self):\n pass\n\n def forward(self, dirs: Float[Tensor, \...
from dataclasses import dataclass, field from functools import partial from threestudio.models.background.base import BaseBackground from threestudio.models.estimators import ImportanceEstimator from threestudio.models.geometry.base import BaseImplicitGeometry from threestudio.models.materials.base import BaseMaterial from threestudio.models.networks import create_network_with_input_encoding from threestudio.models.renderers.base import VolumeRenderer from threestudio.systems.utils import parse_optimizer, parse_scheduler_to_instance from threestudio.utils.ops import chunk_batch, get_activation, validate_empty_rays from threestudio.utils.typing import * import nerfacc import torch import torch.nn.functional as F import threestudio
4,643
@threestudio.register("nerf-volume-renderer") class NeRFVolumeRenderer(VolumeRenderer): @dataclass class Config(VolumeRenderer.Config): num_samples_per_ray: int = 512 eval_chunk_size: int = 160000 randomized: bool = True near_plane: float = 0.0 far_plane: float = 1e10 return_comp_normal: bool = False return_normal_perturb: bool = False # in ["occgrid", "proposal", "importance"] estimator: str = "occgrid" # for occgrid grid_prune: bool = True prune_alpha_threshold: bool = True # for proposal proposal_network_config: Optional[dict] = None prop_optimizer_config: Optional[dict] = None prop_scheduler_config: Optional[dict] = None num_samples_per_ray_proposal: int = 64 # for importance num_samples_per_ray_importance: int = 64 cfg: Config def configure( self, geometry: BaseImplicitGeometry, material: BaseMaterial,
@threestudio.register("nerf-volume-renderer") class NeRFVolumeRenderer(VolumeRenderer): @dataclass class Config(VolumeRenderer.Config): num_samples_per_ray: int = 512 eval_chunk_size: int = 160000 randomized: bool = True near_plane: float = 0.0 far_plane: float = 1e10 return_comp_normal: bool = False return_normal_perturb: bool = False # in ["occgrid", "proposal", "importance"] estimator: str = "occgrid" # for occgrid grid_prune: bool = True prune_alpha_threshold: bool = True # for proposal proposal_network_config: Optional[dict] = None prop_optimizer_config: Optional[dict] = None prop_scheduler_config: Optional[dict] = None num_samples_per_ray_proposal: int = 64 # for importance num_samples_per_ray_importance: int = 64 cfg: Config def configure( self, geometry: BaseImplicitGeometry, material: BaseMaterial,
background: BaseBackground,
0
2023-12-01 01:59:42+00:00
8k
dvlab-research/LLaMA-VID
llamavid/model/llamavid_arch.py
[ { "identifier": "BertConfig", "path": "llamavid/model/qformer.py", "snippet": "class BertEmbeddings(nn.Module):\nclass BertSelfAttention(nn.Module):\nclass BertSelfOutput(nn.Module):\nclass BertAttention(nn.Module):\nclass BertIntermediate(nn.Module):\nclass BertOutput(nn.Module):\nclass BertLayer(nn.Mo...
from abc import ABC, abstractmethod from transformers import BertTokenizer from transformers.models.bert.modeling_bert import BertLMHeadModel as BertLMHeadModelRaw from .qformer import BertConfig from .qformer import BertLMHeadModel as BertLMHeadModelQF from .multimodal_encoder.builder import build_vision_tower from .multimodal_projector.builder import build_vision_projector from llamavid.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_PATCH_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN import os import json import numpy as np import torch import torch.nn as nn import torch.nn.functional as F
3,962
# Copyright 2023 Haotian Liu # # 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. # ------------------------------------------------------------------------ # Modified from LLaVA (https://github.com/haotian-liu/LLaVA) # Copyright 2023 Yanwei Li # ------------------------------------------------------------------------ class LLaMAVIDMetaModel: def __init__(self, config): super(LLaMAVIDMetaModel, self).__init__(config) if hasattr(config, "mm_vision_tower"):
# Copyright 2023 Haotian Liu # # 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. # ------------------------------------------------------------------------ # Modified from LLaVA (https://github.com/haotian-liu/LLaVA) # Copyright 2023 Yanwei Li # ------------------------------------------------------------------------ class LLaMAVIDMetaModel: def __init__(self, config): super(LLaMAVIDMetaModel, self).__init__(config) if hasattr(config, "mm_vision_tower"):
self.vision_tower = build_vision_tower(config, delay_load=True)
2
2023-11-28 09:45:37+00:00
8k
horseee/DeepCache
DeepCache/svd/unet_spatio_temporal_condition.py
[ { "identifier": "UNetMidBlockSpatioTemporal", "path": "DeepCache/svd/unet_3d_blocks.py", "snippet": "class UNetMidBlockSpatioTemporal(nn.Module):\n def __init__(\n self,\n in_channels: int,\n temb_channels: int,\n num_layers: int = 1,\n transformer_layers_per_block:...
from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.loaders import UNet2DConditionLoadersMixin from diffusers.utils import BaseOutput, logging from diffusers.models.attention_processor import CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnProcessor from diffusers.models.embeddings import TimestepEmbedding, Timesteps from diffusers.models.modeling_utils import ModelMixin from .unet_3d_blocks import UNetMidBlockSpatioTemporal, get_down_block, get_up_block import torch import torch.nn as nn
5,632
self.sample_size = sample_size # Check inputs if len(down_block_types) != len(up_block_types): raise ValueError( f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}." ) if len(block_out_channels) != len(down_block_types): raise ValueError( f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}." ) if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types): raise ValueError( f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}." ) if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types): raise ValueError( f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}." ) if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types): raise ValueError( f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}." ) # input self.conv_in = nn.Conv2d( in_channels, block_out_channels[0], kernel_size=3, padding=1, ) # time time_embed_dim = block_out_channels[0] * 4 self.time_proj = Timesteps(block_out_channels[0], True, downscale_freq_shift=0) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) self.add_time_proj = Timesteps(addition_time_embed_dim, True, downscale_freq_shift=0) self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) self.down_blocks = nn.ModuleList([]) self.up_blocks = nn.ModuleList([]) if isinstance(num_attention_heads, int): num_attention_heads = (num_attention_heads,) * len(down_block_types) if isinstance(cross_attention_dim, int): cross_attention_dim = (cross_attention_dim,) * len(down_block_types) if isinstance(layers_per_block, int): layers_per_block = [layers_per_block] * len(down_block_types) if isinstance(transformer_layers_per_block, int): transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types) blocks_time_embed_dim = time_embed_dim # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block[i], transformer_layers_per_block=transformer_layers_per_block[i], in_channels=input_channel, out_channels=output_channel, temb_channels=blocks_time_embed_dim, add_downsample=not is_final_block, resnet_eps=1e-5, cross_attention_dim=cross_attention_dim[i], num_attention_heads=num_attention_heads[i], resnet_act_fn="silu", ) self.down_blocks.append(down_block) # mid self.mid_block = UNetMidBlockSpatioTemporal( block_out_channels[-1], temb_channels=blocks_time_embed_dim, transformer_layers_per_block=transformer_layers_per_block[-1], cross_attention_dim=cross_attention_dim[-1], num_attention_heads=num_attention_heads[-1], ) # count how many layers upsample the images self.num_upsamplers = 0 # up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_num_attention_heads = list(reversed(num_attention_heads)) reversed_layers_per_block = list(reversed(layers_per_block)) reversed_cross_attention_dim = list(reversed(cross_attention_dim)) reversed_transformer_layers_per_block = list(reversed(transformer_layers_per_block)) 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
logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class UNetSpatioTemporalConditionOutput(BaseOutput): """ The output of [`UNetSpatioTemporalConditionModel`]. Args: sample (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`): The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model. """ sample: torch.FloatTensor = None class UNetSpatioTemporalConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin): r""" A conditional Spatio-Temporal UNet model that takes a noisy video frames, conditional state, and a timestep and returns a sample shaped output. This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented for all models (such as downloading or saving). Parameters: sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`): Height and width of input/output sample. in_channels (`int`, *optional*, defaults to 8): Number of channels in the input sample. out_channels (`int`, *optional*, defaults to 4): Number of channels in the output. down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "DownBlockSpatioTemporal")`): The tuple of downsample blocks to use. up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal")`): 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. addition_time_embed_dim: (`int`, defaults to 256): Dimension to to encode the additional time ids. projection_class_embeddings_input_dim (`int`, defaults to 768): The dimension of the projection of encoded `added_time_ids`. layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block. cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280): The dimension of the cross attention features. transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1): The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for [`~models.unet_3d_blocks.CrossAttnDownBlockSpatioTemporal`], [`~models.unet_3d_blocks.CrossAttnUpBlockSpatioTemporal`], [`~models.unet_3d_blocks.UNetMidBlockSpatioTemporal`]. num_attention_heads (`int`, `Tuple[int]`, defaults to `(5, 10, 10, 20)`): The number of attention heads. dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. """ _supports_gradient_checkpointing = True @register_to_config def __init__( self, sample_size: Optional[int] = None, in_channels: int = 8, out_channels: int = 4, down_block_types: Tuple[str] = ( "CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "DownBlockSpatioTemporal", ), up_block_types: Tuple[str] = ( "UpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", ), block_out_channels: Tuple[int] = (320, 640, 1280, 1280), addition_time_embed_dim: int = 256, projection_class_embeddings_input_dim: int = 768, layers_per_block: Union[int, Tuple[int]] = 2, cross_attention_dim: Union[int, Tuple[int]] = 1024, transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1, num_attention_heads: Union[int, Tuple[int]] = (5, 10, 10, 20), num_frames: int = 25, ): super().__init__() self.sample_size = sample_size # Check inputs if len(down_block_types) != len(up_block_types): raise ValueError( f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}." ) if len(block_out_channels) != len(down_block_types): raise ValueError( f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}." ) if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types): raise ValueError( f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}." ) if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types): raise ValueError( f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}." ) if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types): raise ValueError( f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}." ) # input self.conv_in = nn.Conv2d( in_channels, block_out_channels[0], kernel_size=3, padding=1, ) # time time_embed_dim = block_out_channels[0] * 4 self.time_proj = Timesteps(block_out_channels[0], True, downscale_freq_shift=0) timestep_input_dim = block_out_channels[0] self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) self.add_time_proj = Timesteps(addition_time_embed_dim, True, downscale_freq_shift=0) self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim) self.down_blocks = nn.ModuleList([]) self.up_blocks = nn.ModuleList([]) if isinstance(num_attention_heads, int): num_attention_heads = (num_attention_heads,) * len(down_block_types) if isinstance(cross_attention_dim, int): cross_attention_dim = (cross_attention_dim,) * len(down_block_types) if isinstance(layers_per_block, int): layers_per_block = [layers_per_block] * len(down_block_types) if isinstance(transformer_layers_per_block, int): transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types) blocks_time_embed_dim = time_embed_dim # down output_channel = block_out_channels[0] for i, down_block_type in enumerate(down_block_types): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 down_block = get_down_block( down_block_type, num_layers=layers_per_block[i], transformer_layers_per_block=transformer_layers_per_block[i], in_channels=input_channel, out_channels=output_channel, temb_channels=blocks_time_embed_dim, add_downsample=not is_final_block, resnet_eps=1e-5, cross_attention_dim=cross_attention_dim[i], num_attention_heads=num_attention_heads[i], resnet_act_fn="silu", ) self.down_blocks.append(down_block) # mid self.mid_block = UNetMidBlockSpatioTemporal( block_out_channels[-1], temb_channels=blocks_time_embed_dim, transformer_layers_per_block=transformer_layers_per_block[-1], cross_attention_dim=cross_attention_dim[-1], num_attention_heads=num_attention_heads[-1], ) # count how many layers upsample the images self.num_upsamplers = 0 # up reversed_block_out_channels = list(reversed(block_out_channels)) reversed_num_attention_heads = list(reversed(num_attention_heads)) reversed_layers_per_block = list(reversed(layers_per_block)) reversed_cross_attention_dim = list(reversed(cross_attention_dim)) reversed_transformer_layers_per_block = list(reversed(transformer_layers_per_block)) 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(
2
2023-12-01 10:54:04+00:00
8k
csuhan/OneLLM
demos/multi_turn_mm.py
[ { "identifier": "setup_for_distributed", "path": "util/misc.py", "snippet": "def setup_for_distributed(is_master):\n \"\"\"\n This function disables printing when not in master process\n \"\"\"\n builtin_print = builtins.print\n\n def print(*args, **kwargs):\n force = kwargs.pop('f...
import sys import os import argparse import multiprocessing as mp import numpy as np import torch import torch.distributed as dist import gradio as gr import torchvision.transforms as transforms from typing import List, Optional from fairscale.nn.model_parallel import initialize as fs_init from util.misc import setup_for_distributed from util.misc import default_tensor_type from model.meta import MetaModel from data.conversation_lib import conv_templates, SeparatorStyle from PIL import Image from data.fintune_dataset import make_audio_features from data import video_utils
4,078
sys.path.append(os.path.abspath(__file__).rsplit('/', 2)[0]) T_random_resized_crop = transforms.Compose([ transforms.RandomResizedCrop(size=(224, 224), scale=(0.9, 1.0), ratio=(0.75, 1.3333), interpolation=3, antialias=None), # 3 is bicubic transforms.ToTensor(), transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])]) def load_audio(audio_path): fbank = make_audio_features(audio_path, mel_bins=128) fbank = fbank.transpose(0, 1)[None] #[1, 128, 1024] return fbank def load_video(video_path): video_feats = video_utils.load_and_transform_video_data(video_path, video_path, clip_duration=1, clips_per_video=5) return video_feats[:, :, 0] def model_worker( rank: int, args: argparse.Namespace, barrier: mp.Barrier, request_queue: mp.Queue, response_queue: Optional[mp.Queue] = None, ) -> None: """ The worker function that manipulates the GPU to run the inference. Exact n_gpu workers are started, with each one operating on a separate GPU. Args: rank (int): Distributed rank of the worker. args (argparse.Namespace): All command line arguments. barrier (multiprocessing.Barrier): A barrier used to delay the start of Web UI to be after the start of the model. """ world_size = len(args.gpu_ids) gpu_id = args.gpu_ids[rank] dist.init_process_group( backend="nccl", rank=rank, world_size=world_size, init_method=f"tcp://{args.master_addr}:{args.master_port}", ) print(f"| distributed init on worker {rank}/{world_size}. " f"using gpu: {gpu_id}") fs_init.initialize_model_parallel(world_size) torch.cuda.set_device(gpu_id) torch.manual_seed(1) np.random.seed(1) # set the print behavior. setup_for_distributed(rank == 0) target_dtype = { "bf16": torch.bfloat16, "fp16": torch.float16 }[args.dtype] with default_tensor_type(dtype=target_dtype, device="cuda"): model = MetaModel(args.llama_type, args.llama_config, tokenizer_path=args.tokenizer_path) print("Loading pretrained weights ...") checkpoint = torch.load(args.pretrained_path, map_location='cpu') msg = model.load_state_dict(checkpoint, strict=False) print("load result:\n", msg) model.cuda() model.eval() print(f"Model = {str(model)}") barrier.wait() while True: img_path, audio_path, video_path, chatbot, max_gen_len, temperature, top_p, modality = request_queue.get() if 'image' in modality and img_path is not None: image = Image.open(img_path).convert('RGB') inputs = T_random_resized_crop(image) elif 'video' in modality and video_path is not None: inputs = load_video(video_path) elif 'audio' in modality and audio_path is not None: inputs = load_audio(audio_path) else: inputs = None if inputs is not None: inputs = inputs[None].cuda().to(target_dtype) conv = conv_templates["v1"].copy() for user, bot in chatbot: conv.append_message(conv.roles[0], user) conv.append_message(conv.roles[1], bot) with torch.cuda.amp.autocast(dtype=target_dtype): print(conv.get_prompt()) for stream_response in model.stream_generate( conv.get_prompt(), inputs, max_gen_len=max_gen_len, temperature=temperature, top_p=top_p, modal = modality ): conv_sep = ( conv.sep
sys.path.append(os.path.abspath(__file__).rsplit('/', 2)[0]) T_random_resized_crop = transforms.Compose([ transforms.RandomResizedCrop(size=(224, 224), scale=(0.9, 1.0), ratio=(0.75, 1.3333), interpolation=3, antialias=None), # 3 is bicubic transforms.ToTensor(), transforms.Normalize(mean=[0.48145466, 0.4578275, 0.40821073], std=[0.26862954, 0.26130258, 0.27577711])]) def load_audio(audio_path): fbank = make_audio_features(audio_path, mel_bins=128) fbank = fbank.transpose(0, 1)[None] #[1, 128, 1024] return fbank def load_video(video_path): video_feats = video_utils.load_and_transform_video_data(video_path, video_path, clip_duration=1, clips_per_video=5) return video_feats[:, :, 0] def model_worker( rank: int, args: argparse.Namespace, barrier: mp.Barrier, request_queue: mp.Queue, response_queue: Optional[mp.Queue] = None, ) -> None: """ The worker function that manipulates the GPU to run the inference. Exact n_gpu workers are started, with each one operating on a separate GPU. Args: rank (int): Distributed rank of the worker. args (argparse.Namespace): All command line arguments. barrier (multiprocessing.Barrier): A barrier used to delay the start of Web UI to be after the start of the model. """ world_size = len(args.gpu_ids) gpu_id = args.gpu_ids[rank] dist.init_process_group( backend="nccl", rank=rank, world_size=world_size, init_method=f"tcp://{args.master_addr}:{args.master_port}", ) print(f"| distributed init on worker {rank}/{world_size}. " f"using gpu: {gpu_id}") fs_init.initialize_model_parallel(world_size) torch.cuda.set_device(gpu_id) torch.manual_seed(1) np.random.seed(1) # set the print behavior. setup_for_distributed(rank == 0) target_dtype = { "bf16": torch.bfloat16, "fp16": torch.float16 }[args.dtype] with default_tensor_type(dtype=target_dtype, device="cuda"): model = MetaModel(args.llama_type, args.llama_config, tokenizer_path=args.tokenizer_path) print("Loading pretrained weights ...") checkpoint = torch.load(args.pretrained_path, map_location='cpu') msg = model.load_state_dict(checkpoint, strict=False) print("load result:\n", msg) model.cuda() model.eval() print(f"Model = {str(model)}") barrier.wait() while True: img_path, audio_path, video_path, chatbot, max_gen_len, temperature, top_p, modality = request_queue.get() if 'image' in modality and img_path is not None: image = Image.open(img_path).convert('RGB') inputs = T_random_resized_crop(image) elif 'video' in modality and video_path is not None: inputs = load_video(video_path) elif 'audio' in modality and audio_path is not None: inputs = load_audio(audio_path) else: inputs = None if inputs is not None: inputs = inputs[None].cuda().to(target_dtype) conv = conv_templates["v1"].copy() for user, bot in chatbot: conv.append_message(conv.roles[0], user) conv.append_message(conv.roles[1], bot) with torch.cuda.amp.autocast(dtype=target_dtype): print(conv.get_prompt()) for stream_response in model.stream_generate( conv.get_prompt(), inputs, max_gen_len=max_gen_len, temperature=temperature, top_p=top_p, modal = modality ): conv_sep = ( conv.sep
if conv.sep_style == SeparatorStyle.SINGLE
3
2023-11-27 07:28:08+00:00
8k
alvinliu0/HumanGaussian
gaussiansplatting/scene/dataset_readers.py
[ { "identifier": "read_extrinsics_text", "path": "gaussiansplatting/scene/colmap_loader.py", "snippet": "def read_extrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n images = {}\n with open(path, \"r\") as fid...
import os import sys import numpy as np import json from PIL import Image from typing import NamedTuple from gaussiansplatting.scene.colmap_loader import read_extrinsics_text, read_intrinsics_text, qvec2rotmat, \ read_extrinsics_binary, read_intrinsics_binary, read_points3D_binary, read_points3D_text from gaussiansplatting.utils.graphics_utils import getWorld2View2, focal2fov, fov2focal from pathlib import Path from plyfile import PlyData, PlyElement from gaussiansplatting.utils.sh_utils import SH2RGB from gaussiansplatting.scene.gaussian_model import BasicPointCloud
4,224
# All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # class CameraInfo(NamedTuple): uid: int R: np.array T: np.array FovY: np.array FovX: np.array image: np.array image_path: str image_name: str width: int height: int class SceneInfo(NamedTuple): point_cloud: BasicPointCloud train_cameras: list test_cameras: list nerf_normalization: dict ply_path: str def getNerfppNorm(cam_info): def get_center_and_diag(cam_centers): cam_centers = np.hstack(cam_centers) avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True) center = avg_cam_center dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True) diagonal = np.max(dist) return center.flatten(), diagonal cam_centers = [] for cam in cam_info: W2C = getWorld2View2(cam.R, cam.T) C2W = np.linalg.inv(W2C) cam_centers.append(C2W[:3, 3:4]) center, diagonal = get_center_and_diag(cam_centers) radius = diagonal * 1.1 translate = -center return {"translate": translate, "radius": radius} def readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder): cam_infos = [] for idx, key in enumerate(cam_extrinsics): sys.stdout.write('\r') # the exact output you're looking for: sys.stdout.write("Reading camera {}/{}".format(idx+1, len(cam_extrinsics))) sys.stdout.flush() extr = cam_extrinsics[key] intr = cam_intrinsics[extr.camera_id] height = intr.height width = intr.width uid = intr.id R = np.transpose(qvec2rotmat(extr.qvec)) T = np.array(extr.tvec) if intr.model=="SIMPLE_PINHOLE": focal_length_x = intr.params[0] FovY = focal2fov(focal_length_x, height) FovX = focal2fov(focal_length_x, width) elif intr.model=="PINHOLE": focal_length_x = intr.params[0] focal_length_y = intr.params[1] FovY = focal2fov(focal_length_y, height) FovX = focal2fov(focal_length_x, width) else: assert False, "Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!" image_path = os.path.join(images_folder, os.path.basename(extr.name)) image_name = os.path.basename(image_path).split(".")[0] image = Image.open(image_path) cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height) cam_infos.append(cam_info) sys.stdout.write('\n') return cam_infos def fetchPly(path): plydata = PlyData.read(path) vertices = plydata['vertex'] positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0 normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T return BasicPointCloud(points=positions, colors=colors, normals=normals) def storePly(path, xyz, rgb): # Define the dtype for the structured array dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')] normals = np.zeros_like(xyz) elements = np.empty(xyz.shape[0], dtype=dtype) attributes = np.concatenate((xyz, normals, rgb), axis=1) elements[:] = list(map(tuple, attributes)) # Create the PlyData object and write to file vertex_element = PlyElement.describe(elements, 'vertex') ply_data = PlyData([vertex_element]) ply_data.write(path) def readColmapSceneInfo(path, images, eval, llffhold=8): try: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.bin") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.bin") cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file)
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # class CameraInfo(NamedTuple): uid: int R: np.array T: np.array FovY: np.array FovX: np.array image: np.array image_path: str image_name: str width: int height: int class SceneInfo(NamedTuple): point_cloud: BasicPointCloud train_cameras: list test_cameras: list nerf_normalization: dict ply_path: str def getNerfppNorm(cam_info): def get_center_and_diag(cam_centers): cam_centers = np.hstack(cam_centers) avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True) center = avg_cam_center dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True) diagonal = np.max(dist) return center.flatten(), diagonal cam_centers = [] for cam in cam_info: W2C = getWorld2View2(cam.R, cam.T) C2W = np.linalg.inv(W2C) cam_centers.append(C2W[:3, 3:4]) center, diagonal = get_center_and_diag(cam_centers) radius = diagonal * 1.1 translate = -center return {"translate": translate, "radius": radius} def readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder): cam_infos = [] for idx, key in enumerate(cam_extrinsics): sys.stdout.write('\r') # the exact output you're looking for: sys.stdout.write("Reading camera {}/{}".format(idx+1, len(cam_extrinsics))) sys.stdout.flush() extr = cam_extrinsics[key] intr = cam_intrinsics[extr.camera_id] height = intr.height width = intr.width uid = intr.id R = np.transpose(qvec2rotmat(extr.qvec)) T = np.array(extr.tvec) if intr.model=="SIMPLE_PINHOLE": focal_length_x = intr.params[0] FovY = focal2fov(focal_length_x, height) FovX = focal2fov(focal_length_x, width) elif intr.model=="PINHOLE": focal_length_x = intr.params[0] focal_length_y = intr.params[1] FovY = focal2fov(focal_length_y, height) FovX = focal2fov(focal_length_x, width) else: assert False, "Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!" image_path = os.path.join(images_folder, os.path.basename(extr.name)) image_name = os.path.basename(image_path).split(".")[0] image = Image.open(image_path) cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height) cam_infos.append(cam_info) sys.stdout.write('\n') return cam_infos def fetchPly(path): plydata = PlyData.read(path) vertices = plydata['vertex'] positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0 normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T return BasicPointCloud(points=positions, colors=colors, normals=normals) def storePly(path, xyz, rgb): # Define the dtype for the structured array dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')] normals = np.zeros_like(xyz) elements = np.empty(xyz.shape[0], dtype=dtype) attributes = np.concatenate((xyz, normals, rgb), axis=1) elements[:] = list(map(tuple, attributes)) # Create the PlyData object and write to file vertex_element = PlyElement.describe(elements, 'vertex') ply_data = PlyData([vertex_element]) ply_data.write(path) def readColmapSceneInfo(path, images, eval, llffhold=8): try: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.bin") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.bin") cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file)
cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file)
4
2023-11-27 02:39:39+00:00
8k
ShunyuanZheng/GPS-Gaussian
train_stage1.py
[ { "identifier": "StereoHumanDataset", "path": "lib/human_loader.py", "snippet": "class StereoHumanDataset(Dataset):\n def __init__(self, opt, phase='train'):\n self.opt = opt\n self.use_processed_data = opt.use_processed_data\n self.phase = phase\n if self.phase == 'train'...
import logging import numpy as np import os import torch import torch.optim as optim import warnings from pathlib import Path from tqdm import tqdm from datetime import datetime from lib.human_loader import StereoHumanDataset from lib.network import RtStereoHumanModel from config.stereo_human_config import ConfigStereoHuman as config from lib.train_recoder import Logger, file_backup from torch.cuda.amp import GradScaler from torch.utils.data import DataLoader
7,117
from __future__ import print_function, division warnings.filterwarnings("ignore", category=UserWarning) class Trainer: def __init__(self, cfg_file): self.cfg = cfg_file self.model = RtStereoHumanModel(self.cfg, with_gs_render=False) self.train_set = StereoHumanDataset(self.cfg.dataset, phase='train') self.train_loader = DataLoader(self.train_set, batch_size=self.cfg.batch_size, shuffle=True, num_workers=self.cfg.batch_size*2, pin_memory=True) self.train_iterator = iter(self.train_loader) self.val_set = StereoHumanDataset(self.cfg.dataset, phase='val') self.val_loader = DataLoader(self.val_set, batch_size=2, shuffle=False, num_workers=4, pin_memory=True) self.len_val = int(len(self.val_loader) / self.val_set.val_boost) # real length of val set self.val_iterator = iter(self.val_loader) self.optimizer = optim.AdamW(self.model.parameters(), lr=self.cfg.lr, weight_decay=self.cfg.wdecay, eps=1e-8) self.scheduler = optim.lr_scheduler.OneCycleLR(self.optimizer, self.cfg.lr, 100100, pct_start=0.01, cycle_momentum=False, anneal_strategy='linear')
from __future__ import print_function, division warnings.filterwarnings("ignore", category=UserWarning) class Trainer: def __init__(self, cfg_file): self.cfg = cfg_file self.model = RtStereoHumanModel(self.cfg, with_gs_render=False) self.train_set = StereoHumanDataset(self.cfg.dataset, phase='train') self.train_loader = DataLoader(self.train_set, batch_size=self.cfg.batch_size, shuffle=True, num_workers=self.cfg.batch_size*2, pin_memory=True) self.train_iterator = iter(self.train_loader) self.val_set = StereoHumanDataset(self.cfg.dataset, phase='val') self.val_loader = DataLoader(self.val_set, batch_size=2, shuffle=False, num_workers=4, pin_memory=True) self.len_val = int(len(self.val_loader) / self.val_set.val_boost) # real length of val set self.val_iterator = iter(self.val_loader) self.optimizer = optim.AdamW(self.model.parameters(), lr=self.cfg.lr, weight_decay=self.cfg.wdecay, eps=1e-8) self.scheduler = optim.lr_scheduler.OneCycleLR(self.optimizer, self.cfg.lr, 100100, pct_start=0.01, cycle_momentum=False, anneal_strategy='linear')
self.logger = Logger(self.scheduler, cfg.record)
3
2023-12-04 06:12:57+00:00
8k
EricGuo5513/momask-codes
eval_t2m_vq.py
[ { "identifier": "RVQVAE", "path": "models/vq/model.py", "snippet": "class RVQVAE(nn.Module):\n def __init__(self,\n args,\n input_width=263,\n nb_code=1024,\n code_dim=512,\n output_emb_width=512,\n down_t...
import sys import os import torch import utils.eval_t2m as eval_t2m import warnings import numpy as np from os.path import join as pjoin from models.vq.model import RVQVAE from options.vq_option import arg_parse from motion_loaders.dataset_motion_loader import get_dataset_motion_loader from utils.get_opt import get_opt from models.t2m_eval_wrapper import EvaluatorModelWrapper from utils.word_vectorizer import WordVectorizer
4,475
warnings.filterwarnings('ignore') def load_vq_model(vq_opt, which_epoch): # opt_path = pjoin(opt.checkpoints_dir, opt.dataset_name, opt.vq_name, 'opt.txt') vq_model = RVQVAE(vq_opt, dim_pose, vq_opt.nb_code, vq_opt.code_dim, vq_opt.code_dim, vq_opt.down_t, vq_opt.stride_t, vq_opt.width, vq_opt.depth, vq_opt.dilation_growth_rate, vq_opt.vq_act, vq_opt.vq_norm) ckpt = torch.load(pjoin(vq_opt.checkpoints_dir, vq_opt.dataset_name, vq_opt.name, 'model', which_epoch), map_location='cpu') model_key = 'vq_model' if 'vq_model' in ckpt else 'net' vq_model.load_state_dict(ckpt[model_key]) vq_epoch = ckpt['ep'] if 'ep' in ckpt else -1 print(f'Loading VQ Model {vq_opt.name} Completed!, Epoch {vq_epoch}') return vq_model, vq_epoch if __name__ == "__main__": ##### ---- Exp dirs ---- #####
warnings.filterwarnings('ignore') def load_vq_model(vq_opt, which_epoch): # opt_path = pjoin(opt.checkpoints_dir, opt.dataset_name, opt.vq_name, 'opt.txt') vq_model = RVQVAE(vq_opt, dim_pose, vq_opt.nb_code, vq_opt.code_dim, vq_opt.code_dim, vq_opt.down_t, vq_opt.stride_t, vq_opt.width, vq_opt.depth, vq_opt.dilation_growth_rate, vq_opt.vq_act, vq_opt.vq_norm) ckpt = torch.load(pjoin(vq_opt.checkpoints_dir, vq_opt.dataset_name, vq_opt.name, 'model', which_epoch), map_location='cpu') model_key = 'vq_model' if 'vq_model' in ckpt else 'net' vq_model.load_state_dict(ckpt[model_key]) vq_epoch = ckpt['ep'] if 'ep' in ckpt else -1 print(f'Loading VQ Model {vq_opt.name} Completed!, Epoch {vq_epoch}') return vq_model, vq_epoch if __name__ == "__main__": ##### ---- Exp dirs ---- #####
args = arg_parse(False)
1
2023-11-29 19:21:27+00:00
8k
lkeab/gaussian-grouping
scene/dataset_readers.py
[ { "identifier": "read_extrinsics_text", "path": "scene/colmap_loader.py", "snippet": "def read_extrinsics_text(path):\n \"\"\"\n Taken from https://github.com/colmap/colmap/blob/dev/scripts/python/read_write_model.py\n \"\"\"\n images = {}\n with open(path, \"r\") as fid:\n while T...
import os import sys import numpy as np import json from PIL import Image from typing import NamedTuple from scene.colmap_loader import read_extrinsics_text, read_intrinsics_text, qvec2rotmat, \ read_extrinsics_binary, read_intrinsics_binary, read_points3D_binary, read_points3D_text from utils.graphics_utils import getWorld2View2, focal2fov, fov2focal from pathlib import Path from plyfile import PlyData, PlyElement from utils.sh_utils import SH2RGB from scene.gaussian_model import BasicPointCloud
5,130
FovX = focal2fov(focal_length_x, width) elif intr.model=="PINHOLE": focal_length_x = intr.params[0] focal_length_y = intr.params[1] FovY = focal2fov(focal_length_y, height) FovX = focal2fov(focal_length_x, width) else: assert False, "Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!" image_path = os.path.join(images_folder, os.path.basename(extr.name)) image_name = os.path.basename(image_path).split(".")[0] image = Image.open(image_path) if os.path.exists(image_path) else None object_path = os.path.join(objects_folder, image_name + '.png') objects = Image.open(object_path) if os.path.exists(object_path) else None cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height, objects=objects) cam_infos.append(cam_info) sys.stdout.write('\n') return cam_infos def fetchPly(path): plydata = PlyData.read(path) vertices = plydata['vertex'] positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0 normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T return BasicPointCloud(points=positions, colors=colors, normals=normals) def storePly(path, xyz, rgb): # Define the dtype for the structured array dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')] normals = np.zeros_like(xyz) elements = np.empty(xyz.shape[0], dtype=dtype) attributes = np.concatenate((xyz, normals, rgb), axis=1) elements[:] = list(map(tuple, attributes)) # Create the PlyData object and write to file vertex_element = PlyElement.describe(elements, 'vertex') ply_data = PlyData([vertex_element]) ply_data.write(path) def readColmapSceneInfo(path, images, eval, object_path, llffhold=8, n_views=100, random_init=False, train_split=False): try: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.bin") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.bin") cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file) cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file) except: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.txt") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.txt") cam_extrinsics = read_extrinsics_text(cameras_extrinsic_file) cam_intrinsics = read_intrinsics_text(cameras_intrinsic_file) reading_dir = "images" if images == None else images object_dir = 'object_mask' if object_path == None else object_path cam_infos_unsorted = readColmapCameras(cam_extrinsics=cam_extrinsics, cam_intrinsics=cam_intrinsics, images_folder=os.path.join(path, reading_dir), objects_folder=os.path.join(path, object_dir)) cam_infos = sorted(cam_infos_unsorted.copy(), key = lambda x : x.image_name) if eval: if train_split: train_dir = os.path.join(path, "images_train") train_names = sorted(os.listdir(train_dir)) train_names = [train_name.split('.')[0] for train_name in train_names] train_cam_infos = [] test_cam_infos = [] for cam_info in cam_infos: if cam_info.image_name in train_names: train_cam_infos.append(cam_info) else: test_cam_infos.append(cam_info) else: train_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold != 0] test_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold == 0] if n_views == 100: pass elif n_views == 50: idx_sub = np.linspace(0, len(train_cam_infos)-1, round(len(train_cam_infos)*0.5)) # 50% views idx_sub = [round(i) for i in idx_sub] train_cam_infos = [train_cam_infos[i_sub] for i_sub in idx_sub] elif isinstance(n_views,int): idx_sub = np.linspace(0, len(train_cam_infos)-1, n_views) # 3views idx_sub = [round(i) for i in idx_sub] train_cam_infos = [train_cam_infos[i_sub] for i_sub in idx_sub] print(train_cam_infos) else: raise NotImplementedError print("Training images: ", len(train_cam_infos)) print("Testing images: ", len(test_cam_infos)) else: if train_split: train_dir = os.path.join(path, "images_train") train_names = sorted(os.listdir(train_dir)) train_names = [train_name.split('.')[0] for train_name in train_names] train_cam_infos = [] for cam_info in cam_infos: if cam_info.image_name in train_names: train_cam_infos.append(cam_info) test_cam_infos = [] else: train_cam_infos = cam_infos test_cam_infos = [] nerf_normalization = getNerfppNorm(train_cam_infos) if random_init: # Since this data set has no colmap data, we start with random points num_pts = 100_000 print(f"Generating random point cloud ({num_pts})...") # We create random points inside the bounds of the synthetic Blender scenes xyz = np.random.random((num_pts, 3)) * 2.6 - 1.3 shs = np.random.random((num_pts, 3)) / 255.0
# Copyright (C) 2023, Gaussian-Grouping # Gaussian-Grouping research group, https://github.com/lkeab/gaussian-grouping # All rights reserved. # # ------------------------------------------------------------------------ # Modified from codes in Gaussian-Splatting # GRAPHDECO research group, https://team.inria.fr/graphdeco class CameraInfo(NamedTuple): uid: int R: np.array T: np.array FovY: np.array FovX: np.array image: np.array image_path: str image_name: str width: int height: int objects: np.array class SceneInfo(NamedTuple): point_cloud: BasicPointCloud train_cameras: list test_cameras: list nerf_normalization: dict ply_path: str def getNerfppNorm(cam_info): def get_center_and_diag(cam_centers): cam_centers = np.hstack(cam_centers) avg_cam_center = np.mean(cam_centers, axis=1, keepdims=True) center = avg_cam_center dist = np.linalg.norm(cam_centers - center, axis=0, keepdims=True) diagonal = np.max(dist) return center.flatten(), diagonal cam_centers = [] for cam in cam_info: W2C = getWorld2View2(cam.R, cam.T) C2W = np.linalg.inv(W2C) cam_centers.append(C2W[:3, 3:4]) center, diagonal = get_center_and_diag(cam_centers) radius = diagonal * 1.1 translate = -center return {"translate": translate, "radius": radius} def readColmapCameras(cam_extrinsics, cam_intrinsics, images_folder, objects_folder): cam_infos = [] for idx, key in enumerate(cam_extrinsics): sys.stdout.write('\r') # the exact output you're looking for: sys.stdout.write("Reading camera {}/{}".format(idx+1, len(cam_extrinsics))) sys.stdout.flush() extr = cam_extrinsics[key] intr = cam_intrinsics[extr.camera_id] height = intr.height width = intr.width uid = intr.id R = np.transpose(qvec2rotmat(extr.qvec)) T = np.array(extr.tvec) if intr.model=="SIMPLE_PINHOLE": focal_length_x = intr.params[0] FovY = focal2fov(focal_length_x, height) FovX = focal2fov(focal_length_x, width) elif intr.model=="PINHOLE": focal_length_x = intr.params[0] focal_length_y = intr.params[1] FovY = focal2fov(focal_length_y, height) FovX = focal2fov(focal_length_x, width) else: assert False, "Colmap camera model not handled: only undistorted datasets (PINHOLE or SIMPLE_PINHOLE cameras) supported!" image_path = os.path.join(images_folder, os.path.basename(extr.name)) image_name = os.path.basename(image_path).split(".")[0] image = Image.open(image_path) if os.path.exists(image_path) else None object_path = os.path.join(objects_folder, image_name + '.png') objects = Image.open(object_path) if os.path.exists(object_path) else None cam_info = CameraInfo(uid=uid, R=R, T=T, FovY=FovY, FovX=FovX, image=image, image_path=image_path, image_name=image_name, width=width, height=height, objects=objects) cam_infos.append(cam_info) sys.stdout.write('\n') return cam_infos def fetchPly(path): plydata = PlyData.read(path) vertices = plydata['vertex'] positions = np.vstack([vertices['x'], vertices['y'], vertices['z']]).T colors = np.vstack([vertices['red'], vertices['green'], vertices['blue']]).T / 255.0 normals = np.vstack([vertices['nx'], vertices['ny'], vertices['nz']]).T return BasicPointCloud(points=positions, colors=colors, normals=normals) def storePly(path, xyz, rgb): # Define the dtype for the structured array dtype = [('x', 'f4'), ('y', 'f4'), ('z', 'f4'), ('nx', 'f4'), ('ny', 'f4'), ('nz', 'f4'), ('red', 'u1'), ('green', 'u1'), ('blue', 'u1')] normals = np.zeros_like(xyz) elements = np.empty(xyz.shape[0], dtype=dtype) attributes = np.concatenate((xyz, normals, rgb), axis=1) elements[:] = list(map(tuple, attributes)) # Create the PlyData object and write to file vertex_element = PlyElement.describe(elements, 'vertex') ply_data = PlyData([vertex_element]) ply_data.write(path) def readColmapSceneInfo(path, images, eval, object_path, llffhold=8, n_views=100, random_init=False, train_split=False): try: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.bin") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.bin") cam_extrinsics = read_extrinsics_binary(cameras_extrinsic_file) cam_intrinsics = read_intrinsics_binary(cameras_intrinsic_file) except: cameras_extrinsic_file = os.path.join(path, "sparse/0", "images.txt") cameras_intrinsic_file = os.path.join(path, "sparse/0", "cameras.txt") cam_extrinsics = read_extrinsics_text(cameras_extrinsic_file) cam_intrinsics = read_intrinsics_text(cameras_intrinsic_file) reading_dir = "images" if images == None else images object_dir = 'object_mask' if object_path == None else object_path cam_infos_unsorted = readColmapCameras(cam_extrinsics=cam_extrinsics, cam_intrinsics=cam_intrinsics, images_folder=os.path.join(path, reading_dir), objects_folder=os.path.join(path, object_dir)) cam_infos = sorted(cam_infos_unsorted.copy(), key = lambda x : x.image_name) if eval: if train_split: train_dir = os.path.join(path, "images_train") train_names = sorted(os.listdir(train_dir)) train_names = [train_name.split('.')[0] for train_name in train_names] train_cam_infos = [] test_cam_infos = [] for cam_info in cam_infos: if cam_info.image_name in train_names: train_cam_infos.append(cam_info) else: test_cam_infos.append(cam_info) else: train_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold != 0] test_cam_infos = [c for idx, c in enumerate(cam_infos) if idx % llffhold == 0] if n_views == 100: pass elif n_views == 50: idx_sub = np.linspace(0, len(train_cam_infos)-1, round(len(train_cam_infos)*0.5)) # 50% views idx_sub = [round(i) for i in idx_sub] train_cam_infos = [train_cam_infos[i_sub] for i_sub in idx_sub] elif isinstance(n_views,int): idx_sub = np.linspace(0, len(train_cam_infos)-1, n_views) # 3views idx_sub = [round(i) for i in idx_sub] train_cam_infos = [train_cam_infos[i_sub] for i_sub in idx_sub] print(train_cam_infos) else: raise NotImplementedError print("Training images: ", len(train_cam_infos)) print("Testing images: ", len(test_cam_infos)) else: if train_split: train_dir = os.path.join(path, "images_train") train_names = sorted(os.listdir(train_dir)) train_names = [train_name.split('.')[0] for train_name in train_names] train_cam_infos = [] for cam_info in cam_infos: if cam_info.image_name in train_names: train_cam_infos.append(cam_info) test_cam_infos = [] else: train_cam_infos = cam_infos test_cam_infos = [] nerf_normalization = getNerfppNorm(train_cam_infos) if random_init: # Since this data set has no colmap data, we start with random points num_pts = 100_000 print(f"Generating random point cloud ({num_pts})...") # We create random points inside the bounds of the synthetic Blender scenes xyz = np.random.random((num_pts, 3)) * 2.6 - 1.3 shs = np.random.random((num_pts, 3)) / 255.0
pcd = BasicPointCloud(points=xyz, colors=SH2RGB(shs), normals=np.zeros((num_pts, 3)))
10
2023-11-28 14:59:15+00:00
8k
Doubiiu/DynamiCrafter
lvdm/modules/networks/openaimodel3d.py
[ { "identifier": "timestep_embedding", "path": "lvdm/models/utils_diffusion.py", "snippet": "def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):\n \"\"\"\n Create sinusoidal timestep embeddings.\n :param timesteps: a 1-D Tensor of N indices, one per batch element.\n ...
from functools import partial from abc import abstractmethod from einops import rearrange from lvdm.models.utils_diffusion import timestep_embedding from lvdm.common import checkpoint from lvdm.basics import ( zero_module, conv_nd, linear, avg_pool_nd, normalization ) from lvdm.modules.attention import SpatialTransformer, TemporalTransformer import torch import torch.nn as nn import torch.nn.functional as F
5,511
TemporalTransformer(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_linear=use_linear, use_checkpoint=use_checkpoint, only_self_att=temporal_self_att_only, causal_attention=use_causal_attention, relative_position=use_relative_position, temporal_length=temporal_length ) ) self.input_blocks.append(TimestepEmbedSequential(*layers)) input_block_chans.append(ch) if level != len(channel_mult) - 1: out_ch = ch self.input_blocks.append( TimestepEmbedSequential( ResBlock(ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, down=True ) if resblock_updown else Downsample(ch, conv_resample, dims=dims, out_channels=out_ch) ) ) ch = out_ch input_block_chans.append(ch) ds *= 2 if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels layers = [ ResBlock(ch, time_embed_dim, dropout, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware, use_temporal_conv=temporal_conv ), SpatialTransformer(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_linear=use_linear, use_checkpoint=use_checkpoint, disable_self_attn=False, video_length=temporal_length, image_cross_attention=self.image_cross_attention,image_cross_attention_scale_learnable=self.image_cross_attention_scale_learnable ) ] if self.temporal_attention: layers.append( TemporalTransformer(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_linear=use_linear, use_checkpoint=use_checkpoint, only_self_att=temporal_self_att_only, causal_attention=use_causal_attention, relative_position=use_relative_position, temporal_length=temporal_length ) ) layers.append( ResBlock(ch, time_embed_dim, dropout, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware, use_temporal_conv=temporal_conv ) ) ## Middle Block self.middle_block = TimestepEmbedSequential(*layers) ## Output Block self.output_blocks = nn.ModuleList([]) for level, mult in list(enumerate(channel_mult))[::-1]: for i in range(num_res_blocks + 1): ich = input_block_chans.pop() layers = [ ResBlock(ch + ich, time_embed_dim, dropout, out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware, use_temporal_conv=temporal_conv ) ] ch = model_channels * mult if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels layers.append( SpatialTransformer(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_linear=use_linear, use_checkpoint=use_checkpoint, disable_self_attn=False, video_length=temporal_length, image_cross_attention=self.image_cross_attention,image_cross_attention_scale_learnable=self.image_cross_attention_scale_learnable ) ) if self.temporal_attention: layers.append( TemporalTransformer(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_linear=use_linear, use_checkpoint=use_checkpoint, only_self_att=temporal_self_att_only, causal_attention=use_causal_attention, relative_position=use_relative_position, temporal_length=temporal_length ) ) if level and i == num_res_blocks: out_ch = ch layers.append( ResBlock(ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, up=True ) if resblock_updown else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) ) ds //= 2 self.output_blocks.append(TimestepEmbedSequential(*layers)) self.out = nn.Sequential( normalization(ch), nn.SiLU(), zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)), ) def forward(self, x, timesteps, context=None, features_adapter=None, fs=None, **kwargs): b,_,t,_,_ = x.shape
class TimestepBlock(nn.Module): """ Any module where forward() takes timestep embeddings as a second argument. """ @abstractmethod def forward(self, x, emb): """ Apply the module to `x` given `emb` timestep embeddings. """ class TimestepEmbedSequential(nn.Sequential, TimestepBlock): """ A sequential module that passes timestep embeddings to the children that support it as an extra input. """ def forward(self, x, emb, context=None, batch_size=None): for layer in self: if isinstance(layer, TimestepBlock): x = layer(x, emb, batch_size=batch_size) elif isinstance(layer, SpatialTransformer): x = layer(x, context) elif isinstance(layer, TemporalTransformer): x = rearrange(x, '(b f) c h w -> b c f h w', b=batch_size) x = layer(x, context) x = rearrange(x, 'b c f h w -> (b f) c h w') else: x = layer(x) return x class Downsample(nn.Module): """ A downsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then downsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims stride = 2 if dims != 3 else (1, 2, 2) if use_conv: self.op = conv_nd( dims, self.channels, self.out_channels, 3, stride=stride, padding=padding ) else: assert self.channels == self.out_channels self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) def forward(self, x): assert x.shape[1] == self.channels return self.op(x) class Upsample(nn.Module): """ An upsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then upsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims if use_conv: self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding) def forward(self, x): assert x.shape[1] == self.channels if self.dims == 3: x = F.interpolate(x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode='nearest') else: x = F.interpolate(x, scale_factor=2, mode='nearest') if self.use_conv: x = self.conv(x) return x class ResBlock(TimestepBlock): """ A residual block that can optionally change the number of channels. :param channels: the number of input channels. :param emb_channels: the number of timestep embedding channels. :param dropout: the rate of dropout. :param out_channels: if specified, the number of out channels. :param use_conv: if True and out_channels is specified, use a spatial convolution instead of a smaller 1x1 convolution to change the channels in the skip connection. :param dims: determines if the signal is 1D, 2D, or 3D. :param up: if True, use this block for upsampling. :param down: if True, use this block for downsampling. :param use_temporal_conv: if True, use the temporal convolution. :param use_image_dataset: if True, the temporal parameters will not be optimized. """ def __init__( self, channels, emb_channels, dropout, out_channels=None, use_scale_shift_norm=False, dims=2, use_checkpoint=False, use_conv=False, up=False, down=False, use_temporal_conv=False, tempspatial_aware=False ): super().__init__() self.channels = channels self.emb_channels = emb_channels self.dropout = dropout self.out_channels = out_channels or channels self.use_conv = use_conv self.use_checkpoint = use_checkpoint self.use_scale_shift_norm = use_scale_shift_norm self.use_temporal_conv = use_temporal_conv self.in_layers = nn.Sequential( normalization(channels), nn.SiLU(), conv_nd(dims, channels, self.out_channels, 3, padding=1), ) self.updown = up or down if up: self.h_upd = Upsample(channels, False, dims) self.x_upd = Upsample(channels, False, dims) elif down: self.h_upd = Downsample(channels, False, dims) self.x_upd = Downsample(channels, False, dims) else: self.h_upd = self.x_upd = nn.Identity() self.emb_layers = nn.Sequential( nn.SiLU(), nn.Linear( emb_channels, 2 * self.out_channels if use_scale_shift_norm else self.out_channels, ), ) self.out_layers = nn.Sequential( normalization(self.out_channels), nn.SiLU(), nn.Dropout(p=dropout), zero_module(nn.Conv2d(self.out_channels, self.out_channels, 3, padding=1)), ) if self.out_channels == channels: self.skip_connection = nn.Identity() elif use_conv: self.skip_connection = conv_nd(dims, channels, self.out_channels, 3, padding=1) else: self.skip_connection = conv_nd(dims, channels, self.out_channels, 1) if self.use_temporal_conv: self.temopral_conv = TemporalConvBlock( self.out_channels, self.out_channels, dropout=0.1, spatial_aware=tempspatial_aware ) def forward(self, x, emb, batch_size=None): """ Apply the block to a Tensor, conditioned on a timestep embedding. :param x: an [N x C x ...] Tensor of features. :param emb: an [N x emb_channels] Tensor of timestep embeddings. :return: an [N x C x ...] Tensor of outputs. """ input_tuple = (x, emb) if batch_size: forward_batchsize = partial(self._forward, batch_size=batch_size) return checkpoint(forward_batchsize, input_tuple, self.parameters(), self.use_checkpoint) return checkpoint(self._forward, input_tuple, self.parameters(), self.use_checkpoint) def _forward(self, x, emb, batch_size=None): if self.updown: in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] h = in_rest(x) h = self.h_upd(h) x = self.x_upd(x) h = in_conv(h) else: h = self.in_layers(x) emb_out = self.emb_layers(emb).type(h.dtype) while len(emb_out.shape) < len(h.shape): emb_out = emb_out[..., None] if self.use_scale_shift_norm: out_norm, out_rest = self.out_layers[0], self.out_layers[1:] scale, shift = torch.chunk(emb_out, 2, dim=1) h = out_norm(h) * (1 + scale) + shift h = out_rest(h) else: h = h + emb_out h = self.out_layers(h) h = self.skip_connection(x) + h if self.use_temporal_conv and batch_size: h = rearrange(h, '(b t) c h w -> b c t h w', b=batch_size) h = self.temopral_conv(h) h = rearrange(h, 'b c t h w -> (b t) c h w') return h class TemporalConvBlock(nn.Module): """ Adapted from modelscope: https://github.com/modelscope/modelscope/blob/master/modelscope/models/multi_modal/video_synthesis/unet_sd.py """ def __init__(self, in_channels, out_channels=None, dropout=0.0, spatial_aware=False): super(TemporalConvBlock, self).__init__() if out_channels is None: out_channels = in_channels self.in_channels = in_channels self.out_channels = out_channels th_kernel_shape = (3, 1, 1) if not spatial_aware else (3, 3, 1) th_padding_shape = (1, 0, 0) if not spatial_aware else (1, 1, 0) tw_kernel_shape = (3, 1, 1) if not spatial_aware else (3, 1, 3) tw_padding_shape = (1, 0, 0) if not spatial_aware else (1, 0, 1) # conv layers self.conv1 = nn.Sequential( nn.GroupNorm(32, in_channels), nn.SiLU(), nn.Conv3d(in_channels, out_channels, th_kernel_shape, padding=th_padding_shape)) self.conv2 = nn.Sequential( nn.GroupNorm(32, out_channels), nn.SiLU(), nn.Dropout(dropout), nn.Conv3d(out_channels, in_channels, tw_kernel_shape, padding=tw_padding_shape)) self.conv3 = nn.Sequential( nn.GroupNorm(32, out_channels), nn.SiLU(), nn.Dropout(dropout), nn.Conv3d(out_channels, in_channels, th_kernel_shape, padding=th_padding_shape)) self.conv4 = nn.Sequential( nn.GroupNorm(32, out_channels), nn.SiLU(), nn.Dropout(dropout), nn.Conv3d(out_channels, in_channels, tw_kernel_shape, padding=tw_padding_shape)) # zero out the last layer params,so the conv block is identity nn.init.zeros_(self.conv4[-1].weight) nn.init.zeros_(self.conv4[-1].bias) def forward(self, x): identity = x x = self.conv1(x) x = self.conv2(x) x = self.conv3(x) x = self.conv4(x) return identity + x class UNetModel(nn.Module): """ The full UNet model with attention and timestep embedding. :param in_channels: in_channels in the input Tensor. :param model_channels: base channel count for the model. :param out_channels: channels in the output Tensor. :param num_res_blocks: number of residual blocks per downsample. :param attention_resolutions: a collection of downsample rates at which attention will take place. May be a set, list, or tuple. For example, if this contains 4, then at 4x downsampling, attention will be used. :param dropout: the dropout probability. :param channel_mult: channel multiplier for each level of the UNet. :param conv_resample: if True, use learned convolutions for upsampling and downsampling. :param dims: determines if the signal is 1D, 2D, or 3D. :param num_classes: if specified (as an int), then this model will be class-conditional with `num_classes` classes. :param use_checkpoint: use gradient checkpointing to reduce memory usage. :param num_heads: the number of attention heads in each attention layer. :param num_heads_channels: if specified, ignore num_heads and instead use a fixed channel width per attention head. :param num_heads_upsample: works with num_heads to set a different number of heads for upsampling. Deprecated. :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. :param resblock_updown: use residual blocks for up/downsampling. :param use_new_attention_order: use a different attention pattern for potentially increased efficiency. """ def __init__(self, in_channels, model_channels, out_channels, num_res_blocks, attention_resolutions, dropout=0.0, channel_mult=(1, 2, 4, 8), conv_resample=True, dims=2, context_dim=None, use_scale_shift_norm=False, resblock_updown=False, num_heads=-1, num_head_channels=-1, transformer_depth=1, use_linear=False, use_checkpoint=False, temporal_conv=False, tempspatial_aware=False, temporal_attention=True, use_relative_position=True, use_causal_attention=False, temporal_length=None, use_fp16=False, addition_attention=False, temporal_selfatt_only=True, image_cross_attention=False, image_cross_attention_scale_learnable=False, default_fs=4, fs_condition=False, ): super(UNetModel, self).__init__() if num_heads == -1: assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' if num_head_channels == -1: assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' self.in_channels = in_channels self.model_channels = model_channels self.out_channels = out_channels self.num_res_blocks = num_res_blocks self.attention_resolutions = attention_resolutions self.dropout = dropout self.channel_mult = channel_mult self.conv_resample = conv_resample self.temporal_attention = temporal_attention time_embed_dim = model_channels * 4 self.use_checkpoint = use_checkpoint self.dtype = torch.float16 if use_fp16 else torch.float32 temporal_self_att_only = True self.addition_attention = addition_attention self.temporal_length = temporal_length self.image_cross_attention = image_cross_attention self.image_cross_attention_scale_learnable = image_cross_attention_scale_learnable self.default_fs = default_fs self.fs_condition = fs_condition ## Time embedding blocks self.time_embed = nn.Sequential( linear(model_channels, time_embed_dim), nn.SiLU(), linear(time_embed_dim, time_embed_dim), ) if fs_condition: self.framestride_embed = nn.Sequential( linear(model_channels, time_embed_dim), nn.SiLU(), linear(time_embed_dim, time_embed_dim), ) nn.init.zeros_(self.framestride_embed[-1].weight) nn.init.zeros_(self.framestride_embed[-1].bias) ## Input Block self.input_blocks = nn.ModuleList( [ TimestepEmbedSequential(conv_nd(dims, in_channels, model_channels, 3, padding=1)) ] ) if self.addition_attention: self.init_attn=TimestepEmbedSequential( TemporalTransformer( model_channels, n_heads=8, d_head=num_head_channels, depth=transformer_depth, context_dim=context_dim, use_checkpoint=use_checkpoint, only_self_att=temporal_selfatt_only, causal_attention=False, relative_position=use_relative_position, temporal_length=temporal_length)) input_block_chans = [model_channels] ch = model_channels ds = 1 for level, mult in enumerate(channel_mult): for _ in range(num_res_blocks): layers = [ ResBlock(ch, time_embed_dim, dropout, out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware, use_temporal_conv=temporal_conv ) ] ch = mult * model_channels if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels layers.append( SpatialTransformer(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_linear=use_linear, use_checkpoint=use_checkpoint, disable_self_attn=False, video_length=temporal_length, image_cross_attention=self.image_cross_attention, image_cross_attention_scale_learnable=self.image_cross_attention_scale_learnable, ) ) if self.temporal_attention: layers.append( TemporalTransformer(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_linear=use_linear, use_checkpoint=use_checkpoint, only_self_att=temporal_self_att_only, causal_attention=use_causal_attention, relative_position=use_relative_position, temporal_length=temporal_length ) ) self.input_blocks.append(TimestepEmbedSequential(*layers)) input_block_chans.append(ch) if level != len(channel_mult) - 1: out_ch = ch self.input_blocks.append( TimestepEmbedSequential( ResBlock(ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, down=True ) if resblock_updown else Downsample(ch, conv_resample, dims=dims, out_channels=out_ch) ) ) ch = out_ch input_block_chans.append(ch) ds *= 2 if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels layers = [ ResBlock(ch, time_embed_dim, dropout, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware, use_temporal_conv=temporal_conv ), SpatialTransformer(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_linear=use_linear, use_checkpoint=use_checkpoint, disable_self_attn=False, video_length=temporal_length, image_cross_attention=self.image_cross_attention,image_cross_attention_scale_learnable=self.image_cross_attention_scale_learnable ) ] if self.temporal_attention: layers.append( TemporalTransformer(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_linear=use_linear, use_checkpoint=use_checkpoint, only_self_att=temporal_self_att_only, causal_attention=use_causal_attention, relative_position=use_relative_position, temporal_length=temporal_length ) ) layers.append( ResBlock(ch, time_embed_dim, dropout, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware, use_temporal_conv=temporal_conv ) ) ## Middle Block self.middle_block = TimestepEmbedSequential(*layers) ## Output Block self.output_blocks = nn.ModuleList([]) for level, mult in list(enumerate(channel_mult))[::-1]: for i in range(num_res_blocks + 1): ich = input_block_chans.pop() layers = [ ResBlock(ch + ich, time_embed_dim, dropout, out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, tempspatial_aware=tempspatial_aware, use_temporal_conv=temporal_conv ) ] ch = model_channels * mult if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels layers.append( SpatialTransformer(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_linear=use_linear, use_checkpoint=use_checkpoint, disable_self_attn=False, video_length=temporal_length, image_cross_attention=self.image_cross_attention,image_cross_attention_scale_learnable=self.image_cross_attention_scale_learnable ) ) if self.temporal_attention: layers.append( TemporalTransformer(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, use_linear=use_linear, use_checkpoint=use_checkpoint, only_self_att=temporal_self_att_only, causal_attention=use_causal_attention, relative_position=use_relative_position, temporal_length=temporal_length ) ) if level and i == num_res_blocks: out_ch = ch layers.append( ResBlock(ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, up=True ) if resblock_updown else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) ) ds //= 2 self.output_blocks.append(TimestepEmbedSequential(*layers)) self.out = nn.Sequential( normalization(ch), nn.SiLU(), zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)), ) def forward(self, x, timesteps, context=None, features_adapter=None, fs=None, **kwargs): b,_,t,_,_ = x.shape
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).type(x.dtype)
0
2023-11-27 12:34:23+00:00
8k
dvlab-research/LLMGA
llmga/llava/train/train.py
[ { "identifier": "IGNORE_INDEX", "path": "llmga/llava/constants.py", "snippet": "IGNORE_INDEX = -100" }, { "identifier": "IMAGE_TOKEN_INDEX", "path": "llmga/llava/constants.py", "snippet": "IMAGE_TOKEN_INDEX = -200" }, { "identifier": "DEFAULT_IMAGE_TOKEN", "path": "llmga/llav...
import os import copy import json import logging import pathlib import torch import transformers import random import numpy as np import lmdb import io import pytextrank from dataclasses import dataclass, field from typing import Dict, Optional, Sequence, List from llmga.llava.constants import IGNORE_INDEX, IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, \ DEFAULT_IM_END_TOKEN, DEFAULT_OUTPUT_START_TOKEN, DEFAULT_OUTPUT_END_TOKEN from torch.utils.data import Dataset from llmga.llava.train.llava_trainer import LLaVATrainer from llmga.llava import conversation as conversation_lib from llmga.llava.model import * from llmga.llava.mm_utils import tokenizer_image_token from PIL import Image from llmga.llava.masks.make_mask import get_mask_generator from llmga.llava.prompt_temp import outpaint_prompt, inpaint_prompt, textextend_prompt, regen_prompt, ques_prompt, \ textextend_prompt2 from torchvision import transforms from deepspeed import zero from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus from transformers import BitsAndBytesConfig from peft import prepare_model_for_kbit_training from peft import LoraConfig, get_peft_model from peft.tuners.lora import LoraLayer
4,448
class LazySupervisedDataset(Dataset): """Dataset for supervised fine-tuning.""" def __init__(self, data_path: str, data_path2: str, data_path3: str, tokenizer: transformers.PreTrainedTokenizer, data_args: DataArguments): super(LazySupervisedDataset, self).__init__() self.data_args = data_args list_vqa_dict = json.load(open(data_path, "r")) data_path3_1 = os.path.join(data_path3, "lmdb_train-00000-of-00002.json") data_path3_2 = os.path.join(data_path3, "lmdb_train-00001-of-00002.json") list_aes_1_dict = json.load(open(data_path3_1, "r")) list_aes_2_dict = json.load(open(data_path3_2, "r")) with open(os.path.join(self.data_args.image_folder2, "laion_3m_prompt.json"), 'r', encoding='utf-8') as fr: self.prompt_dict_ori = json.load(fr) list_coco_dict = json.load(open(os.path.join(data_path2, "train.json"), "r")) rank0_print("Formatting inputs...Skip in lazy mode") self.tokenizer = tokenizer self.list_vqa_dict = list_vqa_dict self.list_coco_dict = list_coco_dict self.list_aes_1_dict = list_aes_1_dict self.list_aes_2_dict = list_aes_2_dict self.len1 = len(self.list_vqa_dict) self.len_vqa = len(self.list_vqa_dict) self.len_coco = len(self.list_coco_dict) self.len_aes_1 = len(self.list_aes_1_dict) self.len_aes_2 = len(self.list_aes_2_dict) self.txn1 = LoadImageFromLmdb(os.path.join(self.data_args.image_folder2, "lmdb_train-00000-of-00002")) self.txn2 = LoadImageFromLmdb(os.path.join(self.data_args.image_folder2, "lmdb_train-00001-of-00002")) self.len_aes = self.len_aes_1 + self.len_aes_2 self.ratio_aes = self.len_aes / (self.len_coco + self.len_aes) self.gen_mask = get_mask_generator() self.len1 = int(1 * self.len1) self.len2 = int(1 * self.len1) self.len3 = int(1 * self.len1) self.len4 = int(1 * self.len1) def get_dataset_cocov2(self): ii = random.randint(0, self.len_coco - 1) coco = self.list_coco_dict[ii] conversations = [{"from": "human", "value": random.choice(ques_prompt)}, {"from": "gpt", "value": coco["caption"]}] tp = {'image': "%012d.jpg" % (coco["image_id"]), "conversations": conversations} return tp, coco def get_dataset_coco(self): ii = random.randint(0, self.len_coco - 1) coco = self.list_coco_dict[ii] image_folder = self.data_args.image_folder conversations = [{"from": "human", "value": random.choice(ques_prompt)}, {"from": "gpt", "value": coco["caption"]}] tp = {'image': "%012d.jpg" % (coco["image_id"]), "conversations": conversations} return tp, image_folder def get_dataset_aes(self): ii = random.randint(0, self.len_aes_1 + self.len_aes_2 - 1) if ii < self.len_aes_1: return self.list_aes_1_dict[ii].copy(), self.txn1 else: return self.list_aes_2_dict[ii - self.len_aes_1].copy(), self.txn2 def __len__(self): return self.len1 + self.len2 + self.len3 + self.len4 def __getitem__(self, i) -> Dict[str, torch.Tensor]: has_img = True txn = None if i < self.len1: # vqa ii = random.randint(0, self.len1 - 1) tp = self.list_vqa_dict[ii].copy() image_folder = self.data_args.image_folder elif i < self.len1 + self.len2: # inpainting, outpainting if random.random() < self.ratio_aes: tp, txn = self.get_dataset_aes() else: tp, image_folder = self.get_dataset_coco() elif i < self.len1 + self.len2 + self.len3: # similar image generation if random.random() < self.ratio_aes: tp, txn = self.get_dataset_aes() else: tp, image_folder = self.get_dataset_coco() if random.random() < 0.5: # generate image tp["conversations"][0]["value"] = DEFAULT_IMAGE_TOKEN + "\n" + random.choice(regen_prompt) if self.data_args.mm_use_output_start_end: tp["conversations"][1]["value"] = DEFAULT_OUTPUT_START_TOKEN + " " + tp["conversations"][1][ "value"] + " " + DEFAULT_OUTPUT_END_TOKEN else: # describe image tp["conversations"][0]["value"] = DEFAULT_IMAGE_TOKEN + "\n" + random.choice(ques_prompt) else: # prompt refinement if random.random() < self.ratio_aes: tp, txn = self.get_dataset_aes() else: tp, coco = self.get_dataset_cocov2() has_img = False if not has_img: if txn is not None: text_complete = self.prompt_dict_ori[tp['image']] else: text_complete = coco["coco_caption"] _ = tp.pop('image') if random.random() < 0.5: # description tp_prompt = textextend_prompt2 is_generation = False else: # generation
# Adopted from https://github.com/lm-sys/FastChat. Below is the original copyright: # Adopted from tatsu-lab@stanford_alpaca. Below is the original copyright: # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import spacy local_rank = None def rank0_print(*args): if local_rank == 0: print(*args) class LoadImageFromLmdb(object): def __init__(self, lmdb_path): self.lmdb_path = lmdb_path self.txn = None def __call__(self, key): if self.txn is None: env = lmdb.open(self.lmdb_path, max_readers=4, readonly=True, lock=False, readahead=True, meminit=False) self.txn = env.begin(write=False) image_buf = self.txn.get(key.encode()) with Image.open(io.BytesIO(image_buf)) as image: if image.mode == "RGBA" or image.info.get("transparency", None) is not None: image = image.convert("RGBA") white = Image.new(mode="RGB", size=image.size, color=(255, 255, 255)) white.paste(image, mask=image.split()[3]) image = white else: image = image.convert("RGB") return image @dataclass class ModelArguments: model_name_or_path: Optional[str] = field(default="facebook/opt-125m") version: Optional[str] = field(default="v0") freeze_backbone: bool = field(default=False) tune_mm_mlp_adapter: bool = field(default=False) vision_tower: Optional[str] = field(default=None) mm_vision_select_layer: Optional[int] = field(default=-1) # default to the last layer pretrain_mm_mlp_adapter: Optional[str] = field(default=None) mm_use_output_start_end: bool = field(default=True) mm_use_im_start_end: bool = field(default=False) mm_use_im_patch_token: bool = field(default=True) mm_vision_select_feature: Optional[str] = field(default="patch") @dataclass class DataArguments: data_path: str = field(default=None, metadata={"help": "Path to the training data."}) data_path2: str = field(default=None, metadata={"help": "Path to the training data."}) data_path3: str = field(default=None, metadata={"help": "Path to the training data."}) lazy_preprocess: bool = False is_multimodal: bool = False image_folder: Optional[str] = field(default=None) image_folder2: Optional[str] = field(default=None) image_aspect_ratio: str = 'square' image_grid_pinpoints: Optional[str] = field(default=None) @dataclass class TrainingArguments(transformers.TrainingArguments): cache_dir: Optional[str] = field(default=None) optim: str = field(default="adamw_torch") remove_unused_columns: bool = field(default=False) freeze_mm_mlp_adapter: bool = field(default=False) mpt_attn_impl: Optional[str] = field(default="triton") model_max_length: int = field( default=512, metadata={ "help": "Maximum sequence length. Sequences will be right padded (and possibly truncated)." }, ) double_quant: bool = field( default=True, metadata={"help": "Compress the quantization statistics through double quantization."} ) quant_type: str = field( default="nf4", metadata={"help": "Quantization data type to use. Should be one of `fp4` or `nf4`."} ) bits: int = field( default=16, metadata={"help": "How many bits to use."} ) lora_enable: bool = False lora_r: int = 64 lora_alpha: int = 16 lora_dropout: float = 0.05 lora_weight_path: str = "" lora_bias: str = "none" def maybe_zero_3(param, ignore_status=False, name=None): if hasattr(param, "ds_id"): if param.ds_status == ZeroParamStatus.NOT_AVAILABLE: if not ignore_status: logging.warning(f"{name}: param.ds_status != ZeroParamStatus.NOT_AVAILABLE: {param.ds_status}") with zero.GatheredParameters([param]): param = param.data.detach().cpu().clone() else: param = param.detach().cpu().clone() return param # Borrowed from peft.utils.get_peft_model_state_dict def get_peft_state_maybe_zero_3(named_params, bias): if bias == "none": to_return = {k: t for k, t in named_params if "lora_" in k} elif bias == "all": to_return = {k: t for k, t in named_params if "lora_" in k or "bias" in k} elif bias == "lora_only": to_return = {} maybe_lora_bias = {} lora_bias_names = set() for k, t in named_params: if "lora_" in k: to_return[k] = t bias_name = k.split("lora_")[0] + "bias" lora_bias_names.add(bias_name) elif "bias" in k: maybe_lora_bias[k] = t for k, t in maybe_lora_bias: if bias_name in lora_bias_names: to_return[bias_name] = t else: raise NotImplementedError to_return = {k: maybe_zero_3(v, name=k) for k, v in to_return.items()} return to_return def get_peft_state_non_lora_maybe_zero_3(named_params, require_grad_only=True): to_return = {k: t for k, t in named_params if "lora_" not in k} if require_grad_only: to_return = {k: t for k, t in to_return.items() if t.requires_grad} to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} return to_return def get_mm_adapter_state_maybe_zero_3(named_params, keys_to_match): to_return = {k: t for k, t in named_params if any(key_match in k for key_match in keys_to_match)} to_return = {k: maybe_zero_3(v, ignore_status=True).cpu() for k, v in to_return.items()} return to_return def find_all_linear_names(model): cls = torch.nn.Linear lora_module_names = set() for name, module in model.named_modules(): if isinstance(module, cls): names = name.split('.') lora_module_names.add(names[0] if len(names) == 1 else names[-1]) if 'lm_head' in lora_module_names: # needed for 16-bit lora_module_names.remove('lm_head') return list(lora_module_names) def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): """Collects the state dict and dump to disk.""" if getattr(trainer.args, "tune_mm_mlp_adapter", False): # Only save Adapter keys_to_match = ['mm_projector'] if getattr(trainer.args, "use_im_start_end", False): keys_to_match.extend(['embed_tokens', 'embed_in']) if getattr(trainer.args, "use_output_start_end", False): keys_to_match.extend(['embed_tokens', 'embed_in']) weight_to_save = get_mm_adapter_state_maybe_zero_3(trainer.model.named_parameters(), keys_to_match) trainer.model.config.save_pretrained(output_dir) current_folder = output_dir.split('/')[-1] parent_folder = os.path.dirname(output_dir) if trainer.args.local_rank == 0 or trainer.args.local_rank == -1: if current_folder.startswith('checkpoint-'): mm_projector_folder = os.path.join(parent_folder, "mm_projector") os.makedirs(mm_projector_folder, exist_ok=True) torch.save(weight_to_save, os.path.join(mm_projector_folder, f'{current_folder}.bin')) else: torch.save(weight_to_save, os.path.join(output_dir, f'mm_projector.bin')) return if trainer.deepspeed: torch.cuda.synchronize() trainer.save_model(output_dir) return state_dict = trainer.model.state_dict() if trainer.args.should_save: cpu_state_dict = { key: value.cpu() for key, value in state_dict.items() } del state_dict trainer._save(output_dir, state_dict=cpu_state_dict) # noqa def smart_tokenizer_and_embedding_resize( special_tokens_dict: Dict, tokenizer: transformers.PreTrainedTokenizer, model: transformers.PreTrainedModel, ): """Resize tokenizer and embedding. Note: This is the unoptimized version that may make your embedding size not be divisible by 64. """ num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict) model.resize_token_embeddings(len(tokenizer)) if num_new_tokens > 0: input_embeddings = model.get_input_embeddings().weight.data output_embeddings = model.get_output_embeddings().weight.data input_embeddings_avg = input_embeddings[:-num_new_tokens].mean( dim=0, keepdim=True) output_embeddings_avg = output_embeddings[:-num_new_tokens].mean( dim=0, keepdim=True) input_embeddings[-num_new_tokens:] = input_embeddings_avg output_embeddings[-num_new_tokens:] = output_embeddings_avg def _tokenize_fn(strings: Sequence[str], tokenizer: transformers.PreTrainedTokenizer) -> Dict: """Tokenize a list of strings.""" tokenized_list = [ tokenizer( text, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ) for text in strings ] input_ids = labels = [ tokenized.input_ids[0] for tokenized in tokenized_list ] input_ids_lens = labels_lens = [ tokenized.input_ids.ne(tokenizer.pad_token_id).sum().item() for tokenized in tokenized_list ] return dict( input_ids=input_ids, labels=labels, input_ids_lens=input_ids_lens, labels_lens=labels_lens, ) def _mask_targets(target, tokenized_lens, speakers): # cur_idx = 0 cur_idx = tokenized_lens[0] tokenized_lens = tokenized_lens[1:] target[:cur_idx] = IGNORE_INDEX for tokenized_len, speaker in zip(tokenized_lens, speakers): if speaker == "human": target[cur_idx + 2:cur_idx + tokenized_len] = IGNORE_INDEX cur_idx += tokenized_len def _add_speaker_and_signal(header, source, get_conversation=True): """Add speaker and start/end signal on each round.""" BEGIN_SIGNAL = "### " END_SIGNAL = "\n" conversation = header for sentence in source: from_str = sentence["from"] if from_str.lower() == "human": from_str = conversation_lib.default_conversation.roles[0] elif from_str.lower() == "gpt": from_str = conversation_lib.default_conversation.roles[1] else: from_str = 'unknown' sentence["value"] = (BEGIN_SIGNAL + from_str + ": " + sentence["value"] + END_SIGNAL) if get_conversation: conversation += sentence["value"] conversation += BEGIN_SIGNAL return conversation def preprocess_multimodal( sources: Sequence[str], data_args: DataArguments ) -> Dict: is_multimodal = data_args.is_multimodal if not is_multimodal: return sources for source in sources: for sentence in source: if DEFAULT_IMAGE_TOKEN in sentence['value']: sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '').strip() sentence['value'] = DEFAULT_IMAGE_TOKEN + '\n' + sentence['value'] sentence['value'] = sentence['value'].strip() if "mmtag" in conversation_lib.default_conversation.version: sentence['value'] = sentence['value'].replace(DEFAULT_IMAGE_TOKEN, '<Image>' + DEFAULT_IMAGE_TOKEN + '</Image>') replace_token = DEFAULT_IMAGE_TOKEN if data_args.mm_use_im_start_end: replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN sentence["value"] = sentence["value"].replace(DEFAULT_IMAGE_TOKEN, replace_token) return sources def preprocess_llama_2( sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False ) -> Dict: conv = conversation_lib.default_conversation.copy() roles = {"human": conv.roles[0], "gpt": conv.roles[1]} # Apply prompt templates conversations = [] for i, source in enumerate(sources): if roles[source[0]["from"]] != conv.roles[0]: # Skip the first one if it is not from human source = source[1:] conv.messages = [] for j, sentence in enumerate(source): role = roles[sentence["from"]] assert role == conv.roles[j % 2], f"{i}" conv.append_message(role, sentence["value"]) conversations.append(conv.get_prompt()) # Tokenize conversations if has_image: input_ids = torch.stack( [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) else: input_ids = tokenizer( conversations, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ).input_ids targets = input_ids.clone() assert conv.sep_style == conversation_lib.SeparatorStyle.LLAMA_2 # Mask targets sep = "[/INST] " for conversation, target in zip(conversations, targets): total_len = int(target.ne(tokenizer.pad_token_id).sum()) rounds = conversation.split(conv.sep2) cur_len = 1 target[:cur_len] = IGNORE_INDEX for i, rou in enumerate(rounds): if rou == "": break parts = rou.split(sep) if len(parts) != 2: break parts[0] += sep if has_image: round_len = len(tokenizer_image_token(rou, tokenizer)) instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 else: round_len = len(tokenizer(rou).input_ids) instruction_len = len(tokenizer(parts[0]).input_ids) - 2 target[cur_len: cur_len + instruction_len] = IGNORE_INDEX cur_len += round_len target[cur_len:] = IGNORE_INDEX if cur_len < tokenizer.model_max_length: if cur_len != total_len: target[:] = IGNORE_INDEX print( f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)" ) return dict( input_ids=input_ids, labels=targets, ) def preprocess_v1( sources, tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False ) -> Dict: conv = conversation_lib.default_conversation.copy() roles = {"human": conv.roles[0], "gpt": conv.roles[1]} # Apply prompt templates conversations = [] for i, source in enumerate(sources): if roles[source[0]["from"]] != conv.roles[0]: # Skip the first one if it is not from human source = source[1:] conv.messages = [] for j, sentence in enumerate(source): role = roles[sentence["from"]] assert role == conv.roles[j % 2], f"{i}" conv.append_message(role, sentence["value"]) conversations.append(conv.get_prompt()) # Tokenize conversations if has_image: input_ids = torch.stack( [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) else: input_ids = tokenizer( conversations, return_tensors="pt", padding="longest", max_length=tokenizer.model_max_length, truncation=True, ).input_ids targets = input_ids.clone() assert conv.sep_style == conversation_lib.SeparatorStyle.TWO # Mask targets sep = conv.sep + conv.roles[1] + ": " for conversation, target in zip(conversations, targets): total_len = int(target.ne(tokenizer.pad_token_id).sum()) rounds = conversation.split(conv.sep2) cur_len = 1 target[:cur_len] = IGNORE_INDEX for i, rou in enumerate(rounds): if rou == "": break parts = rou.split(sep) if len(parts) != 2: break parts[0] += sep if has_image: round_len = len(tokenizer_image_token(rou, tokenizer)) instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) - 2 else: round_len = len(tokenizer(rou).input_ids) instruction_len = len(tokenizer(parts[0]).input_ids) - 2 target[cur_len: cur_len + instruction_len] = IGNORE_INDEX cur_len += round_len target[cur_len:] = IGNORE_INDEX if cur_len < tokenizer.model_max_length: if cur_len != total_len: target[:] = IGNORE_INDEX print( f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)" ) return dict( input_ids=input_ids, labels=targets, ) def preprocess_mpt( sources, tokenizer: transformers.PreTrainedTokenizer, ) -> Dict: conv = conversation_lib.default_conversation.copy() roles = {"human": conv.roles[0], "gpt": conv.roles[1]} # Apply prompt templates conversations = [] for i, source in enumerate(sources): if roles[source[0]["from"]] != conv.roles[0]: # Skip the first one if it is not from human source = source[1:] conv.messages = [] for j, sentence in enumerate(source): role = roles[sentence["from"]] assert role == conv.roles[j % 2], f"{i}" conv.append_message(role, sentence["value"]) conversations.append(conv.get_prompt()) # Tokenize conversations input_ids = torch.stack([tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations], dim=0) targets = input_ids.clone() assert conv.sep_style == conversation_lib.SeparatorStyle.MPT # Mask targets sep = conv.sep + conv.roles[1] for conversation, target in zip(conversations, targets): total_len = int(target.ne(tokenizer.pad_token_id).sum()) rounds = conversation.split(conv.sep) re_rounds = [conv.sep.join(rounds[:3])] # system + user + gpt for conv_idx in range(3, len(rounds), 2): re_rounds.append(conv.sep.join(rounds[conv_idx:conv_idx + 2])) # user + gpt cur_len = 0 target[:cur_len] = IGNORE_INDEX for i, rou in enumerate(re_rounds): if rou == "": break parts = rou.split(sep) if len(parts) != 2: break parts[0] += sep round_len = len(tokenizer_image_token(rou, tokenizer)) + len(tokenizer_image_token(conv.sep, tokenizer)) instruction_len = len(tokenizer_image_token(parts[0], tokenizer)) target[cur_len: cur_len + instruction_len] = IGNORE_INDEX cur_len += round_len target[cur_len:] = IGNORE_INDEX if cur_len < tokenizer.model_max_length: if cur_len != total_len: target[:] = IGNORE_INDEX print( f"WARNING: tokenization mismatch: {cur_len} vs. {total_len}." f" (ignored)" ) return dict( input_ids=input_ids, labels=targets, ) def preprocess_plain( sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, ) -> Dict: # add end signal and concatenate together conversations = [] for source in sources: assert len(source) == 2 assert DEFAULT_IMAGE_TOKEN in source[0]['value'] source[0]['value'] = DEFAULT_IMAGE_TOKEN conversation = source[0]['value'] + source[1]['value'] + conversation_lib.default_conversation.sep conversations.append(conversation) # tokenize conversations input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] targets = copy.deepcopy(input_ids) for target, source in zip(targets, sources): tokenized_len = len(tokenizer_image_token(source[0]['value'], tokenizer)) target[:tokenized_len] = IGNORE_INDEX return dict(input_ids=input_ids, labels=targets) def preprocess( sources: Sequence[str], tokenizer: transformers.PreTrainedTokenizer, has_image: bool = False ) -> Dict: """ Given a list of sources, each is a conversation list. This transform: 1. Add signal '### ' at the beginning each sentence, with end signal '\n'; 2. Concatenate conversations together; 3. Tokenize the concatenated conversation; 4. Make a deepcopy as the target. Mask human words with IGNORE_INDEX. """ if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.PLAIN: return preprocess_plain(sources, tokenizer) if conversation_lib.default_conversation.sep_style == conversation_lib.SeparatorStyle.LLAMA_2: return preprocess_llama_2(sources, tokenizer, has_image=has_image) if conversation_lib.default_conversation.version.startswith("v1"): return preprocess_v1(sources, tokenizer, has_image=has_image) if conversation_lib.default_conversation.version == "mpt": return preprocess_mpt(sources, tokenizer) # add end signal and concatenate together conversations = [] for source in sources: header = f"{conversation_lib.default_conversation.system}\n\n" conversation = _add_speaker_and_signal(header, source) conversations.append(conversation) # tokenize conversations def get_tokenize_len(prompts): return [len(tokenizer_image_token(prompt, tokenizer)) for prompt in prompts] if has_image: input_ids = [tokenizer_image_token(prompt, tokenizer, return_tensors='pt') for prompt in conversations] else: conversations_tokenized = _tokenize_fn(conversations, tokenizer) input_ids = conversations_tokenized["input_ids"] targets = copy.deepcopy(input_ids) for target, source in zip(targets, sources): if has_image: tokenized_lens = get_tokenize_len([header] + [s["value"] for s in source]) else: tokenized_lens = _tokenize_fn([header] + [s["value"] for s in source], tokenizer)["input_ids_lens"] speakers = [sentence["from"] for sentence in source] _mask_targets(target, tokenized_lens, speakers) return dict(input_ids=input_ids, labels=targets) class LazySupervisedDataset(Dataset): """Dataset for supervised fine-tuning.""" def __init__(self, data_path: str, data_path2: str, data_path3: str, tokenizer: transformers.PreTrainedTokenizer, data_args: DataArguments): super(LazySupervisedDataset, self).__init__() self.data_args = data_args list_vqa_dict = json.load(open(data_path, "r")) data_path3_1 = os.path.join(data_path3, "lmdb_train-00000-of-00002.json") data_path3_2 = os.path.join(data_path3, "lmdb_train-00001-of-00002.json") list_aes_1_dict = json.load(open(data_path3_1, "r")) list_aes_2_dict = json.load(open(data_path3_2, "r")) with open(os.path.join(self.data_args.image_folder2, "laion_3m_prompt.json"), 'r', encoding='utf-8') as fr: self.prompt_dict_ori = json.load(fr) list_coco_dict = json.load(open(os.path.join(data_path2, "train.json"), "r")) rank0_print("Formatting inputs...Skip in lazy mode") self.tokenizer = tokenizer self.list_vqa_dict = list_vqa_dict self.list_coco_dict = list_coco_dict self.list_aes_1_dict = list_aes_1_dict self.list_aes_2_dict = list_aes_2_dict self.len1 = len(self.list_vqa_dict) self.len_vqa = len(self.list_vqa_dict) self.len_coco = len(self.list_coco_dict) self.len_aes_1 = len(self.list_aes_1_dict) self.len_aes_2 = len(self.list_aes_2_dict) self.txn1 = LoadImageFromLmdb(os.path.join(self.data_args.image_folder2, "lmdb_train-00000-of-00002")) self.txn2 = LoadImageFromLmdb(os.path.join(self.data_args.image_folder2, "lmdb_train-00001-of-00002")) self.len_aes = self.len_aes_1 + self.len_aes_2 self.ratio_aes = self.len_aes / (self.len_coco + self.len_aes) self.gen_mask = get_mask_generator() self.len1 = int(1 * self.len1) self.len2 = int(1 * self.len1) self.len3 = int(1 * self.len1) self.len4 = int(1 * self.len1) def get_dataset_cocov2(self): ii = random.randint(0, self.len_coco - 1) coco = self.list_coco_dict[ii] conversations = [{"from": "human", "value": random.choice(ques_prompt)}, {"from": "gpt", "value": coco["caption"]}] tp = {'image': "%012d.jpg" % (coco["image_id"]), "conversations": conversations} return tp, coco def get_dataset_coco(self): ii = random.randint(0, self.len_coco - 1) coco = self.list_coco_dict[ii] image_folder = self.data_args.image_folder conversations = [{"from": "human", "value": random.choice(ques_prompt)}, {"from": "gpt", "value": coco["caption"]}] tp = {'image': "%012d.jpg" % (coco["image_id"]), "conversations": conversations} return tp, image_folder def get_dataset_aes(self): ii = random.randint(0, self.len_aes_1 + self.len_aes_2 - 1) if ii < self.len_aes_1: return self.list_aes_1_dict[ii].copy(), self.txn1 else: return self.list_aes_2_dict[ii - self.len_aes_1].copy(), self.txn2 def __len__(self): return self.len1 + self.len2 + self.len3 + self.len4 def __getitem__(self, i) -> Dict[str, torch.Tensor]: has_img = True txn = None if i < self.len1: # vqa ii = random.randint(0, self.len1 - 1) tp = self.list_vqa_dict[ii].copy() image_folder = self.data_args.image_folder elif i < self.len1 + self.len2: # inpainting, outpainting if random.random() < self.ratio_aes: tp, txn = self.get_dataset_aes() else: tp, image_folder = self.get_dataset_coco() elif i < self.len1 + self.len2 + self.len3: # similar image generation if random.random() < self.ratio_aes: tp, txn = self.get_dataset_aes() else: tp, image_folder = self.get_dataset_coco() if random.random() < 0.5: # generate image tp["conversations"][0]["value"] = DEFAULT_IMAGE_TOKEN + "\n" + random.choice(regen_prompt) if self.data_args.mm_use_output_start_end: tp["conversations"][1]["value"] = DEFAULT_OUTPUT_START_TOKEN + " " + tp["conversations"][1][ "value"] + " " + DEFAULT_OUTPUT_END_TOKEN else: # describe image tp["conversations"][0]["value"] = DEFAULT_IMAGE_TOKEN + "\n" + random.choice(ques_prompt) else: # prompt refinement if random.random() < self.ratio_aes: tp, txn = self.get_dataset_aes() else: tp, coco = self.get_dataset_cocov2() has_img = False if not has_img: if txn is not None: text_complete = self.prompt_dict_ori[tp['image']] else: text_complete = coco["coco_caption"] _ = tp.pop('image') if random.random() < 0.5: # description tp_prompt = textextend_prompt2 is_generation = False else: # generation
tp_prompt = textextend_prompt
11
2023-11-27 18:46:55+00:00
8k
sherwinbahmani/4dfy
threestudio/models/renderers/mask_nerf_renderer.py
[ { "identifier": "BaseBackground", "path": "threestudio/models/background/base.py", "snippet": "class BaseBackground(BaseModule):\n @dataclass\n class Config(BaseModule.Config):\n pass\n\n cfg: Config\n\n def configure(self):\n pass\n\n def forward(self, dirs: Float[Tensor, \...
from dataclasses import dataclass, field from functools import partial from threestudio.models.background.base import BaseBackground from threestudio.models.estimators import ImportanceEstimator from threestudio.models.geometry.base import BaseImplicitGeometry from threestudio.models.materials.base import BaseMaterial from threestudio.models.networks import create_network_with_input_encoding from threestudio.models.renderers.base import VolumeRenderer from threestudio.systems.utils import parse_optimizer, parse_scheduler_to_instance from threestudio.utils.ops import chunk_batch, get_activation, validate_empty_rays from threestudio.utils.typing import * import nerfacc import threestudio import torch import torch.nn.functional as F
4,837
@threestudio.register("mask-nerf-volume-renderer") class StableNeRFVolumeRenderer(VolumeRenderer): @dataclass class Config(VolumeRenderer.Config): num_samples_per_ray: int = 512 eval_chunk_size: int = 160000 randomized: bool = True near_plane: float = 0.0 far_plane: float = 1e10 return_comp_normal: bool = False return_normal_perturb: bool = False # in ["occgrid", "proposal", "importance"] estimator: str = "occgrid" # for occgrid grid_prune: bool = True prune_alpha_threshold: bool = True # for proposal proposal_network_config: Optional[dict] = None prop_optimizer_config: Optional[dict] = None prop_scheduler_config: Optional[dict] = None num_samples_per_ray_proposal: int = 64 # for importance num_samples_per_ray_importance: int = 64 # for memory train_max_nums: int = 6000000 cfg: Config def configure( self, geometry: BaseImplicitGeometry, material: BaseMaterial, background: BaseBackground, ) -> None: super().configure(geometry, material, background) if self.cfg.estimator == "occgrid": self.estimator = nerfacc.OccGridEstimator( roi_aabb=self.bbox.view(-1), resolution=32, levels=1 ) if not self.cfg.grid_prune: self.estimator.occs.fill_(True) self.estimator.binaries.fill_(True) self.render_step_size = ( 1.732 * 2 * self.cfg.radius / self.cfg.num_samples_per_ray ) self.randomized = self.cfg.randomized elif self.cfg.estimator == "importance": self.estimator = ImportanceEstimator() elif self.cfg.estimator == "proposal": self.prop_net = create_network_with_input_encoding( **self.cfg.proposal_network_config ) self.prop_optim = parse_optimizer( self.cfg.prop_optimizer_config, self.prop_net ) self.prop_scheduler = (
@threestudio.register("mask-nerf-volume-renderer") class StableNeRFVolumeRenderer(VolumeRenderer): @dataclass class Config(VolumeRenderer.Config): num_samples_per_ray: int = 512 eval_chunk_size: int = 160000 randomized: bool = True near_plane: float = 0.0 far_plane: float = 1e10 return_comp_normal: bool = False return_normal_perturb: bool = False # in ["occgrid", "proposal", "importance"] estimator: str = "occgrid" # for occgrid grid_prune: bool = True prune_alpha_threshold: bool = True # for proposal proposal_network_config: Optional[dict] = None prop_optimizer_config: Optional[dict] = None prop_scheduler_config: Optional[dict] = None num_samples_per_ray_proposal: int = 64 # for importance num_samples_per_ray_importance: int = 64 # for memory train_max_nums: int = 6000000 cfg: Config def configure( self, geometry: BaseImplicitGeometry, material: BaseMaterial, background: BaseBackground, ) -> None: super().configure(geometry, material, background) if self.cfg.estimator == "occgrid": self.estimator = nerfacc.OccGridEstimator( roi_aabb=self.bbox.view(-1), resolution=32, levels=1 ) if not self.cfg.grid_prune: self.estimator.occs.fill_(True) self.estimator.binaries.fill_(True) self.render_step_size = ( 1.732 * 2 * self.cfg.radius / self.cfg.num_samples_per_ray ) self.randomized = self.cfg.randomized elif self.cfg.estimator == "importance": self.estimator = ImportanceEstimator() elif self.cfg.estimator == "proposal": self.prop_net = create_network_with_input_encoding( **self.cfg.proposal_network_config ) self.prop_optim = parse_optimizer( self.cfg.prop_optimizer_config, self.prop_net ) self.prop_scheduler = (
parse_scheduler_to_instance(
7
2023-11-29 05:15:56+00:00
8k
rlawjdghek/StableVITON
ldm/models/autoencoder.py
[ { "identifier": "Encoder", "path": "ldm/modules/diffusionmodules/model.py", "snippet": "class Encoder(nn.Module):\n def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,\n attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,\n resolution, z...
import torch import pytorch_lightning as pl import torch.nn.functional as F from contextlib import contextmanager from ldm.modules.diffusionmodules.model import Encoder, Decoder from ldm.modules.distributions.distributions import DiagonalGaussianDistribution from ldm.util import instantiate_from_config from ldm.modules.ema import LitEma
3,608
class AutoencoderKL(pl.LightningModule): def __init__(self, ddconfig, lossconfig, embed_dim, ckpt_path=None, ignore_keys=[], image_key="image", colorize_nlabels=None, monitor=None, ema_decay=None, learn_logvar=False ): super().__init__() self.lossconfig = lossconfig self.learn_logvar = learn_logvar self.image_key = image_key self.encoder = Encoder(**ddconfig) self.decoder = Decoder(**ddconfig) self.loss = torch.nn.Identity() assert ddconfig["double_z"] self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1) self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1) self.embed_dim = embed_dim if colorize_nlabels is not None: assert type(colorize_nlabels)==int self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1)) if monitor is not None: self.monitor = monitor self.use_ema = ema_decay is not None if self.use_ema: self.ema_decay = ema_decay assert 0. < ema_decay < 1.
class AutoencoderKL(pl.LightningModule): def __init__(self, ddconfig, lossconfig, embed_dim, ckpt_path=None, ignore_keys=[], image_key="image", colorize_nlabels=None, monitor=None, ema_decay=None, learn_logvar=False ): super().__init__() self.lossconfig = lossconfig self.learn_logvar = learn_logvar self.image_key = image_key self.encoder = Encoder(**ddconfig) self.decoder = Decoder(**ddconfig) self.loss = torch.nn.Identity() assert ddconfig["double_z"] self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1) self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1) self.embed_dim = embed_dim if colorize_nlabels is not None: assert type(colorize_nlabels)==int self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1)) if monitor is not None: self.monitor = monitor self.use_ema = ema_decay is not None if self.use_ema: self.ema_decay = ema_decay assert 0. < ema_decay < 1.
self.model_ema = LitEma(self, decay=ema_decay)
4
2023-12-02 05:56:58+00:00
8k
ContextualAI/HALOs
trainers.py
[ { "identifier": "AutoModelForCausalLMWithValueHead", "path": "models.py", "snippet": "class AutoModelForCausalLMWithValueHead(PreTrainedModelWrapper):\n r\"\"\"\n An autoregressive model with a value head in addition to the language model head.\n\n Class attributes:\n - **transformers_pa...
import torch import torch.nn.functional as F import torch.nn as nn import transformers import gc import torch.distributed as dist import tensor_parallel as tp import contextlib import dataloader import numpy as np import wandb import tqdm import random import os import time import json import functools from models import AutoModelForCausalLMWithValueHead from omegaconf import OmegaConf, DictConfig from transformers import AutoTokenizer from torch.distributed.fsdp import ( FullyShardedDataParallel as FSDP, MixedPrecision, StateDictType, BackwardPrefetch, ShardingStrategy, CPUOffload, ) from torch.distributed.fsdp.api import FullStateDictConfig, FullOptimStateDictConfig from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy, size_based_auto_wrap_policy from utils import ( slice_and_move_batch_for_device, formatted_dict, all_gather_if_needed, pad_to_length, get_block_class_from_model, rank0_print, get_batch_logps, masked_mean, masked_var, entropy_from_logits, delete_dict, rowwise_product, ) from collections import defaultdict from typing import Optional, Dict, List, Union, Tuple from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( checkpoint_wrapper, apply_activation_checkpointing, CheckpointImpl, )
5,019
reference_model: Optional[nn.Module] = None, rank: int = 0, world_size: int = 1, fsdp: bool = False, ): """A trainer for a language model, supporting either SFT, HALO, or offline PPO training. """ self.seed = config.seed torch.manual_seed(self.seed) np.random.seed(self.seed) random.seed(self.seed) self.rank = rank self.device = torch.device('cuda', self.rank) self.world_size = world_size self.config = config self.run_dir = config.local_run_dir self.fsdp = fsdp self.tokenizer = tokenizer self.policy = policy self.policy_dtype = getattr(torch, config.model.policy_dtype) self.reference_model = reference_model self.example_counter = 0 self.batch_counter = 0 self.train_iterator = train_iterator self.eval_iterator = eval_iterator self.eval_batches = list(self.eval_iterator) rank0_print(f'Loaded {len(self.eval_batches)} eval batches of size {config.model.eval_batch_size}') if self.fsdp: self.shard() self.is_mistral = 'mistral' in self.config.model.name_or_path.lower() def shard(self): """ Shard the policy model and reference model (if applicable) using FDSP. """ assert self.config.model.block_name is not None, 'must specify model.block_name (e.g., GPT2Block or GPTNeoXLayer) for FSDP' wrap_class = get_block_class_from_model(self.policy.pretrained_model if self.config.loss.name == 'ppo' else self.policy, self.config.model.block_name) model_auto_wrap_policy = functools.partial(transformer_auto_wrap_policy, transformer_layer_cls={wrap_class},) shared_fsdp_kwargs = dict( auto_wrap_policy=model_auto_wrap_policy, sharding_strategy=ShardingStrategy.FULL_SHARD, cpu_offload=CPUOffload(offload_params=False), backward_prefetch=BackwardPrefetch.BACKWARD_PRE, device_id=self.rank, ignored_modules=None, limit_all_gathers=False, use_orig_params=False, sync_module_states=False ) rank0_print('Sharding models...') mp_dtype = getattr(torch, self.config.model.fsdp_policy_mp) if self.config.model.fsdp_policy_mp is not None else None policy_mp_policy = MixedPrecision(param_dtype=mp_dtype, reduce_dtype=mp_dtype, buffer_dtype=mp_dtype) if self.config.loss.name == 'ppo': self.policy.pretrained_model = FSDP(self.policy.pretrained_model, **shared_fsdp_kwargs, mixed_precision=policy_mp_policy) # shard the value head according to size v_head_shared_fsdp_kwargs = dict( auto_wrap_policy=functools.partial(size_based_auto_wrap_policy, min_num_params=100), sharding_strategy=ShardingStrategy.FULL_SHARD, cpu_offload=CPUOffload(offload_params=False), backward_prefetch=BackwardPrefetch.BACKWARD_PRE, device_id=self.rank, ignored_modules=None, limit_all_gathers=False, use_orig_params=False, sync_module_states=False ) self.policy.v_head = FSDP(self.policy.v_head, **v_head_shared_fsdp_kwargs) else: self.policy = FSDP(self.policy, **shared_fsdp_kwargs, mixed_precision=policy_mp_policy) if self.reference_model is not None: self.reference_model = FSDP(self.reference_model, **shared_fsdp_kwargs, mixed_precision=policy_mp_policy) if self.config.model.activation_checkpointing: rank0_print('Attempting to enable activation checkpointing...') try: # use activation checkpointing, according to: # https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/ # first, verify we have FSDP activation support ready by importing: except Exception as e: rank0_print('FSDP activation checkpointing not available:', e) else: check_fn = lambda submodule: isinstance(submodule, wrap_class) rank0_print('Applying activation checkpointing wrapper to policy...') if self.config.loss.name == 'ppo': apply_activation_checkpointing(self.policy.pretrained_model, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=check_fn) else: apply_activation_checkpointing(self.policy, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=check_fn) if self.reference_model is not None: apply_activation_checkpointing(self.reference_model, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=check_fn) rank0_print('FSDP activation checkpointing enabled!') print('Loaded model on rank', self.rank) dist.barrier() def get_batch_samples(self, batch: Dict[str, torch.LongTensor]) -> Tuple[str, str]: """Generate samples from the policy.""" ctx = lambda: (FSDP.summon_full_params(self.policy, writeback=False, recurse=False) if self.fsdp else contextlib.nullcontext()) with ctx(): policy_output = self.policy.generate( batch['prompt_input_ids'], attention_mask=batch['prompt_attention_mask'], max_length=self.config.model.max_length, do_sample=True, pad_token_id=self.tokenizer.pad_token_id, top_p=self.config.top_p, )
# Copyright (c) 2023 Contextual AI, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ Extendable Trainer classes for aligning LLMs. The specific class that should be used should be specified in the loss file under config/loss. The BasicTrainer contains the core methods (e.g., sharding, basic training loop, etc.). The SFTTrainer, PairedPreferenceTrainer, and UnpairedPreferenceTrainer all subclass BasicTrainer and override the get_batch_metrics() and (optionally) forward() methods. The trainer for each loss should subclass either PairedPreferenceTrainer or UnpairedPreferenceTrainer. """ torch.backends.cuda.matmul.allow_tf32 = True class BasicTrainer(object): def __init__(self, tokenizer: AutoTokenizer, config: DictConfig, train_iterator: dataloader.DataLoader, eval_iterator: dataloader.DataLoader, policy: nn.Module, reference_model: Optional[nn.Module] = None, rank: int = 0, world_size: int = 1, fsdp: bool = False, ): """A trainer for a language model, supporting either SFT, HALO, or offline PPO training. """ self.seed = config.seed torch.manual_seed(self.seed) np.random.seed(self.seed) random.seed(self.seed) self.rank = rank self.device = torch.device('cuda', self.rank) self.world_size = world_size self.config = config self.run_dir = config.local_run_dir self.fsdp = fsdp self.tokenizer = tokenizer self.policy = policy self.policy_dtype = getattr(torch, config.model.policy_dtype) self.reference_model = reference_model self.example_counter = 0 self.batch_counter = 0 self.train_iterator = train_iterator self.eval_iterator = eval_iterator self.eval_batches = list(self.eval_iterator) rank0_print(f'Loaded {len(self.eval_batches)} eval batches of size {config.model.eval_batch_size}') if self.fsdp: self.shard() self.is_mistral = 'mistral' in self.config.model.name_or_path.lower() def shard(self): """ Shard the policy model and reference model (if applicable) using FDSP. """ assert self.config.model.block_name is not None, 'must specify model.block_name (e.g., GPT2Block or GPTNeoXLayer) for FSDP' wrap_class = get_block_class_from_model(self.policy.pretrained_model if self.config.loss.name == 'ppo' else self.policy, self.config.model.block_name) model_auto_wrap_policy = functools.partial(transformer_auto_wrap_policy, transformer_layer_cls={wrap_class},) shared_fsdp_kwargs = dict( auto_wrap_policy=model_auto_wrap_policy, sharding_strategy=ShardingStrategy.FULL_SHARD, cpu_offload=CPUOffload(offload_params=False), backward_prefetch=BackwardPrefetch.BACKWARD_PRE, device_id=self.rank, ignored_modules=None, limit_all_gathers=False, use_orig_params=False, sync_module_states=False ) rank0_print('Sharding models...') mp_dtype = getattr(torch, self.config.model.fsdp_policy_mp) if self.config.model.fsdp_policy_mp is not None else None policy_mp_policy = MixedPrecision(param_dtype=mp_dtype, reduce_dtype=mp_dtype, buffer_dtype=mp_dtype) if self.config.loss.name == 'ppo': self.policy.pretrained_model = FSDP(self.policy.pretrained_model, **shared_fsdp_kwargs, mixed_precision=policy_mp_policy) # shard the value head according to size v_head_shared_fsdp_kwargs = dict( auto_wrap_policy=functools.partial(size_based_auto_wrap_policy, min_num_params=100), sharding_strategy=ShardingStrategy.FULL_SHARD, cpu_offload=CPUOffload(offload_params=False), backward_prefetch=BackwardPrefetch.BACKWARD_PRE, device_id=self.rank, ignored_modules=None, limit_all_gathers=False, use_orig_params=False, sync_module_states=False ) self.policy.v_head = FSDP(self.policy.v_head, **v_head_shared_fsdp_kwargs) else: self.policy = FSDP(self.policy, **shared_fsdp_kwargs, mixed_precision=policy_mp_policy) if self.reference_model is not None: self.reference_model = FSDP(self.reference_model, **shared_fsdp_kwargs, mixed_precision=policy_mp_policy) if self.config.model.activation_checkpointing: rank0_print('Attempting to enable activation checkpointing...') try: # use activation checkpointing, according to: # https://pytorch.org/blog/scaling-multimodal-foundation-models-in-torchmultimodal-with-pytorch-distributed/ # first, verify we have FSDP activation support ready by importing: except Exception as e: rank0_print('FSDP activation checkpointing not available:', e) else: check_fn = lambda submodule: isinstance(submodule, wrap_class) rank0_print('Applying activation checkpointing wrapper to policy...') if self.config.loss.name == 'ppo': apply_activation_checkpointing(self.policy.pretrained_model, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=check_fn) else: apply_activation_checkpointing(self.policy, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=check_fn) if self.reference_model is not None: apply_activation_checkpointing(self.reference_model, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=check_fn) rank0_print('FSDP activation checkpointing enabled!') print('Loaded model on rank', self.rank) dist.barrier() def get_batch_samples(self, batch: Dict[str, torch.LongTensor]) -> Tuple[str, str]: """Generate samples from the policy.""" ctx = lambda: (FSDP.summon_full_params(self.policy, writeback=False, recurse=False) if self.fsdp else contextlib.nullcontext()) with ctx(): policy_output = self.policy.generate( batch['prompt_input_ids'], attention_mask=batch['prompt_attention_mask'], max_length=self.config.model.max_length, do_sample=True, pad_token_id=self.tokenizer.pad_token_id, top_p=self.config.top_p, )
policy_output = pad_to_length(policy_output, self.config.model.max_length, self.tokenizer.pad_token_id)
4
2023-12-03 07:53:36+00:00
8k
AIFSH/NativeSpeaker
src/third_part/facelib/detection/retinaface/retinaface.py
[ { "identifier": "get_reference_facial_points", "path": "src/third_part/facelib/detection/align_trans.py", "snippet": "def get_reference_facial_points(output_size=None, inner_padding_factor=0.0, outer_padding=(0, 0), default_square=False):\n \"\"\"\n Function:\n ----------\n get reference...
import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as models from PIL import Image from torchvision.models._utils import IntermediateLayerGetter as IntermediateLayerGetter from ..align_trans import get_reference_facial_points, warp_and_crop_face from .retinaface_net import FPN, SSH, MobileNetV1, make_bbox_head, make_class_head, make_landmark_head from .retinaface_utils import (PriorBox, batched_decode, batched_decode_landm, decode, decode_landm, py_cpu_nms)
6,023
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def generate_config(network_name): cfg_mnet = { 'name': 'mobilenet0.25', 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True, 'batch_size': 32, 'ngpu': 1, 'epoch': 250, 'decay1': 190, 'decay2': 220, 'image_size': 640, 'return_layers': { 'stage1': 1, 'stage2': 2, 'stage3': 3 }, 'in_channel': 32, 'out_channel': 64 } cfg_re50 = { 'name': 'Resnet50', 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True, 'batch_size': 24, 'ngpu': 4, 'epoch': 100, 'decay1': 70, 'decay2': 90, 'image_size': 840, 'return_layers': { 'layer2': 1, 'layer3': 2, 'layer4': 3 }, 'in_channel': 256, 'out_channel': 256 } if network_name == 'mobile0.25': return cfg_mnet elif network_name == 'resnet50': return cfg_re50 else: raise NotImplementedError(f'network_name={network_name}') class RetinaFace(nn.Module): def __init__(self, network_name='resnet50', half=False, phase='test'): super(RetinaFace, self).__init__() self.half_inference = half cfg = generate_config(network_name) self.backbone = cfg['name'] self.model_name = f'retinaface_{network_name}' self.cfg = cfg self.phase = phase self.target_size, self.max_size = 1600, 2150 self.resize, self.scale, self.scale1 = 1., None, None self.mean_tensor = torch.tensor([[[[104.]], [[117.]], [[123.]]]]).to(device) self.reference = get_reference_facial_points(default_square=True) # Build network. backbone = None if cfg['name'] == 'mobilenet0.25': backbone = MobileNetV1() self.body = IntermediateLayerGetter(backbone, cfg['return_layers']) elif cfg['name'] == 'Resnet50': backbone = models.resnet50(pretrained=False) self.body = IntermediateLayerGetter(backbone, cfg['return_layers']) in_channels_stage2 = cfg['in_channel'] in_channels_list = [ in_channels_stage2 * 2, in_channels_stage2 * 4, in_channels_stage2 * 8, ] out_channels = cfg['out_channel']
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def generate_config(network_name): cfg_mnet = { 'name': 'mobilenet0.25', 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True, 'batch_size': 32, 'ngpu': 1, 'epoch': 250, 'decay1': 190, 'decay2': 220, 'image_size': 640, 'return_layers': { 'stage1': 1, 'stage2': 2, 'stage3': 3 }, 'in_channel': 32, 'out_channel': 64 } cfg_re50 = { 'name': 'Resnet50', 'min_sizes': [[16, 32], [64, 128], [256, 512]], 'steps': [8, 16, 32], 'variance': [0.1, 0.2], 'clip': False, 'loc_weight': 2.0, 'gpu_train': True, 'batch_size': 24, 'ngpu': 4, 'epoch': 100, 'decay1': 70, 'decay2': 90, 'image_size': 840, 'return_layers': { 'layer2': 1, 'layer3': 2, 'layer4': 3 }, 'in_channel': 256, 'out_channel': 256 } if network_name == 'mobile0.25': return cfg_mnet elif network_name == 'resnet50': return cfg_re50 else: raise NotImplementedError(f'network_name={network_name}') class RetinaFace(nn.Module): def __init__(self, network_name='resnet50', half=False, phase='test'): super(RetinaFace, self).__init__() self.half_inference = half cfg = generate_config(network_name) self.backbone = cfg['name'] self.model_name = f'retinaface_{network_name}' self.cfg = cfg self.phase = phase self.target_size, self.max_size = 1600, 2150 self.resize, self.scale, self.scale1 = 1., None, None self.mean_tensor = torch.tensor([[[[104.]], [[117.]], [[123.]]]]).to(device) self.reference = get_reference_facial_points(default_square=True) # Build network. backbone = None if cfg['name'] == 'mobilenet0.25': backbone = MobileNetV1() self.body = IntermediateLayerGetter(backbone, cfg['return_layers']) elif cfg['name'] == 'Resnet50': backbone = models.resnet50(pretrained=False) self.body = IntermediateLayerGetter(backbone, cfg['return_layers']) in_channels_stage2 = cfg['in_channel'] in_channels_list = [ in_channels_stage2 * 2, in_channels_stage2 * 4, in_channels_stage2 * 8, ] out_channels = cfg['out_channel']
self.fpn = FPN(in_channels_list, out_channels)
2
2023-12-01 12:23:19+00:00
8k
orhir/PoseAnything
models/models/backbones/simmim.py
[ { "identifier": "SwinTransformer", "path": "models/models/backbones/swin_transformer.py", "snippet": "class SwinTransformer(nn.Module):\n r\"\"\" Swin Transformer\n A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -\n https://arxiv.org/pdf...
import torch import torch.nn as nn import torch.nn.functional as F from timm.models.layers import trunc_normal_ from .swin_transformer import SwinTransformer from .swin_transformer_v2 import SwinTransformerV2
4,170
# -------------------------------------------------------- # SimMIM # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Zhenda Xie # -------------------------------------------------------- def norm_targets(targets, patch_size): assert patch_size % 2 == 1 targets_ = targets targets_count = torch.ones_like(targets) targets_square = targets ** 2. targets_mean = F.avg_pool2d(targets, kernel_size=patch_size, stride=1, padding=patch_size // 2, count_include_pad=False) targets_square_mean = F.avg_pool2d(targets_square, kernel_size=patch_size, stride=1, padding=patch_size // 2, count_include_pad=False) targets_count = F.avg_pool2d(targets_count, kernel_size=patch_size, stride=1, padding=patch_size // 2, count_include_pad=True) * (patch_size ** 2) targets_var = (targets_square_mean - targets_mean ** 2.) * (targets_count / (targets_count - 1)) targets_var = torch.clamp(targets_var, min=0.) targets_ = (targets_ - targets_mean) / (targets_var + 1.e-6) ** 0.5 return targets_
# -------------------------------------------------------- # SimMIM # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Zhenda Xie # -------------------------------------------------------- def norm_targets(targets, patch_size): assert patch_size % 2 == 1 targets_ = targets targets_count = torch.ones_like(targets) targets_square = targets ** 2. targets_mean = F.avg_pool2d(targets, kernel_size=patch_size, stride=1, padding=patch_size // 2, count_include_pad=False) targets_square_mean = F.avg_pool2d(targets_square, kernel_size=patch_size, stride=1, padding=patch_size // 2, count_include_pad=False) targets_count = F.avg_pool2d(targets_count, kernel_size=patch_size, stride=1, padding=patch_size // 2, count_include_pad=True) * (patch_size ** 2) targets_var = (targets_square_mean - targets_mean ** 2.) * (targets_count / (targets_count - 1)) targets_var = torch.clamp(targets_var, min=0.) targets_ = (targets_ - targets_mean) / (targets_var + 1.e-6) ** 0.5 return targets_
class SwinTransformerForSimMIM(SwinTransformer):
0
2023-11-28 10:33:33+00:00
8k
VITA-Group/FSGS
scene/gaussian_model.py
[ { "identifier": "inverse_sigmoid", "path": "utils/general_utils.py", "snippet": "def inverse_sigmoid(x):\n return torch.log(x/(1-x))" }, { "identifier": "get_expon_lr_func", "path": "utils/general_utils.py", "snippet": "def get_expon_lr_func(\n lr_init, lr_final, lr_delay_steps=0, ...
import matplotlib.pyplot as plt import torch import numpy as np import os import open3d as o3d from utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation from torch import nn from utils.system_utils import mkdir_p from plyfile import PlyData, PlyElement from utils.sh_utils import RGB2SH from simple_knn._C import distCUDA2 from utils.graphics_utils import BasicPointCloud from utils.general_utils import strip_symmetric, build_scaling_rotation, chamfer_dist from torch.optim.lr_scheduler import MultiStepLR
4,844
optimizable_tensors = self._prune_optimizer(valid_points_mask) self._xyz = optimizable_tensors["xyz"] self._features_dc = optimizable_tensors["f_dc"] self._features_rest = optimizable_tensors["f_rest"] self._opacity = optimizable_tensors["opacity"] self._scaling = optimizable_tensors["scaling"] self._rotation = optimizable_tensors["rotation"] self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask] self.denom = self.denom[valid_points_mask] self.max_radii2D = self.max_radii2D[valid_points_mask] def prune_points(self, mask, iter): if iter > self.args.prune_from_iter: valid_points_mask = ~mask optimizable_tensors = self._prune_optimizer(valid_points_mask) self._xyz = optimizable_tensors["xyz"] self._features_dc = optimizable_tensors["f_dc"] self._features_rest = optimizable_tensors["f_rest"] self._opacity = optimizable_tensors["opacity"] self._scaling = optimizable_tensors["scaling"] self._rotation = optimizable_tensors["rotation"] self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask] self.denom = self.denom[valid_points_mask] self.max_radii2D = self.max_radii2D[valid_points_mask] self.confidence = self.confidence[valid_points_mask] def cat_tensors_to_optimizer(self, tensors_dict): optimizable_tensors = {} for group in self.optimizer.param_groups: if group["name"] in ['bg_color']: continue assert len(group["params"]) == 1 extension_tensor = tensors_dict[group["name"]] stored_state = self.optimizer.state.get(group['params'][0], None) if stored_state is not None: stored_state["exp_avg"] = torch.cat((stored_state["exp_avg"], torch.zeros_like(extension_tensor)), dim=0) stored_state["exp_avg_sq"] = torch.cat((stored_state["exp_avg_sq"], torch.zeros_like(extension_tensor)), dim=0) del self.optimizer.state[group['params'][0]] group["params"][0] = nn.Parameter( torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True)) self.optimizer.state[group['params'][0]] = stored_state optimizable_tensors[group["name"]] = group["params"][0] else: group["params"][0] = nn.Parameter( torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True)) optimizable_tensors[group["name"]] = group["params"][0] return optimizable_tensors def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation): d = {"xyz": new_xyz, "f_dc": new_features_dc, "f_rest": new_features_rest, "opacity": new_opacities, "scaling": new_scaling, "rotation": new_rotation} optimizable_tensors = self.cat_tensors_to_optimizer(d) self._xyz = optimizable_tensors["xyz"] self._features_dc = optimizable_tensors["f_dc"] self._features_rest = optimizable_tensors["f_rest"] self._opacity = optimizable_tensors["opacity"] self._scaling = optimizable_tensors["scaling"] self._rotation = optimizable_tensors["rotation"] self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda") self.confidence = torch.cat([self.confidence, torch.ones(new_opacities.shape, device="cuda")], 0) def proximity(self, scene_extent, N = 3): dist, nearest_indices = distCUDA2(self.get_xyz) selected_pts_mask = torch.logical_and(dist > (5. * scene_extent), torch.max(self.get_scaling, dim=1).values > (scene_extent)) new_indices = nearest_indices[selected_pts_mask].reshape(-1).long() source_xyz = self._xyz[selected_pts_mask].repeat(1, N, 1).reshape(-1, 3) target_xyz = self._xyz[new_indices] new_xyz = (source_xyz + target_xyz) / 2 new_scaling = self._scaling[new_indices] new_rotation = torch.zeros_like(self._rotation[new_indices]) new_rotation[:, 0] = 1 new_features_dc = torch.zeros_like(self._features_dc[new_indices]) new_features_rest = torch.zeros_like(self._features_rest[new_indices]) new_opacity = self._opacity[new_indices] self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation) def densify_and_split(self, grads, grad_threshold, scene_extent, iter, N=2): n_init_points = self.get_xyz.shape[0] # Extract points that satisfy the gradient condition padded_grad = torch.zeros((n_init_points), device="cuda") padded_grad[:grads.shape[0]] = grads.squeeze() selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False) selected_pts_mask = torch.logical_and(selected_pts_mask, torch.max(self.get_scaling, dim=1).values > self.percent_dense * scene_extent) dist, _ = distCUDA2(self.get_xyz) selected_pts_mask2 = torch.logical_and(dist > (self.args.dist_thres * scene_extent), torch.max(self.get_scaling, dim=1).values > ( scene_extent)) selected_pts_mask = torch.logical_or(selected_pts_mask, selected_pts_mask2) stds = self.get_scaling[selected_pts_mask].repeat(N, 1) means = torch.zeros((stds.size(0), 3), device="cuda") samples = torch.normal(mean=means, std=stds)
# # Copyright (C) 2023, Inria # GRAPHDECO research group, https://team.inria.fr/graphdeco # All rights reserved. # # This software is free for non-commercial, research and evaluation use # under the terms of the LICENSE.md file. # # For inquiries contact george.drettakis@inria.fr # class GaussianModel: def setup_functions(self): def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation): L = build_scaling_rotation(scaling_modifier * scaling, rotation) actual_covariance = L @ L.transpose(1, 2) symm = strip_symmetric(actual_covariance) return symm self.scaling_activation = torch.exp self.scaling_inverse_activation = torch.log self.covariance_activation = build_covariance_from_scaling_rotation self.opacity_activation = torch.sigmoid self.inverse_opacity_activation = inverse_sigmoid self.rotation_activation = torch.nn.functional.normalize def __init__(self, args): self.args = args self.active_sh_degree = 0 self.max_sh_degree = args.sh_degree self.init_point = torch.empty(0) self._xyz = torch.empty(0) self._features_dc = torch.empty(0) self._features_rest = torch.empty(0) self._scaling = torch.empty(0) self._rotation = torch.empty(0) self._opacity = torch.empty(0) self.max_radii2D = torch.empty(0) self.xyz_gradient_accum = torch.empty(0) self.denom = torch.empty(0) self.optimizer = None self.percent_dense = 0 self.spatial_lr_scale = 0 self.setup_functions() self.bg_color = torch.empty(0) self.confidence = torch.empty(0) def capture(self): return ( self.active_sh_degree, self._xyz, self._features_dc, self._features_rest, self._scaling, self._rotation, self._opacity, self.max_radii2D, self.xyz_gradient_accum, self.denom, self.optimizer.state_dict(), self.spatial_lr_scale, ) def restore(self, model_args, training_args): (self.active_sh_degree, self._xyz, self._features_dc, self._features_rest, self._scaling, self._rotation, self._opacity, self.max_radii2D, xyz_gradient_accum, denom, opt_dict, self.spatial_lr_scale) = model_args self.training_setup(training_args) self.xyz_gradient_accum = xyz_gradient_accum self.denom = denom # self.optimizer.load_state_dict(opt_dict) @property def get_scaling(self): return self.scaling_activation(self._scaling) @property def get_rotation(self): w = self.rotation_activation(self._rotation) return self.rotation_activation(self._rotation) @property def get_xyz(self): return self._xyz @property def get_features(self): features_dc = self._features_dc features_rest = self._features_rest return torch.cat((features_dc, features_rest), dim=1) @property def get_opacity(self): return self.opacity_activation(self._opacity) def get_covariance(self, scaling_modifier=1): return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation) def oneupSHdegree(self): if self.active_sh_degree < self.max_sh_degree: self.active_sh_degree += 1 def create_from_pcd(self, pcd: BasicPointCloud, spatial_lr_scale: float): self.spatial_lr_scale = spatial_lr_scale fused_point_cloud = torch.tensor(np.asarray(pcd.points)).cuda().float() fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda()) features = torch.zeros((fused_point_cloud.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda() if self.args.use_color: features[:, :3, 0] = fused_color features[:, 3:, 1:] = 0.0 print("Number of points at initialisation : ", fused_point_cloud.shape[0]) self.init_point = fused_point_cloud dist2 = torch.clamp_min(distCUDA2(fused_point_cloud)[0], 0.0000001) scales = torch.log(torch.sqrt(dist2))[..., None].repeat(1, 3) rots = torch.zeros((fused_point_cloud.shape[0], 4), device="cuda") rots[:, 0] = 1 opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device="cuda")) self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True)) self._features_dc = nn.Parameter(features[:, :, 0:1].transpose(1, 2).contiguous().requires_grad_(True)) self._features_rest = nn.Parameter(features[:, :, 1:].transpose(1, 2).contiguous().requires_grad_(True)) self._scaling = nn.Parameter(scales.requires_grad_(True)) self._rotation = nn.Parameter(rots.requires_grad_(True)) self._opacity = nn.Parameter(opacities.requires_grad_(True)) self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda") self.confidence = torch.ones_like(opacities, device="cuda") if self.args.train_bg: self.bg_color = nn.Parameter((torch.zeros(3, 1, 1) + 0.).cuda().requires_grad_(True)) def training_setup(self, training_args): self.percent_dense = training_args.percent_dense self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") l = [ {'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, "name": "xyz"}, {'params': [self._features_dc], 'lr': training_args.feature_lr, "name": "f_dc"}, {'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, "name": "f_rest"}, {'params': [self._opacity], 'lr': training_args.opacity_lr, "name": "opacity"}, {'params': [self._scaling], 'lr': training_args.scaling_lr, "name": "scaling"}, {'params': [self._rotation], 'lr': training_args.rotation_lr, "name": "rotation"}, ] if self.args.train_bg: l.append({'params': [self.bg_color], 'lr': 0.001, "name": "bg_color"}) self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15) self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init * self.spatial_lr_scale, lr_final=training_args.position_lr_final * self.spatial_lr_scale, lr_delay_mult=training_args.position_lr_delay_mult, max_steps=training_args.position_lr_max_steps) def update_learning_rate(self, iteration): ''' Learning rate scheduling per step ''' xyz_lr = self.xyz_scheduler_args(iteration) for param_group in self.optimizer.param_groups: if param_group["name"] == "xyz": param_group['lr'] = xyz_lr return xyz_lr def construct_list_of_attributes(self): l = ['x', 'y', 'z', 'nx', 'ny', 'nz'] # All channels except the 3 DC for i in range(self._features_dc.shape[1] * self._features_dc.shape[2]): l.append('f_dc_{}'.format(i)) for i in range(self._features_rest.shape[1] * self._features_rest.shape[2]): l.append('f_rest_{}'.format(i)) l.append('opacity') for i in range(self._scaling.shape[1]): l.append('scale_{}'.format(i)) for i in range(self._rotation.shape[1]): l.append('rot_{}'.format(i)) return l def save_ply(self, path): mkdir_p(os.path.dirname(path)) xyz = self._xyz.detach().cpu().numpy() normals = np.zeros_like(xyz) f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy() f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy() opacities = self._opacity.detach().cpu().numpy() scale = self._scaling.detach().cpu().numpy() rotation = self._rotation.detach().cpu().numpy() dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()] elements = np.empty(xyz.shape[0], dtype=dtype_full) attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1) elements[:] = list(map(tuple, attributes)) el = PlyElement.describe(elements, 'vertex') PlyData([el]).write(path) def reset_opacity(self): opacities_new = inverse_sigmoid(torch.min(self.get_opacity, torch.ones_like(self.get_opacity) * 0.05)) if len(self.optimizer.state.keys()): optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, "opacity") self._opacity = optimizable_tensors["opacity"] def load_ply(self, path): plydata = PlyData.read(path) xyz = np.stack((np.asarray(plydata.elements[0]["x"]), np.asarray(plydata.elements[0]["y"]), np.asarray(plydata.elements[0]["z"])), axis=1) opacities = np.asarray(plydata.elements[0]["opacity"])[..., np.newaxis] features_dc = np.zeros((xyz.shape[0], 3, 1)) features_dc[:, 0, 0] = np.asarray(plydata.elements[0]["f_dc_0"]) features_dc[:, 1, 0] = np.asarray(plydata.elements[0]["f_dc_1"]) features_dc[:, 2, 0] = np.asarray(plydata.elements[0]["f_dc_2"]) extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("f_rest_")] extra_f_names = sorted(extra_f_names, key=lambda x: int(x.split('_')[-1])) assert len(extra_f_names) == 3 * (self.max_sh_degree + 1) ** 2 - 3 features_extra = np.zeros((xyz.shape[0], len(extra_f_names))) for idx, attr_name in enumerate(extra_f_names): features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name]) # Reshape (P,F*SH_coeffs) to (P, F, SH_coeffs except DC) features_extra = features_extra.reshape((features_extra.shape[0], 3, (self.max_sh_degree + 1) ** 2 - 1)) scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("scale_")] scale_names = sorted(scale_names, key=lambda x: int(x.split('_')[-1])) scales = np.zeros((xyz.shape[0], len(scale_names))) for idx, attr_name in enumerate(scale_names): scales[:, idx] = np.asarray(plydata.elements[0][attr_name]) rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("rot")] rot_names = sorted(rot_names, key=lambda x: int(x.split('_')[-1])) rots = np.zeros((xyz.shape[0], len(rot_names))) for idx, attr_name in enumerate(rot_names): rots[:, idx] = np.asarray(plydata.elements[0][attr_name]) self._xyz = nn.Parameter(torch.tensor(xyz, dtype=torch.float, device="cuda").requires_grad_(True)) self._features_dc = nn.Parameter( torch.tensor(features_dc, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_( True)) self._features_rest = nn.Parameter( torch.tensor(features_extra, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_( True)) self._opacity = nn.Parameter(torch.tensor(opacities, dtype=torch.float, device="cuda").requires_grad_(True)) self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device="cuda").requires_grad_(True)) self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device="cuda").requires_grad_(True)) self.active_sh_degree = self.max_sh_degree def replace_tensor_to_optimizer(self, tensor, name): optimizable_tensors = {} for group in self.optimizer.param_groups: if group["name"] == name: stored_state = self.optimizer.state.get(group['params'][0], None) stored_state["exp_avg"] = torch.zeros_like(tensor) stored_state["exp_avg_sq"] = torch.zeros_like(tensor) del self.optimizer.state[group['params'][0]] group["params"][0] = nn.Parameter(tensor.requires_grad_(True)) self.optimizer.state[group['params'][0]] = stored_state optimizable_tensors[group["name"]] = group["params"][0] return optimizable_tensors def _prune_optimizer(self, mask): optimizable_tensors = {} for group in self.optimizer.param_groups: if group["name"] in ['bg_color']: continue stored_state = self.optimizer.state.get(group['params'][0], None) if stored_state is not None: stored_state["exp_avg"] = stored_state["exp_avg"][mask] stored_state["exp_avg_sq"] = stored_state["exp_avg_sq"][mask] del self.optimizer.state[group['params'][0]] group["params"][0] = nn.Parameter((group["params"][0][mask].requires_grad_(True))) self.optimizer.state[group['params'][0]] = stored_state optimizable_tensors[group["name"]] = group["params"][0] else: group["params"][0] = nn.Parameter(group["params"][0][mask].requires_grad_(True)) optimizable_tensors[group["name"]] = group["params"][0] return optimizable_tensors def dist_prune(self): dist = chamfer_dist(self.init_point, self._xyz) valid_points_mask = (dist < 3.0) optimizable_tensors = self._prune_optimizer(valid_points_mask) self._xyz = optimizable_tensors["xyz"] self._features_dc = optimizable_tensors["f_dc"] self._features_rest = optimizable_tensors["f_rest"] self._opacity = optimizable_tensors["opacity"] self._scaling = optimizable_tensors["scaling"] self._rotation = optimizable_tensors["rotation"] self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask] self.denom = self.denom[valid_points_mask] self.max_radii2D = self.max_radii2D[valid_points_mask] def prune_points(self, mask, iter): if iter > self.args.prune_from_iter: valid_points_mask = ~mask optimizable_tensors = self._prune_optimizer(valid_points_mask) self._xyz = optimizable_tensors["xyz"] self._features_dc = optimizable_tensors["f_dc"] self._features_rest = optimizable_tensors["f_rest"] self._opacity = optimizable_tensors["opacity"] self._scaling = optimizable_tensors["scaling"] self._rotation = optimizable_tensors["rotation"] self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask] self.denom = self.denom[valid_points_mask] self.max_radii2D = self.max_radii2D[valid_points_mask] self.confidence = self.confidence[valid_points_mask] def cat_tensors_to_optimizer(self, tensors_dict): optimizable_tensors = {} for group in self.optimizer.param_groups: if group["name"] in ['bg_color']: continue assert len(group["params"]) == 1 extension_tensor = tensors_dict[group["name"]] stored_state = self.optimizer.state.get(group['params'][0], None) if stored_state is not None: stored_state["exp_avg"] = torch.cat((stored_state["exp_avg"], torch.zeros_like(extension_tensor)), dim=0) stored_state["exp_avg_sq"] = torch.cat((stored_state["exp_avg_sq"], torch.zeros_like(extension_tensor)), dim=0) del self.optimizer.state[group['params'][0]] group["params"][0] = nn.Parameter( torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True)) self.optimizer.state[group['params'][0]] = stored_state optimizable_tensors[group["name"]] = group["params"][0] else: group["params"][0] = nn.Parameter( torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True)) optimizable_tensors[group["name"]] = group["params"][0] return optimizable_tensors def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation): d = {"xyz": new_xyz, "f_dc": new_features_dc, "f_rest": new_features_rest, "opacity": new_opacities, "scaling": new_scaling, "rotation": new_rotation} optimizable_tensors = self.cat_tensors_to_optimizer(d) self._xyz = optimizable_tensors["xyz"] self._features_dc = optimizable_tensors["f_dc"] self._features_rest = optimizable_tensors["f_rest"] self._opacity = optimizable_tensors["opacity"] self._scaling = optimizable_tensors["scaling"] self._rotation = optimizable_tensors["rotation"] self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda") self.confidence = torch.cat([self.confidence, torch.ones(new_opacities.shape, device="cuda")], 0) def proximity(self, scene_extent, N = 3): dist, nearest_indices = distCUDA2(self.get_xyz) selected_pts_mask = torch.logical_and(dist > (5. * scene_extent), torch.max(self.get_scaling, dim=1).values > (scene_extent)) new_indices = nearest_indices[selected_pts_mask].reshape(-1).long() source_xyz = self._xyz[selected_pts_mask].repeat(1, N, 1).reshape(-1, 3) target_xyz = self._xyz[new_indices] new_xyz = (source_xyz + target_xyz) / 2 new_scaling = self._scaling[new_indices] new_rotation = torch.zeros_like(self._rotation[new_indices]) new_rotation[:, 0] = 1 new_features_dc = torch.zeros_like(self._features_dc[new_indices]) new_features_rest = torch.zeros_like(self._features_rest[new_indices]) new_opacity = self._opacity[new_indices] self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation) def densify_and_split(self, grads, grad_threshold, scene_extent, iter, N=2): n_init_points = self.get_xyz.shape[0] # Extract points that satisfy the gradient condition padded_grad = torch.zeros((n_init_points), device="cuda") padded_grad[:grads.shape[0]] = grads.squeeze() selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False) selected_pts_mask = torch.logical_and(selected_pts_mask, torch.max(self.get_scaling, dim=1).values > self.percent_dense * scene_extent) dist, _ = distCUDA2(self.get_xyz) selected_pts_mask2 = torch.logical_and(dist > (self.args.dist_thres * scene_extent), torch.max(self.get_scaling, dim=1).values > ( scene_extent)) selected_pts_mask = torch.logical_or(selected_pts_mask, selected_pts_mask2) stds = self.get_scaling[selected_pts_mask].repeat(N, 1) means = torch.zeros((stds.size(0), 3), device="cuda") samples = torch.normal(mean=means, std=stds)
rots = build_rotation(self._rotation[selected_pts_mask]).repeat(N, 1, 1)
2
2023-12-04 00:07:22+00:00
8k
JiahuiLei/GART
lib_guidance/mvdream/extern/MVDream/mvdream/ldm/modules/diffusionmodules/openaimodel.py
[ { "identifier": "checkpoint", "path": "lib_guidance/mvdream/extern/MVDream/mvdream/ldm/modules/diffusionmodules/util.py", "snippet": "def checkpoint(func, inputs, params, flag):\n \"\"\"\n Evaluate a function without caching intermediate activations, allowing for\n reduced memory at the expense...
from abc import abstractmethod from .util import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_module, normalization, timestep_embedding, ) from ..attention import SpatialTransformer, SpatialTransformer3D, exists from omegaconf.listconfig import ListConfig from omegaconf.listconfig import ListConfig import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F
5,166
n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model legacy=True, disable_self_attentions=None, num_attention_blocks=None, disable_middle_self_attn=False, use_linear_in_transformer=False, adm_in_channels=None, ): super().__init__() if use_spatial_transformer: assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...' if context_dim is not None: assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...' if type(context_dim) == ListConfig: context_dim = list(context_dim) if num_heads_upsample == -1: num_heads_upsample = num_heads if num_heads == -1: assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' if num_head_channels == -1: assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' self.image_size = image_size self.in_channels = in_channels self.model_channels = model_channels self.out_channels = out_channels if isinstance(num_res_blocks, int): self.num_res_blocks = len(channel_mult) * [num_res_blocks] else: if len(num_res_blocks) != len(channel_mult): raise ValueError("provide num_res_blocks either as an int (globally constant) or " "as a list/tuple (per-level) with the same length as channel_mult") self.num_res_blocks = num_res_blocks if disable_self_attentions is not None: # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not assert len(disable_self_attentions) == len(channel_mult) if num_attention_blocks is not None: assert len(num_attention_blocks) == len(self.num_res_blocks) assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks)))) print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. " f"This option has LESS priority than attention_resolutions {attention_resolutions}, " f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, " f"attention will still not be set.") self.attention_resolutions = attention_resolutions self.dropout = dropout self.channel_mult = channel_mult self.conv_resample = conv_resample self.num_classes = num_classes self.use_checkpoint = use_checkpoint self.dtype = th.float16 if use_fp16 else th.float32 self.dtype = th.bfloat16 if use_bf16 else self.dtype self.num_heads = num_heads self.num_head_channels = num_head_channels self.num_heads_upsample = num_heads_upsample self.predict_codebook_ids = n_embed is not None time_embed_dim = model_channels * 4 self.time_embed = nn.Sequential( linear(model_channels, time_embed_dim), nn.SiLU(), linear(time_embed_dim, time_embed_dim), ) if self.num_classes is not None: if isinstance(self.num_classes, int): self.label_emb = nn.Embedding(num_classes, time_embed_dim) elif self.num_classes == "continuous": print("setting up linear c_adm embedding layer") self.label_emb = nn.Linear(1, time_embed_dim) elif self.num_classes == "sequential": assert adm_in_channels is not None self.label_emb = nn.Sequential( nn.Sequential( linear(adm_in_channels, time_embed_dim), nn.SiLU(), linear(time_embed_dim, time_embed_dim), ) ) else: raise ValueError() self.input_blocks = nn.ModuleList( [ TimestepEmbedSequential( conv_nd(dims, in_channels, model_channels, 3, padding=1) ) ] ) self._feature_size = model_channels input_block_chans = [model_channels] ch = model_channels ds = 1 for level, mult in enumerate(channel_mult): for nr in range(self.num_res_blocks[level]): layers = [ ResBlock( ch, time_embed_dim, dropout, out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = mult * model_channels if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
# dummy replace def convert_module_to_f16(x): pass def convert_module_to_f32(x): pass ## go class AttentionPool2d(nn.Module): """ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py """ def __init__( self, spacial_dim: int, embed_dim: int, num_heads_channels: int, output_dim: int = None, ): super().__init__() self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5) self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1) self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1) self.num_heads = embed_dim // num_heads_channels self.attention = QKVAttention(self.num_heads) def forward(self, x): b, c, *_spatial = x.shape x = x.reshape(b, c, -1) # NC(HW) x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1) x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1) x = self.qkv_proj(x) x = self.attention(x) x = self.c_proj(x) return x[:, :, 0] class TimestepBlock(nn.Module): """ Any module where forward() takes timestep embeddings as a second argument. """ @abstractmethod def forward(self, x, emb): """ Apply the module to `x` given `emb` timestep embeddings. """ class TimestepEmbedSequential(nn.Sequential, TimestepBlock): """ A sequential module that passes timestep embeddings to the children that support it as an extra input. """ def forward(self, x, emb, context=None, num_frames=1): for layer in self: if isinstance(layer, TimestepBlock): x = layer(x, emb) elif isinstance(layer, SpatialTransformer3D): x = layer(x, context, num_frames=num_frames) elif isinstance(layer, SpatialTransformer): x = layer(x, context) else: x = layer(x) return x class Upsample(nn.Module): """ An upsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then upsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims if use_conv: self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding) def forward(self, x): assert x.shape[1] == self.channels if self.dims == 3: x = F.interpolate( x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest" ) else: x = F.interpolate(x, scale_factor=2, mode="nearest") if self.use_conv: x = self.conv(x) return x class TransposedUpsample(nn.Module): 'Learned 2x upsampling without padding' def __init__(self, channels, out_channels=None, ks=5): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2) def forward(self,x): return self.up(x) class Downsample(nn.Module): """ A downsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then downsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims stride = 2 if dims != 3 else (1, 2, 2) if use_conv: self.op = conv_nd( dims, self.channels, self.out_channels, 3, stride=stride, padding=padding ) else: assert self.channels == self.out_channels self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) def forward(self, x): assert x.shape[1] == self.channels return self.op(x) class ResBlock(TimestepBlock): """ A residual block that can optionally change the number of channels. :param channels: the number of input channels. :param emb_channels: the number of timestep embedding channels. :param dropout: the rate of dropout. :param out_channels: if specified, the number of out channels. :param use_conv: if True and out_channels is specified, use a spatial convolution instead of a smaller 1x1 convolution to change the channels in the skip connection. :param dims: determines if the signal is 1D, 2D, or 3D. :param use_checkpoint: if True, use gradient checkpointing on this module. :param up: if True, use this block for upsampling. :param down: if True, use this block for downsampling. """ def __init__( self, channels, emb_channels, dropout, out_channels=None, use_conv=False, use_scale_shift_norm=False, dims=2, use_checkpoint=False, up=False, down=False, ): super().__init__() self.channels = channels self.emb_channels = emb_channels self.dropout = dropout self.out_channels = out_channels or channels self.use_conv = use_conv self.use_checkpoint = use_checkpoint self.use_scale_shift_norm = use_scale_shift_norm self.in_layers = nn.Sequential( normalization(channels), nn.SiLU(), conv_nd(dims, channels, self.out_channels, 3, padding=1), ) self.updown = up or down if up: self.h_upd = Upsample(channels, False, dims) self.x_upd = Upsample(channels, False, dims) elif down: self.h_upd = Downsample(channels, False, dims) self.x_upd = Downsample(channels, False, dims) else: self.h_upd = self.x_upd = nn.Identity() self.emb_layers = nn.Sequential( nn.SiLU(), linear( emb_channels, 2 * self.out_channels if use_scale_shift_norm else self.out_channels, ), ) self.out_layers = nn.Sequential( normalization(self.out_channels), nn.SiLU(), nn.Dropout(p=dropout), zero_module( conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1) ), ) if self.out_channels == channels: self.skip_connection = nn.Identity() elif use_conv: self.skip_connection = conv_nd( dims, channels, self.out_channels, 3, padding=1 ) else: self.skip_connection = conv_nd(dims, channels, self.out_channels, 1) def forward(self, x, emb): """ Apply the block to a Tensor, conditioned on a timestep embedding. :param x: an [N x C x ...] Tensor of features. :param emb: an [N x emb_channels] Tensor of timestep embeddings. :return: an [N x C x ...] Tensor of outputs. """ return checkpoint( self._forward, (x, emb), self.parameters(), self.use_checkpoint ) def _forward(self, x, emb): if self.updown: in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] h = in_rest(x) h = self.h_upd(h) x = self.x_upd(x) h = in_conv(h) else: h = self.in_layers(x) emb_out = self.emb_layers(emb).type(h.dtype) while len(emb_out.shape) < len(h.shape): emb_out = emb_out[..., None] if self.use_scale_shift_norm: out_norm, out_rest = self.out_layers[0], self.out_layers[1:] scale, shift = th.chunk(emb_out, 2, dim=1) h = out_norm(h) * (1 + scale) + shift h = out_rest(h) else: h = h + emb_out h = self.out_layers(h) return self.skip_connection(x) + h class AttentionBlock(nn.Module): """ An attention block that allows spatial positions to attend to each other. Originally ported from here, but adapted to the N-d case. https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66. """ def __init__( self, channels, num_heads=1, num_head_channels=-1, use_checkpoint=False, use_new_attention_order=False, ): super().__init__() self.channels = channels if num_head_channels == -1: self.num_heads = num_heads else: assert ( channels % num_head_channels == 0 ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" self.num_heads = channels // num_head_channels self.use_checkpoint = use_checkpoint self.norm = normalization(channels) self.qkv = conv_nd(1, channels, channels * 3, 1) if use_new_attention_order: # split qkv before split heads self.attention = QKVAttention(self.num_heads) else: # split heads before split qkv self.attention = QKVAttentionLegacy(self.num_heads) self.proj_out = zero_module(conv_nd(1, channels, channels, 1)) def forward(self, x): return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!! #return pt_checkpoint(self._forward, x) # pytorch def _forward(self, x): b, c, *spatial = x.shape x = x.reshape(b, c, -1) qkv = self.qkv(self.norm(x)) h = self.attention(qkv) h = self.proj_out(h) return (x + h).reshape(b, c, *spatial) def count_flops_attn(model, _x, y): """ A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, ) """ b, c, *spatial = y[0].shape num_spatial = int(np.prod(spatial)) # We perform two matmuls with the same number of ops. # The first computes the weight matrix, the second computes # the combination of the value vectors. matmul_ops = 2 * b * (num_spatial ** 2) * c model.total_ops += th.DoubleTensor([matmul_ops]) class QKVAttentionLegacy(nn.Module): """ A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping """ def __init__(self, n_heads): super().__init__() self.n_heads = n_heads def forward(self, qkv): """ Apply QKV attention. :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention. """ bs, width, length = qkv.shape assert width % (3 * self.n_heads) == 0 ch = width // (3 * self.n_heads) q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) scale = 1 / math.sqrt(math.sqrt(ch)) weight = th.einsum( "bct,bcs->bts", q * scale, k * scale ) # More stable with f16 than dividing afterwards weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) a = th.einsum("bts,bcs->bct", weight, v) return a.reshape(bs, -1, length) @staticmethod def count_flops(model, _x, y): return count_flops_attn(model, _x, y) class QKVAttention(nn.Module): """ A module which performs QKV attention and splits in a different order. """ def __init__(self, n_heads): super().__init__() self.n_heads = n_heads def forward(self, qkv): """ Apply QKV attention. :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention. """ bs, width, length = qkv.shape assert width % (3 * self.n_heads) == 0 ch = width // (3 * self.n_heads) q, k, v = qkv.chunk(3, dim=1) scale = 1 / math.sqrt(math.sqrt(ch)) weight = th.einsum( "bct,bcs->bts", (q * scale).view(bs * self.n_heads, ch, length), (k * scale).view(bs * self.n_heads, ch, length), ) # More stable with f16 than dividing afterwards weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length)) return a.reshape(bs, -1, length) @staticmethod def count_flops(model, _x, y): return count_flops_attn(model, _x, y) class Timestep(nn.Module): def __init__(self, dim): super().__init__() self.dim = dim def forward(self, t): return timestep_embedding(t, self.dim) class UNetModel(nn.Module): """ The full UNet model with attention and timestep embedding. :param in_channels: channels in the input Tensor. :param model_channels: base channel count for the model. :param out_channels: channels in the output Tensor. :param num_res_blocks: number of residual blocks per downsample. :param attention_resolutions: a collection of downsample rates at which attention will take place. May be a set, list, or tuple. For example, if this contains 4, then at 4x downsampling, attention will be used. :param dropout: the dropout probability. :param channel_mult: channel multiplier for each level of the UNet. :param conv_resample: if True, use learned convolutions for upsampling and downsampling. :param dims: determines if the signal is 1D, 2D, or 3D. :param num_classes: if specified (as an int), then this model will be class-conditional with `num_classes` classes. :param use_checkpoint: use gradient checkpointing to reduce memory usage. :param num_heads: the number of attention heads in each attention layer. :param num_heads_channels: if specified, ignore num_heads and instead use a fixed channel width per attention head. :param num_heads_upsample: works with num_heads to set a different number of heads for upsampling. Deprecated. :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. :param resblock_updown: use residual blocks for up/downsampling. :param use_new_attention_order: use a different attention pattern for potentially increased efficiency. """ def __init__( self, image_size, in_channels, model_channels, out_channels, num_res_blocks, attention_resolutions, dropout=0, channel_mult=(1, 2, 4, 8), conv_resample=True, dims=2, num_classes=None, use_checkpoint=False, use_fp16=False, use_bf16=False, num_heads=-1, num_head_channels=-1, num_heads_upsample=-1, use_scale_shift_norm=False, resblock_updown=False, use_new_attention_order=False, use_spatial_transformer=False, # custom transformer support transformer_depth=1, # custom transformer support context_dim=None, # custom transformer support n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model legacy=True, disable_self_attentions=None, num_attention_blocks=None, disable_middle_self_attn=False, use_linear_in_transformer=False, adm_in_channels=None, ): super().__init__() if use_spatial_transformer: assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...' if context_dim is not None: assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...' if type(context_dim) == ListConfig: context_dim = list(context_dim) if num_heads_upsample == -1: num_heads_upsample = num_heads if num_heads == -1: assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' if num_head_channels == -1: assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' self.image_size = image_size self.in_channels = in_channels self.model_channels = model_channels self.out_channels = out_channels if isinstance(num_res_blocks, int): self.num_res_blocks = len(channel_mult) * [num_res_blocks] else: if len(num_res_blocks) != len(channel_mult): raise ValueError("provide num_res_blocks either as an int (globally constant) or " "as a list/tuple (per-level) with the same length as channel_mult") self.num_res_blocks = num_res_blocks if disable_self_attentions is not None: # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not assert len(disable_self_attentions) == len(channel_mult) if num_attention_blocks is not None: assert len(num_attention_blocks) == len(self.num_res_blocks) assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks)))) print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. " f"This option has LESS priority than attention_resolutions {attention_resolutions}, " f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, " f"attention will still not be set.") self.attention_resolutions = attention_resolutions self.dropout = dropout self.channel_mult = channel_mult self.conv_resample = conv_resample self.num_classes = num_classes self.use_checkpoint = use_checkpoint self.dtype = th.float16 if use_fp16 else th.float32 self.dtype = th.bfloat16 if use_bf16 else self.dtype self.num_heads = num_heads self.num_head_channels = num_head_channels self.num_heads_upsample = num_heads_upsample self.predict_codebook_ids = n_embed is not None time_embed_dim = model_channels * 4 self.time_embed = nn.Sequential( linear(model_channels, time_embed_dim), nn.SiLU(), linear(time_embed_dim, time_embed_dim), ) if self.num_classes is not None: if isinstance(self.num_classes, int): self.label_emb = nn.Embedding(num_classes, time_embed_dim) elif self.num_classes == "continuous": print("setting up linear c_adm embedding layer") self.label_emb = nn.Linear(1, time_embed_dim) elif self.num_classes == "sequential": assert adm_in_channels is not None self.label_emb = nn.Sequential( nn.Sequential( linear(adm_in_channels, time_embed_dim), nn.SiLU(), linear(time_embed_dim, time_embed_dim), ) ) else: raise ValueError() self.input_blocks = nn.ModuleList( [ TimestepEmbedSequential( conv_nd(dims, in_channels, model_channels, 3, padding=1) ) ] ) self._feature_size = model_channels input_block_chans = [model_channels] ch = model_channels ds = 1 for level, mult in enumerate(channel_mult): for nr in range(self.num_res_blocks[level]): layers = [ ResBlock( ch, time_embed_dim, dropout, out_channels=mult * model_channels, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, ) ] ch = mult * model_channels if ds in attention_resolutions: if num_head_channels == -1: dim_head = ch // num_heads else: num_heads = ch // num_head_channels dim_head = num_head_channels if legacy: #num_heads = 1 dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
if exists(disable_self_attentions):
9
2023-11-27 17:30:04+00:00
8k