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 |
|---|---|---|---|---|---|---|---|---|---|---|
camenduru/MotionDirector-hf | demo/motiondirector.py | [
{
"identifier": "export_to_video",
"path": "MotionDirector_train.py",
"snippet": "def export_to_video(video_frames, output_video_path, fps):\n video_writer = imageio.get_writer(output_video_path, fps=fps)\n for img in video_frames:\n video_writer.append_data(np.array(img))\n video_writer... | import os
import warnings
import torch
import random
import imageio
from typing import Optional
from diffusers import DDIMScheduler, TextToVideoSDPipeline
from einops import rearrange
from torch import Tensor
from torch.nn.functional import interpolate
from tqdm import trange
from MotionDirector_train import export_to_video, handle_memory_attention, load_primary_models, unet_and_text_g_c, freeze_models
from utils.lora_handler import LoraHandler
from utils.ddim_utils import ddim_inversion
from utils.lora import extract_lora_child_module | 4,311 | unet=unet.to(device=device, dtype=torch.half),
)
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
return pipe
def inverse_video(pipe, latents, num_steps):
ddim_inv_scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
ddim_inv_scheduler.set_timesteps(num_steps)
ddim_inv_latent = ddim_inversion(
pipe, ddim_inv_scheduler, video_latent=latents.to(pipe.device),
num_inv_steps=num_steps, prompt="")[-1]
return ddim_inv_latent
def prepare_input_latents(
pipe: TextToVideoSDPipeline,
batch_size: int,
num_frames: int,
height: int,
width: int,
latents_path:str,
model_select: str,
random_seed: int,
):
# initialize with random gaussian noise
scale = pipe.vae_scale_factor
shape = (batch_size, pipe.unet.config.in_channels, num_frames, height // scale, width // scale)
if random_seed > 1000:
torch.manual_seed(random_seed)
else:
random_seed = random.randint(100, 10000000)
torch.manual_seed(random_seed)
print(f"random_seed: {random_seed}")
if '1-' in model_select:
noise_prior = 0.3
elif '2-' in model_select:
noise_prior = 0.5
elif '3-' in model_select:
noise_prior = 0.
else:
noise_prior = 0.
if noise_prior > 0.:
cached_latents = torch.load(latents_path)
if 'inversion_noise' not in cached_latents:
latents = inverse_video(pipe, cached_latents['latents'].unsqueeze(0), 50).squeeze(0)
else:
latents = torch.load(latents_path)['inversion_noise'].unsqueeze(0)
if latents.shape[0] != batch_size:
latents = latents.repeat(batch_size, 1, 1, 1, 1)
if latents.shape != shape:
latents = interpolate(rearrange(latents, "b c f h w -> (b f) c h w", b=batch_size), (height // scale, width // scale), mode='bilinear')
latents = rearrange(latents, "(b f) c h w -> b c f h w", b=batch_size)
noise = torch.randn_like(latents, dtype=torch.half)
latents_base = noise
latents = (noise_prior) ** 0.5 * latents + (1 - noise_prior) ** 0.5 * noise
else:
latents = torch.randn(shape, dtype=torch.half)
latents_base = latents
return latents, latents_base, random_seed
class MotionDirector():
def __init__(self):
self.version = "0.0.0"
self.foundation_model_path = "./zeroscope_v2_576w/"
self.lora_path = "./MotionDirector_pretrained/dolly_zoom_(hitchcockian_zoom)/checkpoint-default/temporal/lora"
with torch.autocast("cuda", dtype=torch.half):
self.pipe = initialize_pipeline(model=self.foundation_model_path, lora_path=self.lora_path, lora_scale=1)
def reload_lora(self, lora_path):
if lora_path != self.lora_path:
self.lora_path = lora_path
with torch.autocast("cuda", dtype=torch.half):
self.pipe = initialize_pipeline(model=self.foundation_model_path, lora_path=self.lora_path)
def __call__(self, model_select, text_pormpt, neg_text_pormpt, random_seed, steps, guidance_scale, baseline_select):
model_select = str(model_select)
out_name = f"./outputs/inference"
out_name += f"{text_pormpt}".replace(' ', '_').replace(',', '').replace('.', '')
model_select_type = model_select.split('--')[1].strip()
model_select_type = model_select_type.lower().replace(' ', '_')
lora_path = f"./MotionDirector_pretrained/{model_select_type}/checkpoint-default/temporal/lora"
self.reload_lora(lora_path)
latents_folder = f"./MotionDirector_pretrained/{model_select_type}/cached_latents"
latents_path = f"{latents_folder}/{random.choice(os.listdir(latents_folder))}"
assert os.path.exists(lora_path)
device = "cuda"
with torch.autocast(device, dtype=torch.half):
# prepare input latents
with torch.no_grad():
init_latents, init_latents_base, random_seed = prepare_input_latents(
pipe=self.pipe,
batch_size=1,
num_frames=16,
height=384,
width=384,
latents_path=latents_path,
model_select=model_select,
random_seed=random_seed
)
video_frames = self.pipe(
prompt=text_pormpt,
negative_prompt=neg_text_pormpt,
width=384,
height=384,
num_frames=16,
num_inference_steps=steps,
guidance_scale=guidance_scale,
latents=init_latents
).frames
out_file = f"{out_name}_{random_seed}.mp4"
os.makedirs(os.path.dirname(out_file), exist_ok=True)
|
def initialize_pipeline(
model: str,
device: str = "cuda",
xformers: bool = True,
sdp: bool = True,
lora_path: str = "",
lora_rank: int = 32,
lora_scale: float = 1.0,
):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
scheduler, tokenizer, text_encoder, vae, unet = load_primary_models(model)
# Freeze any necessary models
freeze_models([vae, text_encoder, unet])
# Enable xformers if available
handle_memory_attention(xformers, sdp, unet)
lora_manager_temporal = LoraHandler(
version="cloneofsimo",
use_unet_lora=True,
use_text_lora=False,
save_for_webui=False,
only_for_webui=False,
unet_replace_modules=["TransformerTemporalModel"],
text_encoder_replace_modules=None,
lora_bias=None
)
unet_lora_params, unet_negation = lora_manager_temporal.add_lora_to_model(
True, unet, lora_manager_temporal.unet_replace_modules, 0, lora_path, r=lora_rank, scale=lora_scale)
unet.eval()
text_encoder.eval()
unet_and_text_g_c(unet, text_encoder, False, False)
pipe = TextToVideoSDPipeline.from_pretrained(
pretrained_model_name_or_path=model,
scheduler=scheduler,
tokenizer=tokenizer,
text_encoder=text_encoder.to(device=device, dtype=torch.half),
vae=vae.to(device=device, dtype=torch.half),
unet=unet.to(device=device, dtype=torch.half),
)
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
return pipe
def inverse_video(pipe, latents, num_steps):
ddim_inv_scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
ddim_inv_scheduler.set_timesteps(num_steps)
ddim_inv_latent = ddim_inversion(
pipe, ddim_inv_scheduler, video_latent=latents.to(pipe.device),
num_inv_steps=num_steps, prompt="")[-1]
return ddim_inv_latent
def prepare_input_latents(
pipe: TextToVideoSDPipeline,
batch_size: int,
num_frames: int,
height: int,
width: int,
latents_path:str,
model_select: str,
random_seed: int,
):
# initialize with random gaussian noise
scale = pipe.vae_scale_factor
shape = (batch_size, pipe.unet.config.in_channels, num_frames, height // scale, width // scale)
if random_seed > 1000:
torch.manual_seed(random_seed)
else:
random_seed = random.randint(100, 10000000)
torch.manual_seed(random_seed)
print(f"random_seed: {random_seed}")
if '1-' in model_select:
noise_prior = 0.3
elif '2-' in model_select:
noise_prior = 0.5
elif '3-' in model_select:
noise_prior = 0.
else:
noise_prior = 0.
if noise_prior > 0.:
cached_latents = torch.load(latents_path)
if 'inversion_noise' not in cached_latents:
latents = inverse_video(pipe, cached_latents['latents'].unsqueeze(0), 50).squeeze(0)
else:
latents = torch.load(latents_path)['inversion_noise'].unsqueeze(0)
if latents.shape[0] != batch_size:
latents = latents.repeat(batch_size, 1, 1, 1, 1)
if latents.shape != shape:
latents = interpolate(rearrange(latents, "b c f h w -> (b f) c h w", b=batch_size), (height // scale, width // scale), mode='bilinear')
latents = rearrange(latents, "(b f) c h w -> b c f h w", b=batch_size)
noise = torch.randn_like(latents, dtype=torch.half)
latents_base = noise
latents = (noise_prior) ** 0.5 * latents + (1 - noise_prior) ** 0.5 * noise
else:
latents = torch.randn(shape, dtype=torch.half)
latents_base = latents
return latents, latents_base, random_seed
class MotionDirector():
def __init__(self):
self.version = "0.0.0"
self.foundation_model_path = "./zeroscope_v2_576w/"
self.lora_path = "./MotionDirector_pretrained/dolly_zoom_(hitchcockian_zoom)/checkpoint-default/temporal/lora"
with torch.autocast("cuda", dtype=torch.half):
self.pipe = initialize_pipeline(model=self.foundation_model_path, lora_path=self.lora_path, lora_scale=1)
def reload_lora(self, lora_path):
if lora_path != self.lora_path:
self.lora_path = lora_path
with torch.autocast("cuda", dtype=torch.half):
self.pipe = initialize_pipeline(model=self.foundation_model_path, lora_path=self.lora_path)
def __call__(self, model_select, text_pormpt, neg_text_pormpt, random_seed, steps, guidance_scale, baseline_select):
model_select = str(model_select)
out_name = f"./outputs/inference"
out_name += f"{text_pormpt}".replace(' ', '_').replace(',', '').replace('.', '')
model_select_type = model_select.split('--')[1].strip()
model_select_type = model_select_type.lower().replace(' ', '_')
lora_path = f"./MotionDirector_pretrained/{model_select_type}/checkpoint-default/temporal/lora"
self.reload_lora(lora_path)
latents_folder = f"./MotionDirector_pretrained/{model_select_type}/cached_latents"
latents_path = f"{latents_folder}/{random.choice(os.listdir(latents_folder))}"
assert os.path.exists(lora_path)
device = "cuda"
with torch.autocast(device, dtype=torch.half):
# prepare input latents
with torch.no_grad():
init_latents, init_latents_base, random_seed = prepare_input_latents(
pipe=self.pipe,
batch_size=1,
num_frames=16,
height=384,
width=384,
latents_path=latents_path,
model_select=model_select,
random_seed=random_seed
)
video_frames = self.pipe(
prompt=text_pormpt,
negative_prompt=neg_text_pormpt,
width=384,
height=384,
num_frames=16,
num_inference_steps=steps,
guidance_scale=guidance_scale,
latents=init_latents
).frames
out_file = f"{out_name}_{random_seed}.mp4"
os.makedirs(os.path.dirname(out_file), exist_ok=True) | export_to_video(video_frames, out_file, 8) | 0 | 2023-12-11 04:51:39+00:00 | 8k |
Yingyue-L/Mamba-LLaVA | llava/serve/cli.py | [
{
"identifier": "IMAGE_TOKEN_INDEX",
"path": "llava/constants.py",
"snippet": "IMAGE_TOKEN_INDEX = -200"
},
{
"identifier": "DEFAULT_IMAGE_TOKEN",
"path": "llava/constants.py",
"snippet": "DEFAULT_IMAGE_TOKEN = \"<image>\""
},
{
"identifier": "DEFAULT_IM_START_TOKEN",
"path":... | import argparse
import torch
import requests
from llava.constants import IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN, DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN
from llava.conversation import conv_templates, SeparatorStyle
from llava.model.builder import load_pretrained_model
from llava.utils import disable_torch_init
from llava.mm_utils import process_images, tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
from PIL import Image
from PIL import Image
from io import BytesIO
from transformers import TextStreamer | 3,761 |
def load_image(image_file):
if image_file.startswith('http://') or image_file.startswith('https://'):
response = requests.get(image_file)
image = Image.open(BytesIO(response.content)).convert('RGB')
else:
image = Image.open(image_file).convert('RGB')
return image
def main(args):
# Model
disable_torch_init()
model_name = get_model_name_from_path(args.model_path)
tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device)
if 'llama-2' in model_name.lower():
conv_mode = "llava_llama_2"
elif "v1" in model_name.lower():
conv_mode = "llava_v1"
elif "mpt" in model_name.lower():
conv_mode = "mpt"
else:
conv_mode = "llava_v0"
if args.conv_mode is not None and conv_mode != args.conv_mode:
print('[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}'.format(conv_mode, args.conv_mode, args.conv_mode))
else:
args.conv_mode = conv_mode
conv = conv_templates[args.conv_mode].copy()
if "mpt" in model_name.lower():
roles = ('user', 'assistant')
else:
roles = conv.roles
image = load_image(args.image_file)
# Similar operation in model_worker.py
image_tensor = process_images([image], image_processor, model.config)
if type(image_tensor) is list:
image_tensor = [image.to(model.device, dtype=torch.float16) for image in image_tensor]
else:
image_tensor = image_tensor.to(model.device, dtype=torch.float16)
while True:
try:
inp = input(f"{roles[0]}: ")
except EOFError:
inp = ""
if not inp:
print("exit...")
break
print(f"{roles[1]}: ", end="")
if image is not None:
# first message
if model.config.mm_use_im_start_end:
inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + inp
else:
inp = DEFAULT_IMAGE_TOKEN + '\n' + inp
conv.append_message(conv.roles[0], inp)
image = None
else:
# later messages
conv.append_message(conv.roles[0], inp)
conv.append_message(conv.roles[1], None)
prompt = conv.get_prompt()
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(model.device)
|
def load_image(image_file):
if image_file.startswith('http://') or image_file.startswith('https://'):
response = requests.get(image_file)
image = Image.open(BytesIO(response.content)).convert('RGB')
else:
image = Image.open(image_file).convert('RGB')
return image
def main(args):
# Model
disable_torch_init()
model_name = get_model_name_from_path(args.model_path)
tokenizer, model, image_processor, context_len = load_pretrained_model(args.model_path, args.model_base, model_name, args.load_8bit, args.load_4bit, device=args.device)
if 'llama-2' in model_name.lower():
conv_mode = "llava_llama_2"
elif "v1" in model_name.lower():
conv_mode = "llava_v1"
elif "mpt" in model_name.lower():
conv_mode = "mpt"
else:
conv_mode = "llava_v0"
if args.conv_mode is not None and conv_mode != args.conv_mode:
print('[WARNING] the auto inferred conversation mode is {}, while `--conv-mode` is {}, using {}'.format(conv_mode, args.conv_mode, args.conv_mode))
else:
args.conv_mode = conv_mode
conv = conv_templates[args.conv_mode].copy()
if "mpt" in model_name.lower():
roles = ('user', 'assistant')
else:
roles = conv.roles
image = load_image(args.image_file)
# Similar operation in model_worker.py
image_tensor = process_images([image], image_processor, model.config)
if type(image_tensor) is list:
image_tensor = [image.to(model.device, dtype=torch.float16) for image in image_tensor]
else:
image_tensor = image_tensor.to(model.device, dtype=torch.float16)
while True:
try:
inp = input(f"{roles[0]}: ")
except EOFError:
inp = ""
if not inp:
print("exit...")
break
print(f"{roles[1]}: ", end="")
if image is not None:
# first message
if model.config.mm_use_im_start_end:
inp = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + inp
else:
inp = DEFAULT_IMAGE_TOKEN + '\n' + inp
conv.append_message(conv.roles[0], inp)
image = None
else:
# later messages
conv.append_message(conv.roles[0], inp)
conv.append_message(conv.roles[1], None)
prompt = conv.get_prompt()
input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt').unsqueeze(0).to(model.device) | stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2 | 4 | 2023-12-09 09:39:13+00:00 | 8k |
Theia-4869/MoSA | src/models/vit_adapter/swin_adapter.py | [
{
"identifier": "Mlp",
"path": "src/models/vit_backbones/swin_transformer.py",
"snippet": "class Mlp(nn.Module):\n def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):\n super().__init__()\n out_features = out_features or in_features\n ... | import copy
import math
import numpy as np
import torch
import torch.nn as nn
from ..vit_backbones.swin_transformer import Mlp, SwinTransformerBlock, BasicLayer, PatchMerging, SwinTransformer
from ...utils import logging | 6,072 | #!/usr/bin/env python3
"""
vit with adapter
"""
logger = logging.get_logger("MOSA")
class AdaptedMlp(Mlp):
def __init__(
self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.,
adapter_config=None, adapter_scalar=1.0, dropout=0.0
):
super(AdaptedMlp, self).__init__(in_features, hidden_features, out_features, act_layer, drop)
self.adapter_config = adapter_config
if adapter_scalar is None:
self.adapter_scale = nn.Parameter(torch.ones(1))
else:
self.adapter_scale = adapter_scalar
self.dropout = dropout
out_features = out_features or in_features
self.adapter_down = nn.Linear(
in_features,
adapter_config.BOTTLENECK_SIZE
)
self.adapter_up = nn.Linear(
adapter_config.BOTTLENECK_SIZE,
out_features
)
self.adapter_act_fn = nn.ReLU()
nn.init.kaiming_uniform_(self.adapter_down.weight, a=math.sqrt(5))
nn.init.zeros_(self.adapter_down.bias)
nn.init.zeros_(self.adapter_up.weight)
nn.init.zeros_(self.adapter_up.bias)
def forward(self, x):
# same as reguluar Mlp block
h = x
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
# start to insert adapter layers...
adpt = self.adapter_down(h)
adpt = self.adapter_act_fn(adpt)
adpt = nn.functional.dropout(adpt, p=self.dropout, training=self.training)
adpt = self.adapter_up(adpt)
x = adpt * self.adapter_scale + x
# ...end
return x
| #!/usr/bin/env python3
"""
vit with adapter
"""
logger = logging.get_logger("MOSA")
class AdaptedMlp(Mlp):
def __init__(
self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.,
adapter_config=None, adapter_scalar=1.0, dropout=0.0
):
super(AdaptedMlp, self).__init__(in_features, hidden_features, out_features, act_layer, drop)
self.adapter_config = adapter_config
if adapter_scalar is None:
self.adapter_scale = nn.Parameter(torch.ones(1))
else:
self.adapter_scale = adapter_scalar
self.dropout = dropout
out_features = out_features or in_features
self.adapter_down = nn.Linear(
in_features,
adapter_config.BOTTLENECK_SIZE
)
self.adapter_up = nn.Linear(
adapter_config.BOTTLENECK_SIZE,
out_features
)
self.adapter_act_fn = nn.ReLU()
nn.init.kaiming_uniform_(self.adapter_down.weight, a=math.sqrt(5))
nn.init.zeros_(self.adapter_down.bias)
nn.init.zeros_(self.adapter_up.weight)
nn.init.zeros_(self.adapter_up.bias)
def forward(self, x):
# same as reguluar Mlp block
h = x
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
# start to insert adapter layers...
adpt = self.adapter_down(h)
adpt = self.adapter_act_fn(adpt)
adpt = nn.functional.dropout(adpt, p=self.dropout, training=self.training)
adpt = self.adapter_up(adpt)
x = adpt * self.adapter_scale + x
# ...end
return x
| class AdaptedSwinTransformerBlock(SwinTransformerBlock): | 1 | 2023-12-06 07:50:16+00:00 | 8k |
khwong-c/syn-magia | tests/core/test_const.py | [
{
"identifier": "Constant",
"path": "magia/core.py",
"snippet": "class Constant(Signal):\n \"\"\"\n Representing a constant signal. The value stored in bytes representing the constance driver.\n \"\"\"\n new_const_counter = count(0)\n\n def __init__(\n self,\n value,... | from pathlib import Path
from cocotb_test.simulator import run as sim_run
from magia import Constant, Module, Output
import cocotb.clock
import pytest
import tests.helper as helper | 3,840 |
test_constants = [
# Format: (value, width, signed) # noqa: ERA001
(0, 8, False),
(0, 8, True),
(0xFF, 8, False),
(-1, 8, True),
(0x0F, 8, False),
(0x0F, 8, True),
(0x0F, 4, False),
(0x0F, 4, True),
(0x0F, 2, False),
(0x0F, 2, True),
(0x0F, 1, False),
(0x0F, 1, True),
(0x0F, 16, False),
(0x0F, 16, True),
(0x0F, 32, False),
(0x0F, 32, True),
(0x0F, 64, False),
(0x0F, 64, True),
(-10, 3, True),
]
test_constants += [(i, 5, True) for i in range(-16, 16)]
test_constants += [(i, 5, False) for i in range(0, 32)]
class AssignmentModule(Module):
def __init__(self, constant_list, **kwargs):
super().__init__(**kwargs)
for i, (value, width, signed) in enumerate(constant_list):
port_name = f"q{i}"
|
test_constants = [
# Format: (value, width, signed) # noqa: ERA001
(0, 8, False),
(0, 8, True),
(0xFF, 8, False),
(-1, 8, True),
(0x0F, 8, False),
(0x0F, 8, True),
(0x0F, 4, False),
(0x0F, 4, True),
(0x0F, 2, False),
(0x0F, 2, True),
(0x0F, 1, False),
(0x0F, 1, True),
(0x0F, 16, False),
(0x0F, 16, True),
(0x0F, 32, False),
(0x0F, 32, True),
(0x0F, 64, False),
(0x0F, 64, True),
(-10, 3, True),
]
test_constants += [(i, 5, True) for i in range(-16, 16)]
test_constants += [(i, 5, False) for i in range(0, 32)]
class AssignmentModule(Module):
def __init__(self, constant_list, **kwargs):
super().__init__(**kwargs)
for i, (value, width, signed) in enumerate(constant_list):
port_name = f"q{i}" | self.io += Output(port_name, width, signed=signed) | 1 | 2023-12-12 22:50:43+00:00 | 8k |
batmanlab/DrasCLR | train.py | [
{
"identifier": "Encoder",
"path": "models/cnn3d.py",
"snippet": "class Encoder(nn.Module):\n\n def __init__(self, rep_dim, moco_dim, num_experts, num_coordinates):\n super(Encoder, self).__init__()\n self.rep_dim = rep_dim\n self.moco_dim = moco_dim\n self.num_experts = n... | import os
import argparse
import builtins
import math
import random
import shutil
import time
import warnings
import json
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distributed
import models.loader as DrasCLR_Loader
from tensorboard_logger import configure, log_value
from models.cnn3d import Encoder
from models.builder import DrasCLR
from data.copd_patch import COPD_dataset
from monai.transforms import Compose, RandGaussianNoise, RandAffine, Rand3DElastic, RandAdjustContrast | 6,901 | help='root directory of registered images in COPD dataset')
parser.add_argument('--label-name', default=["FEV1pp_utah", "FEV1_FVC_utah", "finalGold"], nargs='+',
help='phenotype label names')
parser.add_argument('--label-name-set2', default=["Exacerbation_Frequency", "MMRCDyspneaScor"], nargs='+',
help='phenotype label names')
parser.add_argument('--visual-score', default=["Emph_Severity", "Emph_Paraseptal"], nargs='+',
help='phenotype label names')
parser.add_argument('--P2-Pheno', default=["Exacerbation_Frequency_P2"], nargs='+',
help='phenotype label names')
parser.add_argument('--nhw-only', action='store_true',
help='only include white people')
parser.add_argument('--fold', default=0, type=int,
help='fold index of cross validation')
# MoCo specific configs:
parser.add_argument('--rep-dim', default=128, type=int,
help='feature dimension (default: 128)')
parser.add_argument('--moco-dim', default=128, type=int,
help='feature dimension (default: 128)')
parser.add_argument('--moco-k', default=4096, type=int,
help='queue size; number of negative keys (default: 4098)')
parser.add_argument('--moco-m', default=0.999, type=float,
help='moco momentum of updating key encoder (default: 0.999)')
parser.add_argument('--moco-t', default=0.2, type=float,
help='softmax temperature (default: 0.2)')
# options for moco v2
parser.add_argument('--mlp', action='store_false',
help='use mlp head')
parser.add_argument('--cos', action='store_false',
help='use cosine lr schedule')
# experiment configs
parser.add_argument('--adj-thres', default=0.18, type=float,
help='patch adjacent threshold (default: 0.18)')
parser.add_argument('--k-neighbors', default=2, type=int,
help='top k nearest neighbors of the anchor patch in the atlas image.')
parser.add_argument('--beta', default=1.0, type=float,
help='scaling factor of neighbor InfoNCE loss. (default: 1.0)')
parser.add_argument('--warm-up', default=0, type=int,
help='number of warm-up epochs before training neighbor contrastive loss.')
parser.add_argument('--num-experts', default=8, type=int,
help='number of experts in CondConv layer.')
parser.add_argument('--num-coordinates', default=1, type=int,
help='number of input coordinates.')
parser.add_argument('--augmentation', default='agc',
help='initials of augmentation including: (f)lip, (a)ffine, (e)lastic, (g)uassian, (c)ontrast.')
parser.add_argument('--exp-name', default='debug_patch', type=str,
help='experiment name')
def main():
# read configurations
args = parser.parse_args()
# define and create the experiment directory
exp_dir = os.path.join('./ssl_exp', args.exp_name)
if not os.path.isdir(exp_dir):
os.makedirs(exp_dir, exist_ok=True)
# save configurations to a dictionary
with open(os.path.join(exp_dir, 'configs.json'), 'w') as f:
json.dump(vars(args), f, indent=2)
f.close()
if args.seed is not None:
random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed)
torch.backends.cudnn.benchmark = True
if args.gpu is not None:
warnings.warn('You have chosen a specific GPU. This will completely '
'disable data parallelism.')
if args.dist_url == "env://" and args.world_size == -1:
args.world_size = int(os.environ["WORLD_SIZE"])
args.distributed = args.world_size > 1 or args.multiprocessing_distributed
print("Distributed:", args.distributed)
#ngpus_per_node = torch.cuda.device_count()
ngpus_per_node = args.npgus_per_node
if args.multiprocessing_distributed:
# Since we have ngpus_per_node processes per node, the total world_size
# needs to be adjusted accordingly
args.world_size = ngpus_per_node * args.world_size
# Use torch.multiprocessing.spawn to launch distributed processes: the
# main_worker process function
mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args))
else:
# Simply call main_worker function
main_worker(args.gpu, ngpus_per_node, args)
def main_worker(gpu, ngpus_per_node, args):
args.gpu = gpu
# suppress printing if not master
if args.multiprocessing_distributed and args.gpu != 0:
def print_pass(*args):
pass
builtins.print = print_pass
if args.gpu is not None:
print("Use GPU: {} for training".format(args.gpu))
if args.distributed:
if args.dist_url == "env://" and args.rank == -1:
args.rank = int(os.environ["RANK"])
if args.multiprocessing_distributed:
# For multiprocessing distributed training, rank needs to be the
# global rank among all the processes
args.rank = args.rank * ngpus_per_node + gpu
dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
world_size=args.world_size, rank=args.rank)
if args.rank == 0:
configure(os.path.join('./ssl_exp', args.exp_name))
# create patch-level encoder
|
parser = argparse.ArgumentParser(description='3D CT Images Self-Supervised Training Patch-level')
parser.add_argument('--arch', metavar='ARCH', default='custom')
parser.add_argument('--workers', default=0, type=int, metavar='N',
help='patch-level number of data loading workers (default: 0)')
parser.add_argument('--epochs', default=20, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('--batch-size', default=64, type=int,
metavar='N',
help='patch-level mini-batch size (default: 32), this is the total '
'batch size of all GPUs on the current node when '
'using Data Parallel or Distributed Data Parallel')
parser.add_argument('--lr', '--learning-rate', default=0.01, type=float,
metavar='LR', help='initial learning rate', dest='lr')
parser.add_argument('--start-epoch', default=0, type=int, metavar='N',
help='manual epoch number (useful on restarts)')
parser.add_argument('--schedule', default=[120, 160], nargs='*', type=int,
help='learning rate schedule (when to drop lr by 10x)')
parser.add_argument('--momentum', default=0.9, type=float, metavar='M',
help='momentum of SGD solver')
parser.add_argument('--weight-decay', default=1e-4, type=float,
metavar='W', help='weight decay (default: 1e-4)',
dest='weight_decay')
parser.add_argument('--print-freq', default=10, type=int,
metavar='N', help='print frequency (default: 10)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to latest patch-level checkpoint (default: None)')
parser.add_argument('--world-size', default=1, type=int,
help='number of nodes for distributed training')
parser.add_argument('--rank', default=0, type=int,
help='node rank for distributed training')
parser.add_argument('--dist-url', default='tcp://localhost:10000', type=str,
help='url used to set up distributed training')
parser.add_argument('--dist-backend', default='nccl', type=str,
help='distributed backend')
parser.add_argument('--seed', default=0, type=int,
help='seed for initializing training. ')
parser.add_argument('--gpu', default=None, type=int,
help='GPU id to use.')
parser.add_argument('--multiprocessing-distributed', action='store_false',
help='use multi-processing distributed training to launch '
'N processes per node, which has N GPUs. This is the '
'fastest way to use PyTorch for either single node or '
'multi node data parallel training')
parser.add_argument('--npgus-per-node', default=2, type=int,
help='number of gpus per node.')
# image data configs:
parser.add_argument('--stage', default='training', type=str,
help='stage: training or testing')
parser.add_argument('--num-patch', default=581, type=int,
help='total number of patches in the atlas image.')
parser.add_argument('--root-dir', default='/ocean/projects/asc170022p/lisun/copd/gnn_shared/data/patch_data_32_6_reg_mask/',
help='root directory of registered images in COPD dataset')
parser.add_argument('--label-name', default=["FEV1pp_utah", "FEV1_FVC_utah", "finalGold"], nargs='+',
help='phenotype label names')
parser.add_argument('--label-name-set2', default=["Exacerbation_Frequency", "MMRCDyspneaScor"], nargs='+',
help='phenotype label names')
parser.add_argument('--visual-score', default=["Emph_Severity", "Emph_Paraseptal"], nargs='+',
help='phenotype label names')
parser.add_argument('--P2-Pheno', default=["Exacerbation_Frequency_P2"], nargs='+',
help='phenotype label names')
parser.add_argument('--nhw-only', action='store_true',
help='only include white people')
parser.add_argument('--fold', default=0, type=int,
help='fold index of cross validation')
# MoCo specific configs:
parser.add_argument('--rep-dim', default=128, type=int,
help='feature dimension (default: 128)')
parser.add_argument('--moco-dim', default=128, type=int,
help='feature dimension (default: 128)')
parser.add_argument('--moco-k', default=4096, type=int,
help='queue size; number of negative keys (default: 4098)')
parser.add_argument('--moco-m', default=0.999, type=float,
help='moco momentum of updating key encoder (default: 0.999)')
parser.add_argument('--moco-t', default=0.2, type=float,
help='softmax temperature (default: 0.2)')
# options for moco v2
parser.add_argument('--mlp', action='store_false',
help='use mlp head')
parser.add_argument('--cos', action='store_false',
help='use cosine lr schedule')
# experiment configs
parser.add_argument('--adj-thres', default=0.18, type=float,
help='patch adjacent threshold (default: 0.18)')
parser.add_argument('--k-neighbors', default=2, type=int,
help='top k nearest neighbors of the anchor patch in the atlas image.')
parser.add_argument('--beta', default=1.0, type=float,
help='scaling factor of neighbor InfoNCE loss. (default: 1.0)')
parser.add_argument('--warm-up', default=0, type=int,
help='number of warm-up epochs before training neighbor contrastive loss.')
parser.add_argument('--num-experts', default=8, type=int,
help='number of experts in CondConv layer.')
parser.add_argument('--num-coordinates', default=1, type=int,
help='number of input coordinates.')
parser.add_argument('--augmentation', default='agc',
help='initials of augmentation including: (f)lip, (a)ffine, (e)lastic, (g)uassian, (c)ontrast.')
parser.add_argument('--exp-name', default='debug_patch', type=str,
help='experiment name')
def main():
# read configurations
args = parser.parse_args()
# define and create the experiment directory
exp_dir = os.path.join('./ssl_exp', args.exp_name)
if not os.path.isdir(exp_dir):
os.makedirs(exp_dir, exist_ok=True)
# save configurations to a dictionary
with open(os.path.join(exp_dir, 'configs.json'), 'w') as f:
json.dump(vars(args), f, indent=2)
f.close()
if args.seed is not None:
random.seed(args.seed)
torch.manual_seed(args.seed)
torch.cuda.manual_seed_all(args.seed)
torch.backends.cudnn.benchmark = True
if args.gpu is not None:
warnings.warn('You have chosen a specific GPU. This will completely '
'disable data parallelism.')
if args.dist_url == "env://" and args.world_size == -1:
args.world_size = int(os.environ["WORLD_SIZE"])
args.distributed = args.world_size > 1 or args.multiprocessing_distributed
print("Distributed:", args.distributed)
#ngpus_per_node = torch.cuda.device_count()
ngpus_per_node = args.npgus_per_node
if args.multiprocessing_distributed:
# Since we have ngpus_per_node processes per node, the total world_size
# needs to be adjusted accordingly
args.world_size = ngpus_per_node * args.world_size
# Use torch.multiprocessing.spawn to launch distributed processes: the
# main_worker process function
mp.spawn(main_worker, nprocs=ngpus_per_node, args=(ngpus_per_node, args))
else:
# Simply call main_worker function
main_worker(args.gpu, ngpus_per_node, args)
def main_worker(gpu, ngpus_per_node, args):
args.gpu = gpu
# suppress printing if not master
if args.multiprocessing_distributed and args.gpu != 0:
def print_pass(*args):
pass
builtins.print = print_pass
if args.gpu is not None:
print("Use GPU: {} for training".format(args.gpu))
if args.distributed:
if args.dist_url == "env://" and args.rank == -1:
args.rank = int(os.environ["RANK"])
if args.multiprocessing_distributed:
# For multiprocessing distributed training, rank needs to be the
# global rank among all the processes
args.rank = args.rank * ngpus_per_node + gpu
dist.init_process_group(backend=args.dist_backend, init_method=args.dist_url,
world_size=args.world_size, rank=args.rank)
if args.rank == 0:
configure(os.path.join('./ssl_exp', args.exp_name))
# create patch-level encoder | model = DrasCLR( | 1 | 2023-12-09 02:33:53+00:00 | 8k |
CHDers/Traffic-Flow-Prediction-with-Graph-Neural-Networks | traffic_prediction.py | [
{
"identifier": "LoadData",
"path": "traffic_dataset.py",
"snippet": "class LoadData(Dataset): # 这个就是把读入的数据处理成模型需要的训练数据和测试数据,一个一个样本能读取出来\n def __init__(self, data_path, num_nodes, divide_days, time_interval, history_length, train_mode):\n \"\"\"\n :param data_path: list, [\"graph file ... | import os
import time
import h5py
import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import warnings
from torch.utils.data import DataLoader
from traffic_dataset import LoadData
from utils import Evaluation # 三种评价指标以及可视化类
from utils import visualize_result
from gcnnet import GCN
from chebnet import ChebNet
from gat import GATNet
from rich import print
from tqdm import tqdm | 4,888 | # @Time : 2020/8/25
# @Author : LeronQ
# @github : https://github.com/LeronQ
# Pytorch-基于GCN/GAT/Chebnet图神经网络实现的交通流预测(附代码): https://blog.csdn.net/yilulvxing/article/details/110306999
# traffic_prediction.py
# 这个就是上一小节处理数据自己写的的类,封装在traffic_dataset.py文件中
warnings.filterwarnings('ignore')
def main():
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # 配置GPU,因为可能有多个GPU,这里用了第0号GPU
# 第一步:准备数据(上一节已经准备好了,这里只是调用而已,链接在最开头)
| # @Time : 2020/8/25
# @Author : LeronQ
# @github : https://github.com/LeronQ
# Pytorch-基于GCN/GAT/Chebnet图神经网络实现的交通流预测(附代码): https://blog.csdn.net/yilulvxing/article/details/110306999
# traffic_prediction.py
# 这个就是上一小节处理数据自己写的的类,封装在traffic_dataset.py文件中
warnings.filterwarnings('ignore')
def main():
os.environ["CUDA_VISIBLE_DEVICES"] = "0" # 配置GPU,因为可能有多个GPU,这里用了第0号GPU
# 第一步:准备数据(上一节已经准备好了,这里只是调用而已,链接在最开头) | train_data = LoadData(data_path=["PeMS_04/PeMS04.csv", "PeMS_04/PeMS04.npz"], num_nodes=307, divide_days=[45, 14], | 0 | 2023-12-05 07:25:35+00:00 | 8k |
casiatao/PAD | detection/detectron2/modeling/backbone/vit_adapt.py | [
{
"identifier": "Backbone",
"path": "detection/detectron2/modeling/backbone/backbone.py",
"snippet": "class Backbone(nn.Module, metaclass=ABCMeta):\n \"\"\"\n Abstract base class for network backbones.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n The `__init__` method of any sub... | import logging
import math
import fvcore.nn.weight_init as weight_init
import torch
import torch.nn as nn
import torch.nn.functional as F
from detectron2.layers import CNNBlockBase, Conv2d, get_norm
from detectron2.modeling.backbone.fpn import _assert_strides_are_log2_contiguous
from .backbone import Backbone
from .utils import (
PatchEmbed,
add_decomposed_rel_pos,
get_abs_pos,
window_partition,
window_unpartition,
)
from timm.models.layers import DropPath, Mlp
from fairscale.nn.checkpoint import checkpoint_wrapper | 4,957 | window_block_indexes=(),
residual_block_indexes=(),
use_act_checkpoint=False,
pretrain_img_size=224,
pretrain_use_cls_token=True,
out_feature="last_feat",
down_size=64,
adapt_scalar="frozen",
init_value="0.0",
layernorm_option="in",
patch_wise_scalar=False,
fusion_method="concat",
):
"""
Args:
img_size (int): Input image size.
patch_size (int): Patch size.
in_chans (int): Number of input image channels.
embed_dim (int): Patch embedding dimension.
depth (int): Depth of ViT.
num_heads (int): Number of attention heads in each ViT block.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool): If True, add a learnable bias to query, key, value.
drop_path_rate (float): Stochastic depth rate.
norm_layer (nn.Module): Normalization layer.
act_layer (nn.Module): Activation layer.
use_abs_pos (bool): If True, use absolute positional embeddings.
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
window_size (int): Window size for window attention blocks.
window_block_indexes (list): Indexes for blocks using window attention.
residual_block_indexes (list): Indexes for blocks using conv propagation.
use_act_checkpoint (bool): If True, use activation checkpointing.
pretrain_img_size (int): input image size for pretraining models.
pretrain_use_cls_token (bool): If True, pretrainig models use class token.
out_feature (str): name of the feature from the last block.
"""
super().__init__()
self.pretrain_use_cls_token = pretrain_use_cls_token
self.patch_embed = PatchEmbed(
kernel_size=(patch_size, patch_size),
stride=(patch_size, patch_size),
in_chans=in_chans,
embed_dim=embed_dim,
)
if use_abs_pos:
# Initialize absolute positional embedding with pretrain image size.
num_patches = (pretrain_img_size // patch_size) * (pretrain_img_size // patch_size)
num_positions = (num_patches + 1) if pretrain_use_cls_token else num_patches
self.pos_embed = nn.Parameter(torch.zeros(1, num_positions, embed_dim))
else:
self.pos_embed = None
# stochastic depth decay rule
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
self.blocks = nn.ModuleList()
for i in range(depth):
block = Block(
dim=embed_dim,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias,
drop_path=dpr[i],
norm_layer=norm_layer,
act_layer=act_layer,
use_rel_pos=use_rel_pos,
rel_pos_zero_init=rel_pos_zero_init,
window_size=window_size if i in window_block_indexes else 0,
use_residual_block=i in residual_block_indexes,
input_size=(img_size // patch_size, img_size // patch_size),
down_size=down_size,
adapt_scalar=adapt_scalar,
init_value=init_value,
layernorm_option=layernorm_option,
patch_wise_scalar=patch_wise_scalar,
fusion_method=fusion_method,
)
if use_act_checkpoint:
# TODO: use torch.utils.checkpoint
block = checkpoint_wrapper(block)
self.blocks.append(block)
self._out_feature_channels = {out_feature: embed_dim}
self._out_feature_strides = {out_feature: patch_size}
self._out_features = [out_feature]
if self.pos_embed is not None:
nn.init.trunc_normal_(self.pos_embed, std=0.02)
self.apply(self._init_weights)
# init adapter
for i, blk in enumerate(self.blocks):
nn.init.kaiming_uniform_(blk.adaptmlp.down_proj.weight, a=math.sqrt(5))
nn.init.zeros_(blk.adaptmlp.up_proj.weight)
nn.init.zeros_(blk.adaptmlp.down_proj.bias)
nn.init.zeros_(blk.adaptmlp.up_proj.bias)
if patch_wise_scalar:
nn.init.zeros_(blk.scalar_pred.weight)
if blk.scalar_pred.bias is not None:
nn.init.zeros_(blk.scalar_pred.bias)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
nn.init.trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def forward(self, x):
x = self.patch_embed(x)
if self.pos_embed is not None:
|
logger = logging.getLogger(__name__)
__all__ = ["ViT_adapt", "SimpleFeaturePyramid", "get_vit_lr_decay_rate"]
class Adapter(nn.Module):
def __init__(self,
d_model,
down_size = 64,
dropout=0.0,
adapter_scalar="frozen",
init_value="0.0",
adapter_layernorm_option="in",
patch_wise_scalar=False):
super().__init__()
self.n_embd = d_model
self.down_size = down_size
#_before
self.adapter_layernorm_option = adapter_layernorm_option
self.adapter_layer_norm_before = None
if adapter_layernorm_option == "in" or adapter_layernorm_option == "out":
self.adapter_layer_norm_before = nn.LayerNorm(self.n_embd)
self.patch_wise_scalar = patch_wise_scalar
if patch_wise_scalar:
self.scale = None
else:
if adapter_scalar == "learnable_scalar":
self.scale = nn.Parameter(torch.ones(1) * 0.5)
else:
if init_value != "0.0":
self.scale = float(init_value)
else:
self.register_buffer('scale', torch.ones(1) * 0.5)
self.down_proj = nn.Linear(self.n_embd, self.down_size)
self.non_linear_func = nn.ReLU()
self.up_proj = nn.Linear(self.down_size, self.n_embd)
self.dropout = dropout
def forward(self, x, add_residual=False, residual=None):
residual = x if residual is None else residual
if self.adapter_layernorm_option == 'in':
x = self.adapter_layer_norm_before(x)
down = self.down_proj(x)
down = self.non_linear_func(down)
down = nn.functional.dropout(down, p=self.dropout, training=self.training)
up = self.up_proj(down)
if add_residual:
output = up + residual
else:
output = up
return output, self.scale
class Attention(nn.Module):
"""Multi-head Attention block with relative position embeddings."""
def __init__(
self,
dim,
num_heads=8,
qkv_bias=True,
use_rel_pos=False,
rel_pos_zero_init=True,
input_size=None,
):
"""
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads.
qkv_bias (bool: If True, add a learnable bias to query, key, value.
rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
input_size (int or None): Input resolution for calculating the relative positional
parameter size.
"""
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = head_dim**-0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.proj = nn.Linear(dim, dim)
self.use_rel_pos = use_rel_pos
if self.use_rel_pos:
# initialize relative positional embeddings
self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
if not rel_pos_zero_init:
nn.init.trunc_normal_(self.rel_pos_h, std=0.02)
nn.init.trunc_normal_(self.rel_pos_w, std=0.02)
def forward(self, x):
B, H, W, _ = x.shape
# qkv with shape (3, B, nHead, H * W, C)
qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
# q, k, v with shape (B * nHead, H * W, C)
q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
attn = (q * self.scale) @ k.transpose(-2, -1)
if self.use_rel_pos:
attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W))
attn = attn.softmax(dim=-1)
x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)
x = self.proj(x)
return x
class ResBottleneckBlock(CNNBlockBase):
"""
The standard bottleneck residual block without the last activation layer.
It contains 3 conv layers with kernels 1x1, 3x3, 1x1.
"""
def __init__(
self,
in_channels,
out_channels,
bottleneck_channels,
norm="LN",
act_layer=nn.GELU,
):
"""
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
bottleneck_channels (int): number of output channels for the 3x3
"bottleneck" conv layers.
norm (str or callable): normalization for all conv layers.
See :func:`layers.get_norm` for supported format.
act_layer (callable): activation for all conv layers.
"""
super().__init__(in_channels, out_channels, 1)
self.conv1 = Conv2d(in_channels, bottleneck_channels, 1, bias=False)
self.norm1 = get_norm(norm, bottleneck_channels)
self.act1 = act_layer()
self.conv2 = Conv2d(
bottleneck_channels,
bottleneck_channels,
3,
padding=1,
bias=False,
)
self.norm2 = get_norm(norm, bottleneck_channels)
self.act2 = act_layer()
self.conv3 = Conv2d(bottleneck_channels, out_channels, 1, bias=False)
self.norm3 = get_norm(norm, out_channels)
for layer in [self.conv1, self.conv2, self.conv3]:
weight_init.c2_msra_fill(layer)
for layer in [self.norm1, self.norm2]:
layer.weight.data.fill_(1.0)
layer.bias.data.zero_()
# zero init last norm layer.
self.norm3.weight.data.zero_()
self.norm3.bias.data.zero_()
def forward(self, x):
out = x
for layer in self.children():
out = layer(out)
out = x + out
return out
class Block(nn.Module):
"""Transformer blocks with support of window attention and residual propagation blocks"""
def __init__(
self,
dim,
num_heads,
mlp_ratio=4.0,
qkv_bias=True,
drop_path=0.0,
norm_layer=nn.LayerNorm,
act_layer=nn.GELU,
use_rel_pos=False,
rel_pos_zero_init=True,
window_size=0,
use_residual_block=False,
input_size=None,
down_size=64,
adapt_scalar="frozen",
init_value="0.0",
layernorm_option="in",
patch_wise_scalar=False,
fusion_method='concat',
):
"""
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads in each ViT block.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool): If True, add a learnable bias to query, key, value.
drop_path (float): Stochastic depth rate.
norm_layer (nn.Module): Normalization layer.
act_layer (nn.Module): Activation layer.
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
window_size (int): Window size for window attention blocks. If it equals 0, then not
use window attention.
use_residual_block (bool): If True, use a residual block after the MLP block.
input_size (int or None): Input resolution for calculating the relative positional
parameter size.
"""
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(
dim,
num_heads=num_heads,
qkv_bias=qkv_bias,
use_rel_pos=use_rel_pos,
rel_pos_zero_init=rel_pos_zero_init,
input_size=input_size if window_size == 0 else (window_size, window_size),
)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
self.mlp = Mlp(in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer)
self.patch_wise_scalar = patch_wise_scalar
self.fusion_method = fusion_method
self.window_size = window_size
self.adapt_scalar = adapt_scalar
self.adaptmlp = Adapter(dim, down_size=down_size, dropout=0.1,
adapter_scalar=adapt_scalar, init_value=init_value, adapter_layernorm_option=layernorm_option,
patch_wise_scalar=patch_wise_scalar)
if self.patch_wise_scalar:
if self.fusion_method == 'concat':
self.scalar_pred = nn.Linear(dim * 2, 1, bias=False)
elif self.fusion_method == 'sum' or self.fusion_method == 'side' or self.fusion_method == 'gside':
self.scalar_pred = nn.Linear(dim, 1, bias=False)
else:
raise ValueError("Only support fusion methods of concat and sum!")
self.scalar_act_layer = nn.Sigmoid()
self.use_residual_block = use_residual_block
if use_residual_block:
# Use a residual block with bottleneck channel as dim // 2
self.residual = ResBottleneckBlock(
in_channels=dim,
out_channels=dim,
bottleneck_channels=dim // 2,
norm="LN",
act_layer=act_layer,
)
def forward(self, x):
shortcut = x
x = self.norm1(x)
# Window partition
if self.window_size > 0:
H, W = x.shape[1], x.shape[2]
x, pad_hw = window_partition(x, self.window_size)
x = self.attn(x)
# Reverse window partition
if self.window_size > 0:
x = window_unpartition(x, self.window_size, pad_hw, (H, W))
x = shortcut + self.drop_path(x)
adapt_x, scale = self.adaptmlp(x, add_residual=False)
origin_mlp_x = self.mlp(self.norm2(x))
if self.patch_wise_scalar:
if self.fusion_method == 'concat':
scalar = self.scalar_pred(torch.concat([origin_mlp_x, adapt_x], axis=-1))
elif self.fusion_method == "sum":
scalar = self.scalar_pred(origin_mlp_x + adapt_x)
elif self.fusion_method == 'side':
scalar = self.scalar_pred(adapt_x)
elif self.fusion_method == 'gside':
scalar = self.scalar_pred(origin_mlp_x)
scalar = self.scalar_act_layer(scalar)
else:
scalar = scale
adapt_x = adapt_x * scalar
x = x + adapt_x
x = x + self.drop_path(origin_mlp_x)
if self.use_residual_block:
x = self.residual(x.permute(0, 3, 1, 2)).permute(0, 2, 3, 1)
return x
class ViT_adapt(Backbone):
"""
This module implements Vision Transformer (ViT) backbone in :paper:`vitdet`.
"Exploring Plain Vision Transformer Backbones for Object Detection",
https://arxiv.org/abs/2203.16527
"""
def __init__(
self,
img_size=1024,
patch_size=16,
in_chans=3,
embed_dim=768,
depth=12,
num_heads=12,
mlp_ratio=4.0,
qkv_bias=True,
drop_path_rate=0.0,
norm_layer=nn.LayerNorm,
act_layer=nn.GELU,
use_abs_pos=True,
use_rel_pos=False,
rel_pos_zero_init=True,
window_size=0,
window_block_indexes=(),
residual_block_indexes=(),
use_act_checkpoint=False,
pretrain_img_size=224,
pretrain_use_cls_token=True,
out_feature="last_feat",
down_size=64,
adapt_scalar="frozen",
init_value="0.0",
layernorm_option="in",
patch_wise_scalar=False,
fusion_method="concat",
):
"""
Args:
img_size (int): Input image size.
patch_size (int): Patch size.
in_chans (int): Number of input image channels.
embed_dim (int): Patch embedding dimension.
depth (int): Depth of ViT.
num_heads (int): Number of attention heads in each ViT block.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool): If True, add a learnable bias to query, key, value.
drop_path_rate (float): Stochastic depth rate.
norm_layer (nn.Module): Normalization layer.
act_layer (nn.Module): Activation layer.
use_abs_pos (bool): If True, use absolute positional embeddings.
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
window_size (int): Window size for window attention blocks.
window_block_indexes (list): Indexes for blocks using window attention.
residual_block_indexes (list): Indexes for blocks using conv propagation.
use_act_checkpoint (bool): If True, use activation checkpointing.
pretrain_img_size (int): input image size for pretraining models.
pretrain_use_cls_token (bool): If True, pretrainig models use class token.
out_feature (str): name of the feature from the last block.
"""
super().__init__()
self.pretrain_use_cls_token = pretrain_use_cls_token
self.patch_embed = PatchEmbed(
kernel_size=(patch_size, patch_size),
stride=(patch_size, patch_size),
in_chans=in_chans,
embed_dim=embed_dim,
)
if use_abs_pos:
# Initialize absolute positional embedding with pretrain image size.
num_patches = (pretrain_img_size // patch_size) * (pretrain_img_size // patch_size)
num_positions = (num_patches + 1) if pretrain_use_cls_token else num_patches
self.pos_embed = nn.Parameter(torch.zeros(1, num_positions, embed_dim))
else:
self.pos_embed = None
# stochastic depth decay rule
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
self.blocks = nn.ModuleList()
for i in range(depth):
block = Block(
dim=embed_dim,
num_heads=num_heads,
mlp_ratio=mlp_ratio,
qkv_bias=qkv_bias,
drop_path=dpr[i],
norm_layer=norm_layer,
act_layer=act_layer,
use_rel_pos=use_rel_pos,
rel_pos_zero_init=rel_pos_zero_init,
window_size=window_size if i in window_block_indexes else 0,
use_residual_block=i in residual_block_indexes,
input_size=(img_size // patch_size, img_size // patch_size),
down_size=down_size,
adapt_scalar=adapt_scalar,
init_value=init_value,
layernorm_option=layernorm_option,
patch_wise_scalar=patch_wise_scalar,
fusion_method=fusion_method,
)
if use_act_checkpoint:
# TODO: use torch.utils.checkpoint
block = checkpoint_wrapper(block)
self.blocks.append(block)
self._out_feature_channels = {out_feature: embed_dim}
self._out_feature_strides = {out_feature: patch_size}
self._out_features = [out_feature]
if self.pos_embed is not None:
nn.init.trunc_normal_(self.pos_embed, std=0.02)
self.apply(self._init_weights)
# init adapter
for i, blk in enumerate(self.blocks):
nn.init.kaiming_uniform_(blk.adaptmlp.down_proj.weight, a=math.sqrt(5))
nn.init.zeros_(blk.adaptmlp.up_proj.weight)
nn.init.zeros_(blk.adaptmlp.down_proj.bias)
nn.init.zeros_(blk.adaptmlp.up_proj.bias)
if patch_wise_scalar:
nn.init.zeros_(blk.scalar_pred.weight)
if blk.scalar_pred.bias is not None:
nn.init.zeros_(blk.scalar_pred.bias)
def _init_weights(self, m):
if isinstance(m, nn.Linear):
nn.init.trunc_normal_(m.weight, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
def forward(self, x):
x = self.patch_embed(x)
if self.pos_embed is not None: | x = x + get_abs_pos( | 3 | 2023-12-13 13:14:36+00:00 | 8k |
nickruggeri/hypergraph-message-passing | src/model/hypergraph_block_model.py | [
{
"identifier": "IncidenceHypergraph",
"path": "src/data/representation/incidence_hypergraph.py",
"snippet": "class IncidenceHypergraph(BinaryHypergraph):\n \"\"\"Representation of a binary hypergraph via its incidence matrix.\n The incidence matrix B is of size N x E, with N number of nodes in th... | import logging
import numpy as np
from collections import Counter
from typing import Iterable
from scipy import sparse, special
from src.data.representation.incidence_hypergraph import IncidenceHypergraph
from src.model.kappa import compute_C_prime, compute_C_third
from src.model.numerical import hyperedge_pi, sparse_reduce_lse
from .dynamic_updates import (
compute_psi_dynamic_programming,
compute_psi_tilde_dynamic_programming,
) | 5,872 | )
assert external_field.shape == (K,)
return C_prime / N * np.exp(external_field)
def single_hye_pi(self, assignments: Iterable[int]) -> float:
r"""Compute the hyperedge unnormalized probability.
For a hyperedge e and community assignments t, the unnormalized probability is
given by
.. math::
\pi_e := \sum_{i < j \in e} p_{t_i t_j}
Parameters
----------
assignments: community assignments.
This array contains the community assignments :math::`t_i` (with values
between 0 and K-1, where K is the number of communities) for all nodes i in
the hyperedge.
Returns
-------
The value of :math::`\pi_e`.
"""
K = self.K
hye_comm_counts = [0] * K
counts = Counter(assignments)
for comm, count in counts.items():
hye_comm_counts[comm] = count
return hyperedge_pi(hye_comm_counts, self.p)
def hye_pi(
self, hypergraph: IncidenceHypergraph, return_interactions: bool = False
) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
r"""Compute the hyperedge unnormalized probabilities for all the hyperedges in
the hypergraph. For a hyperedge e, the unnormalized probability has form
.. math::
\pi_e := \sum_{i <j \in e} p_{t_i t_j}
with p affinity matrix and :math::`t_i` community assignment of node i.
Parameters
----------
hypergraph: the input hypergraph.
return_interactions: whether to optionally return the tensor of community
interactions within hyperedges, defined as, for any hyperedge e and
communities a, b:
.. math::
\#_{ab}^{(e)} := \sum_{i <j \in e} \delta_{t_i a} \delta_{t_j b}
where :math::`\delta_{xy}` is the Dirac delta, equal to 1 if :math::`x=y`,
else 0.
The tensor :math::`\#` has shape (E, K, K), with E number of hyperedges and
K number of communities.
Returns
-------
The array of :math::`\pi_e` values. Optionally, the tensor of :math::`\#`
values.
"""
E = hypergraph.E
K = self.K
p = self.p
incidence = hypergraph.get_binary_incidence_matrix()
onehot_assignments = np.zeros((self.N, K))
onehot_assignments[np.arange(self.N), self.community_assignments()] = 1
counts = incidence.transpose() @ onehot_assignments
assert counts.shape == (E, K)
del onehot_assignments
interactions = counts.reshape(E, 1, K) * counts.reshape(E, K, 1)
interactions[:, np.arange(K), np.arange(K)] = counts * (counts - 1) / 2
assert interactions.shape == (E, K, K)
del counts
pi = 0.5 * (
np.sum(interactions * p.reshape(1, K, K), axis=(1, 2))
+ np.inner(interactions[:, np.arange(K), np.arange(K)], np.diagonal(p))
)
if return_interactions:
return pi, interactions
return pi
def free_energy(self, hypergraph: IncidenceHypergraph) -> float:
"""Compute the free energy of a hypergraph utilizing the message passing
cavity approximations. The free energy, often denoted as :math::`F = -log Z`,
corresponds to the negative log-normalizing constant of the Boltzmann
distribution. Z is also called the evidence of the probabilistic model.
Parameters
----------
hypergraph: hypergraph.
Returns
-------
The log-likelihood value.
"""
self._check_hypergraph_vs_model_params(hypergraph)
K = self.K
N = self.N
external_field = self.compute_external_field()
ones = np.ones(hypergraph.E)
log_marginals = self.log_marginals
hye_dims = hypergraph.get_binary_incidence_matrix().sum(axis=0)
# Node-related addends.
f_i = [
x.tocsc().dot(ones) - external_field[k]
for k, x in enumerate(
compute_psi_dynamic_programming(hypergraph=hypergraph, model=self)
)
]
assert len(f_i) == K
assert all(x.shape == (N,) for x in f_i)
f_i = np.vstack(f_i).T
assert f_i.shape == (N, K)
f_i = special.logsumexp(a=f_i, b=self.n.reshape(1, -1), axis=1)
f_i_sum = f_i.sum()
# Edge-related addends.
# First addend.
| from __future__ import annotations
# Define the type of sparse matrix that is utilized to store the messages during message
# passing. These can be different for messages from hyperedges to nodes and from nodes
# to hyperedges.
TYPE_HYE_TO_NODE: sparse.spmatrix = sparse.csc_array
TYPE_NODE_TO_HYE: sparse.spmatrix = sparse.csc_array
CLIP_MIN: float = -30
CLIP_MAX: float = -1e-15
class HypergraphBlockModel:
"""Hypergraph version of the Stochastic Block Model, introduced in
"Message Passing on Hypergraphs: Detectability, Phase Transitions, and Higher-Order
Information", Ruggeri et al.
This probabilistic model for hypergraphs partitions the nodes into K hard
communities, specified by an array of assignments t. The communities interact
through a symmetric affinity matrix p, with shape (K, K). Together, the community
assignments t and the affinity matrix p define the Bernoulli probability of the
single hyperedges to be observed or not.
"""
def __init__(
self,
n: np.ndarray | None,
p: np.ndarray | None,
N: int,
K: int,
max_hye_size: int | None,
) -> None:
r"""Stochastic Block Model for Hypergraphs.
This version of SBM considers, for every node i, hard community assignments
:math::`t_i`, i.e. categorical assignments to one out of K communities.
Together with a (K, K) affinity matrix, these two parameters define the
likelihood for unweighted hypergraphs (i.e. hyperedges have weights in {0, 1}).
A prior :math::`n=(n_1, \ldots, n_K)` for the community assignments can also be
specified.
Parameters
----------
n: array of prior parameters for the communities.
If specified, this array is used as initialization for EM inference,
otherwise it is initialized at random.
The array has length K equal to the number of communities, and specifies the
categorical prior probabilities.
p: symmetric matrix of community interaction probabilities.
If specified, this matrix is used as initialization for EM inference,
otherwise it is initialized at random.
The matrix has shape (K, K), where K is the number of communities, and
contains the inter and intra-community interaction probabilities,
constrained to the [0, 1] interval.
N: number of nodes.
K: number of communities.
max_hye_size: maximum size of the hyperedges D.
Notice that this quantity is used to infer probabilistic quantities in the
model, but is not checked against input hypergraphs.
"""
# Model related attributes
self._check_params(n, p, K, N, max_hye_size)
self.n = n.copy() if n is not None else None
self.p = p.copy() if p is not None else None
self.N = N
self.K = K
self.max_hye_size: int = max_hye_size if max_hye_size is not None else N
# Quantities inferred after message passing.
# log of the messages from hyperedges to nodes. Stored as lists of sparse
# matrices. For every hyperedge e and node i, the matrix at position a in the
# list contains the messages from e to i, for community assignment a.
self.log_hye_to_node: list[TYPE_HYE_TO_NODE] | None = None
# log of the messages from nodes to hyperedges.
# They are encoded similarly to the messages above.
self.log_node_to_hye: list[TYPE_NODE_TO_HYE] | None = None
# Other quantities, log-marginals and external field
self.log_marginals: np.ndarray | None = None
self.external_field: np.ndarray | None = None
# Training diagnostics.
self.training_iter: int | None = None
self.n_diff: list[float] = []
self.c_diff: list[float] = []
self.log_marginal_diff: list[list[float]] = []
# Random number generator.
self.rng: np.random.Generator = np.random.default_rng()
@property
def c(self):
"""Return the rescaled affinity matrix c, defined as
.. math::
c = N p
where N is the number of nodes and p the affinity matrix.
"""
return self.p * self.N
def em_inference(
self,
hypergraph: IncidenceHypergraph,
em_iter: int = 20,
em_thresh: float = 1e-5,
mp_iter: int = 2000,
mp_thresh: float = 1e-5,
mp_patience: int = 50,
seed: int | None = None,
dirichlet_alpha: float | None = None,
dropout: float = 0.99,
) -> None:
"""Perform Expectation Maximization (EM) inference on a hypergraph.
The inference routine consist of alternating message passing, where the
community assignments :math::`t_i` are inferred, and updates to the global
parameters, i.e. the affinity matrix w and community priors n.
If the affinity w or priors n are provided at initialization of the model, these
are not inferred, but kept fixed.
Parameters
----------
hypergraph: hypergraph to perform inference on.
em_iter: maximum number of EM iterations.
One iteration consists of the message passing routine plus the global
parameter updates.
em_thresh: threshold for EM convergence.
The threshold is computed over the absolute difference of the community
priors and the affinity matrix between two consecutive EM iterations.
mp_iter: maximum number of message passing iterations.
mp_thresh: threshold for message passing convergence.
The threshold is computed over the absolute difference of the log-marginals
between two consecutive iterations.
mp_patience: number of steps below the mp_thresh.
After a number of consecutive iterations, specified by patience, with an
absolute change in log-marginals below the mp_thresh, the message passing
procedure is stopped.
seed: random seed.
dirichlet_alpha: parameter for the Dirichlet distribution.
Utilized for the initialization of the messages, which are drawn from a
uniform Dirichlet distribution with parameter alpha.
If None, alpha is chosen automatically.
dropout: dropout rate.
The dropout rate it the number of randomly discarded updates in the messages
and marginals. At every iteration of message passing, these discarded values
are kept at the previous iteration value.
"""
if seed is not None:
self.rng = np.random.default_rng(seed)
self._check_hypergraph_vs_model_params(hypergraph)
if self.n is None:
fixed_n = False
self._random_init_n()
logging.info(f"Initialized n prior:\n{self.n}")
else:
fixed_n = True
if self.p is None:
fixed_p = False
self._random_init_p()
logging.info(f"Initialized rescaled affinity c=N*p:\n{self.c}")
else:
fixed_p = True
for it in range(em_iter):
logging.info(f"EM iteration {it}")
# Local parameters: message passing.
self.parallel_message_passing(
hypergraph,
mp_iter=mp_iter,
mp_thresh=mp_thresh,
patience=mp_patience,
warm_start=True,
seed=None, # keep the current random number generator unaltered.
dirichlet_alpha=dirichlet_alpha,
dropout=dropout,
)
# Global parameters: EM updates.
if not fixed_n or not fixed_p:
logging.info("\tUpdates of priors n and affinity p...")
if not fixed_n:
old_n = self.n.copy()
self.n = self.updated_community_prior()
self.n_diff.append(np.abs(old_n - self.n).sum())
logging.info(
f"\tCommunity prior:\n{self.n}"
"\n\tDifference from previous iteration: "
f"{self.n_diff[-1]}"
)
if not fixed_p:
old_c = self.c.copy()
self.p = self.updated_affinity_matrix(hypergraph)
self.c_diff.append(np.abs(old_c - self.c).sum())
logging.info(
f"\tRescaled affinity matrix c=N*p:\n{self.c}"
"\n\tDifference from previous iteration:"
f"{self.c_diff[-1]}"
)
self.training_iter = it + 1
if not fixed_n or not fixed_p:
param_diff = 0.0
if not fixed_n:
param_diff += self.n_diff[-1]
if not fixed_p:
param_diff += self.c_diff[-1]
if param_diff <= em_thresh:
logging.info(
"Expectation-maximization threshold passed. "
"inference terminated."
)
break
def parallel_message_passing(
self,
hypergraph: IncidenceHypergraph,
mp_iter: int = 2000,
mp_thresh: float = 1.0e-5,
dirichlet_alpha: float | None = None,
dropout: float = 0.99,
patience: int = 50,
seed: int | None = None,
warm_start: bool = True,
) -> None:
"""Perform message passing inference of the node assignments.
Parameters
----------
hypergraph: a hypergraph.
mp_iter: maximum number of message passing iterations.
mp_thresh: threshold for message passing convergence.
The threshold is computed over the absolute difference of the log-marginals
between two consecutive iterations.
dirichlet_alpha: parameter for the Dirichlet distribution.
Utilized for the initialization of the messages, which are drawn from a
uniform Dirichlet distribution with parameter alpha.
If None, alpha is chosen automatically.
dropout: dropout rate.
The dropout rate it the number of randomly discarded updates in the messages
and marginals. At every iteration of message passing, these discarded values
are kept at the previous iteration value.
patience: number of steps below the mp_thresh.
After a number of consecutive iterations, specified by patience, with an
absolute change in log-marginals below the mp_thresh, the message passing
procedure is stopped.
seed: random seed.
warm_start: whether to re-initialize the messages and marginal beliefs.
"""
logging.info("\tMessage passing...")
if seed is not None:
self.rng = np.random.default_rng(seed)
self._check_hypergraph_vs_model_params(hypergraph)
all_messages_init = (
self.log_hye_to_node is not None
and self.log_node_to_hye is not None
and self.log_marginals is not None
and self.external_field is not None
)
if not warm_start or not all_messages_init:
alpha = 10.0 * self.K if dirichlet_alpha is None else dirichlet_alpha
self._init_message_passing(hypergraph, dirichlet_alpha=alpha)
logging.debug(
f"\t\tInitialized hye to node:\n{self.log_hye_to_node[0].data[:5]}"
)
logging.debug(
f"\t\tInitialized node to hye:\n{self.log_node_to_hye[0].data[:5]}"
)
logging.debug(f"\t\tInitialized marginals:\n{self.log_marginals[:5]}")
logging.debug(f"\t\tInitialized external field:\n{self.external_field}")
self.log_marginal_diff.append(list())
patience_count = 0
for i in range(mp_iter):
old_log_marginals = self.log_marginals.copy()
self._parallel_message_passing_step(hypergraph, dropout)
self.log_marginal_diff[-1].append(
np.abs(old_log_marginals - self.log_marginals).sum()
)
logging.info(
f"\t\tMP step {i} - difference in log-marginals from previous iter: "
f"{self.log_marginal_diff[-1][-1]}"
)
if self.log_marginal_diff[-1][-1] <= mp_thresh:
patience_count += 1
else:
patience_count = 0
if patience_count == patience:
logging.info(
"\tMessage passing threshold passed. Message passing terminated."
)
break
def _parallel_message_passing_step(
self,
hypergraph: IncidenceHypergraph,
dropout: float = 0.99,
) -> None:
"""Perform one step of message passing, updating the messages from nodes to
factors, the messages from factors to nodes, the marginal probabilities and
external field."""
inc = hypergraph.get_binary_incidence_matrix()
# Update node to hye.
new_node_to_hye = [None] * self.K
for assignment in range(self.K):
col_sum = self.log_hye_to_node[assignment].sum(axis=1)
assert col_sum.shape == (self.N,)
col_sum += np.log(self.n[assignment]) - self.external_field[assignment]
col_sum = col_sum.reshape((self.N, 1))
new_node_to_hye[assignment] = (
TYPE_HYE_TO_NODE(inc * col_sum) - self.log_hye_to_node[assignment]
)
norm = sparse_reduce_lse(*new_node_to_hye)
for assignment in range(self.K):
new_node_to_hye[assignment].data -= norm.data
new_node_to_hye[assignment].data = np.clip(
new_node_to_hye[assignment].data, a_min=CLIP_MIN, a_max=CLIP_MAX
)
# TODO dropout could be made more efficient here. Do it or not?
if dropout > 0:
non_dropout_mask = (
self.rng.random(len(self.log_node_to_hye[0].data)) >= dropout
)
for assignment in range(self.K):
self.log_node_to_hye[assignment].data[
non_dropout_mask
] = new_node_to_hye[assignment].data[non_dropout_mask]
else:
for assignment in range(self.K):
self.log_node_to_hye[assignment].data = new_node_to_hye[assignment].data
logging.debug(f"\t\tUpdated node to hye:\n{self.log_node_to_hye[0].data[:5]}")
# Update hye to node.
if dropout > 0:
non_dropout_mask = (
self.rng.random(len(self.log_hye_to_node[0].data)) >= dropout
)
else:
non_dropout_mask = None
new_hye_to_node = [
TYPE_HYE_TO_NODE(x)
for x in compute_psi_dynamic_programming(
hypergraph=hypergraph,
model=self,
mask=non_dropout_mask,
)
]
norm = sparse_reduce_lse(*new_hye_to_node)
for assignment in range(self.K):
new_hye_to_node[assignment].data -= norm.data
new_hye_to_node[assignment].data = np.clip(
new_hye_to_node[assignment].data, a_min=CLIP_MIN, a_max=CLIP_MAX
)
for assignment in range(self.K):
self.log_hye_to_node[assignment].data[non_dropout_mask] = new_hye_to_node[
assignment
].data
logging.debug(f"\t\tUpdated hye to node:\n{self.log_hye_to_node[0].data[:5]}")
# Update marginals.
new_marginals = []
for assignment in range(self.K):
col_sum = self.log_hye_to_node[assignment].sum(axis=1)
assert col_sum.shape == (self.N,)
col_sum += np.log(self.n[assignment]) - self.external_field[assignment]
new_marginals.append(col_sum)
new_marginals = np.stack(new_marginals, axis=1)
assert new_marginals.shape == (self.N, self.K)
new_marginals = new_marginals - special.logsumexp(
new_marginals, axis=1, keepdims=True
)
new_marginals = np.clip(new_marginals, a_min=CLIP_MIN, a_max=CLIP_MAX)
if dropout > 0:
non_dropout_mask = self.rng.random(self.N) >= dropout
self.log_marginals[non_dropout_mask] = new_marginals[non_dropout_mask]
else:
self.log_marginals = new_marginals
logging.debug(f"\t\tUpdated marginals:\n{self.log_marginals[:5]}")
# Update external field.
lse_term = special.logsumexp(
a=self.log_marginals.reshape((self.N, self.K, 1)),
b=self.c.reshape(1, self.K, self.K),
axis=(0, 1),
)
assert lse_term.shape == (self.K,)
C_prime = compute_C_prime(self.max_hye_size)
self.external_field = C_prime / self.N * np.exp(lse_term)
logging.debug(f"\t\tUpdated external field:\n{self.external_field}")
def updated_community_prior(self) -> np.ndarray:
"""Parameter updates for the community priors n during EM inference.
Returns
-------
The updated array of community priors.
"""
assignments = self.community_assignments()
comm, counts = np.unique(assignments, return_counts=True)
n = np.zeros(self.K)
n[comm] = counts / self.N
return np.clip(n, a_min=1.0e-20, a_max=1.0)
def updated_affinity_matrix(self, hypergraph: IncidenceHypergraph) -> np.ndarray:
"""Parameter updates for the affinity matrix p during EM inference.
Parameters
----------
hypergraph: a hypergraph.
Returns
-------
The updated affinity matrix.
"""
# Numerator.
pi, interactions = self.hye_pi(hypergraph, return_interactions=True)
numerator = np.tensordot(
interactions, 1 / np.clip(pi, a_min=1.0e-20, a_max=None), axes=(0, 0)
)
assert numerator.shape == (self.K, self.K)
# Denominator.
C_prime = compute_C_prime(self.max_hye_size)
denominator = (
self.N * C_prime * (self.N * np.outer(self.n, self.n) - np.diag(self.n))
)
p = self.p * 2 * numerator / denominator
return np.clip(p, a_min=1e-20, a_max=0.99)
def community_assignments(self):
marginals = self.log_marginals
return np.argmax(marginals, axis=1)
def compute_external_field(self) -> np.array:
r"""Compute the approximate external field, defined as
.. math::
h(t_i) :=
\frac{C'}{N}
\sum_{j \in V} \sum_{t_j} c_{t_i t_j} q_j(t_j)
where
.. math::
C' = \sum_{d=2}^D \binom{N-2}{d-2} \frac{1}{\kappa_d}
Returns
-------
The external field h.
"""
log_marginals = self.log_marginals
c = self.c
K = self.K
N = self.N
C_prime = compute_C_prime(self.max_hye_size)
external_field = special.logsumexp(
a=log_marginals.reshape(N, 1, K), b=c.reshape(1, K, K), axis=(0, 2)
)
assert external_field.shape == (K,)
return C_prime / N * np.exp(external_field)
def single_hye_pi(self, assignments: Iterable[int]) -> float:
r"""Compute the hyperedge unnormalized probability.
For a hyperedge e and community assignments t, the unnormalized probability is
given by
.. math::
\pi_e := \sum_{i < j \in e} p_{t_i t_j}
Parameters
----------
assignments: community assignments.
This array contains the community assignments :math::`t_i` (with values
between 0 and K-1, where K is the number of communities) for all nodes i in
the hyperedge.
Returns
-------
The value of :math::`\pi_e`.
"""
K = self.K
hye_comm_counts = [0] * K
counts = Counter(assignments)
for comm, count in counts.items():
hye_comm_counts[comm] = count
return hyperedge_pi(hye_comm_counts, self.p)
def hye_pi(
self, hypergraph: IncidenceHypergraph, return_interactions: bool = False
) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
r"""Compute the hyperedge unnormalized probabilities for all the hyperedges in
the hypergraph. For a hyperedge e, the unnormalized probability has form
.. math::
\pi_e := \sum_{i <j \in e} p_{t_i t_j}
with p affinity matrix and :math::`t_i` community assignment of node i.
Parameters
----------
hypergraph: the input hypergraph.
return_interactions: whether to optionally return the tensor of community
interactions within hyperedges, defined as, for any hyperedge e and
communities a, b:
.. math::
\#_{ab}^{(e)} := \sum_{i <j \in e} \delta_{t_i a} \delta_{t_j b}
where :math::`\delta_{xy}` is the Dirac delta, equal to 1 if :math::`x=y`,
else 0.
The tensor :math::`\#` has shape (E, K, K), with E number of hyperedges and
K number of communities.
Returns
-------
The array of :math::`\pi_e` values. Optionally, the tensor of :math::`\#`
values.
"""
E = hypergraph.E
K = self.K
p = self.p
incidence = hypergraph.get_binary_incidence_matrix()
onehot_assignments = np.zeros((self.N, K))
onehot_assignments[np.arange(self.N), self.community_assignments()] = 1
counts = incidence.transpose() @ onehot_assignments
assert counts.shape == (E, K)
del onehot_assignments
interactions = counts.reshape(E, 1, K) * counts.reshape(E, K, 1)
interactions[:, np.arange(K), np.arange(K)] = counts * (counts - 1) / 2
assert interactions.shape == (E, K, K)
del counts
pi = 0.5 * (
np.sum(interactions * p.reshape(1, K, K), axis=(1, 2))
+ np.inner(interactions[:, np.arange(K), np.arange(K)], np.diagonal(p))
)
if return_interactions:
return pi, interactions
return pi
def free_energy(self, hypergraph: IncidenceHypergraph) -> float:
"""Compute the free energy of a hypergraph utilizing the message passing
cavity approximations. The free energy, often denoted as :math::`F = -log Z`,
corresponds to the negative log-normalizing constant of the Boltzmann
distribution. Z is also called the evidence of the probabilistic model.
Parameters
----------
hypergraph: hypergraph.
Returns
-------
The log-likelihood value.
"""
self._check_hypergraph_vs_model_params(hypergraph)
K = self.K
N = self.N
external_field = self.compute_external_field()
ones = np.ones(hypergraph.E)
log_marginals = self.log_marginals
hye_dims = hypergraph.get_binary_incidence_matrix().sum(axis=0)
# Node-related addends.
f_i = [
x.tocsc().dot(ones) - external_field[k]
for k, x in enumerate(
compute_psi_dynamic_programming(hypergraph=hypergraph, model=self)
)
]
assert len(f_i) == K
assert all(x.shape == (N,) for x in f_i)
f_i = np.vstack(f_i).T
assert f_i.shape == (N, K)
f_i = special.logsumexp(a=f_i, b=self.n.reshape(1, -1), axis=1)
f_i_sum = f_i.sum()
# Edge-related addends.
# First addend. | first_addend = compute_psi_tilde_dynamic_programming( | 6 | 2023-12-06 22:01:38+00:00 | 8k |
sailfishos-chum/sailfishos-chum.github.io | chumweb/static_site_gen.py | [
{
"identifier": "CONFIG",
"path": "chumweb/config.py",
"snippet": "CONFIG = init_config()"
},
{
"identifier": "create_package_atom_feed",
"path": "chumweb/atom_feed.py",
"snippet": "def create_package_atom_feed(pkgs: List[Package], public_url: str, title: str) -> Document:\n \"\"\"\n ... | import dataclasses
import json
import os
import random
import importlib.resources as resources
import lunr
from dataclasses import dataclass
from urllib.parse import urljoin
from jinja2 import Environment, PackageLoader, Template, select_autoescape, pass_eval_context
from jinja2.nodes import EvalContext
from markupsafe import Markup
from os import makedirs, mkdir
from pathlib import Path
from shutil import rmtree
from typing import List, Dict, Tuple, Set
from . import CONFIG
from .atom_feed import create_package_atom_feed
from .package import Package, PackageApplicationCategory
from datetime import datetime
from .progress import begin_step, step_progress
from .repo_loader import RepoInfo
from math import log2 | 3,631 | """
This module generates the static website
"""
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
@dataclass
class PackageIndex:
id: str
display: str
page_title: str
file: str
pkgs: List[Package]
def as_dict(self):
# dataclasses.asdict() converts the pkgs to dicts as well, which is not what I want, hence the hand-typed version
return {
"id": self.id,
"display": self.display,
"page_title": self.page_title,
"file": self.file,
"pkgs": self.pkgs
}
@dataclass
class CategoryPage:
name: str
categories: Set[str]
def __hash__(self):
return self.name.__hash__()
@dataclass
class Feed:
title: str
path: str
pkgs: List[Package]
def __getattr__(self, item):
if item == "url":
return CONFIG.public_url + self.path
CATEGORY_PAGES = [
CategoryPage("Accessibility", {PackageApplicationCategory.accessibility}),
CategoryPage("Development", {PackageApplicationCategory.development}),
CategoryPage("Education", {PackageApplicationCategory.education}),
CategoryPage("Games", {PackageApplicationCategory.game}),
CategoryPage("Graphics", {PackageApplicationCategory.graphics}),
CategoryPage("Libraries", {PackageApplicationCategory.library}),
CategoryPage("Location and Navigation", {PackageApplicationCategory.maps}),
CategoryPage("Multimedia", {PackageApplicationCategory.audio, PackageApplicationCategory.video,
PackageApplicationCategory.audio_video}),
CategoryPage("Office", {PackageApplicationCategory.office}),
CategoryPage("Science", {PackageApplicationCategory.science}),
CategoryPage("Utilities", {PackageApplicationCategory.system, PackageApplicationCategory.utility}),
CategoryPage("Other", {PackageApplicationCategory.other}),
]
def gen_site(repo_info: RepoInfo, out_dir: Path):
"""
Generates the static website given a list of packages
:param repo_info: The repository info and packages to generate the website for
:param out_dir: The directory to output the generated website in
"""
| """
This module generates the static website
"""
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
@dataclass
class PackageIndex:
id: str
display: str
page_title: str
file: str
pkgs: List[Package]
def as_dict(self):
# dataclasses.asdict() converts the pkgs to dicts as well, which is not what I want, hence the hand-typed version
return {
"id": self.id,
"display": self.display,
"page_title": self.page_title,
"file": self.file,
"pkgs": self.pkgs
}
@dataclass
class CategoryPage:
name: str
categories: Set[str]
def __hash__(self):
return self.name.__hash__()
@dataclass
class Feed:
title: str
path: str
pkgs: List[Package]
def __getattr__(self, item):
if item == "url":
return CONFIG.public_url + self.path
CATEGORY_PAGES = [
CategoryPage("Accessibility", {PackageApplicationCategory.accessibility}),
CategoryPage("Development", {PackageApplicationCategory.development}),
CategoryPage("Education", {PackageApplicationCategory.education}),
CategoryPage("Games", {PackageApplicationCategory.game}),
CategoryPage("Graphics", {PackageApplicationCategory.graphics}),
CategoryPage("Libraries", {PackageApplicationCategory.library}),
CategoryPage("Location and Navigation", {PackageApplicationCategory.maps}),
CategoryPage("Multimedia", {PackageApplicationCategory.audio, PackageApplicationCategory.video,
PackageApplicationCategory.audio_video}),
CategoryPage("Office", {PackageApplicationCategory.office}),
CategoryPage("Science", {PackageApplicationCategory.science}),
CategoryPage("Utilities", {PackageApplicationCategory.system, PackageApplicationCategory.utility}),
CategoryPage("Other", {PackageApplicationCategory.other}),
]
def gen_site(repo_info: RepoInfo, out_dir: Path):
"""
Generates the static website given a list of packages
:param repo_info: The repository info and packages to generate the website for
:param out_dir: The directory to output the generated website in
""" | sitegen_step = begin_step("Generating site") | 4 | 2023-12-14 19:25:31+00:00 | 8k |
oVo-HxBots/URLUploadBot | Uploader/callbacks.py | [
{
"identifier": "progress_for_pyrogram",
"path": "Uploader/functions/display_progress.py",
"snippet": "async def progress_for_pyrogram(\n current,\n total,\n ud_type,\n message,\n start\n):\n now = time.time()\n diff = now - start\n if round(diff % 10.00) == 0 or current == total... | import os
import logging
from Uploader.functions.display_progress import progress_for_pyrogram, humanbytes
from Uploader.config import Config
from sample_config import Config
from Uploader.dl_button import ddl_call_back
from Uploader.button import youtube_dl_call_back
from Uploader.script import Translation
from pyrogram import Client, types
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton | 5,889 | # MIT License
# Copyright (c) 2022 Hash Minner
# 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
if bool(os.environ.get("WEBHOOK")):
else:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
@Client.on_callback_query()
async def button(bot, update):
if update.data == "home":
await update.message.edit(
text=Translation.START_TEXT.format(update.from_user.mention),
reply_markup=Translation.START_BUTTONS,
# disable_web_page_preview=True
)
elif update.data == "help":
await update.message.edit(
text=Translation.HELP_TEXT,
reply_markup=Translation.HELP_BUTTONS,
# disable_web_page_preview=True
)
elif update.data == "about":
await update.message.edit(
text=Translation.ABOUT_TEXT,
reply_markup=Translation.ABOUT_BUTTONS,
# disable_web_page_preview=True
)
elif "close" in update.data:
await update.message.delete(True)
elif "|" in update.data:
await youtube_dl_call_back(bot, update)
elif "=" in update.data:
| # MIT License
# Copyright (c) 2022 Hash Minner
# 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
if bool(os.environ.get("WEBHOOK")):
else:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
@Client.on_callback_query()
async def button(bot, update):
if update.data == "home":
await update.message.edit(
text=Translation.START_TEXT.format(update.from_user.mention),
reply_markup=Translation.START_BUTTONS,
# disable_web_page_preview=True
)
elif update.data == "help":
await update.message.edit(
text=Translation.HELP_TEXT,
reply_markup=Translation.HELP_BUTTONS,
# disable_web_page_preview=True
)
elif update.data == "about":
await update.message.edit(
text=Translation.ABOUT_TEXT,
reply_markup=Translation.ABOUT_BUTTONS,
# disable_web_page_preview=True
)
elif "close" in update.data:
await update.message.delete(True)
elif "|" in update.data:
await youtube_dl_call_back(bot, update)
elif "=" in update.data: | await ddl_call_back(bot, update) | 2 | 2023-12-09 03:24:55+00:00 | 8k |
Jiawei-Yao0812/PixelFormer_DGR | pixelformer/networks/PixelFormer.py | [
{
"identifier": "SwinTransformer",
"path": "pixelformer/networks/swin_transformer.py",
"snippet": "class SwinTransformer(nn.Module):\n \"\"\" Swin Transformer backbone.\n A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -\n https://arxiv.o... | import torch
import torch.nn as nn
import torch.nn.functional as F
from .swin_transformer import SwinTransformer
from .PQI import PSP
from .SAM import SAM | 3,848 |
########################################################################################################################
class BCP(nn.Module):
""" Multilayer perceptron."""
def __init__(self, max_depth, min_depth, in_features=512, hidden_features=512*4, out_features=256, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
self.min_depth = min_depth
self.max_depth = max_depth
def forward(self, x):
x = torch.mean(x.flatten(start_dim=2), dim = 2)
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
bins = torch.softmax(x, dim=1)
bins = bins / bins.sum(dim=1, keepdim=True)
bin_widths = (self.max_depth - self.min_depth) * bins
bin_widths = nn.functional.pad(bin_widths, (1, 0), mode='constant', value=self.min_depth)
bin_edges = torch.cumsum(bin_widths, dim=1)
centers = 0.5 * (bin_edges[:, :-1] + bin_edges[:, 1:])
n, dout = centers.size()
centers = centers.contiguous().view(n, dout, 1, 1)
return centers
class PixelFormer(nn.Module):
def __init__(self, version=None, inv_depth=False, pretrained=None,
frozen_stages=-1, min_depth=0.1, max_depth=100.0, **kwargs):
super().__init__()
self.inv_depth = inv_depth
self.with_auxiliary_head = False
self.with_neck = False
norm_cfg = dict(type='BN', requires_grad=True)
# norm_cfg = dict(type='GN', requires_grad=True, num_groups=8)
window_size = int(version[-2:])
if version[:-2] == 'base':
embed_dim = 128
depths = [2, 2, 18, 2]
num_heads = [4, 8, 16, 32]
in_channels = [128, 256, 512, 1024]
elif version[:-2] == 'large':
embed_dim = 192
depths = [2, 2, 18, 2]
num_heads = [6, 12, 24, 48]
in_channels = [192, 384, 768, 1536]
elif version[:-2] == 'tiny':
embed_dim = 96
depths = [2, 2, 6, 2]
num_heads = [3, 6, 12, 24]
in_channels = [96, 192, 384, 768]
backbone_cfg = dict(
embed_dim=embed_dim,
depths=depths,
num_heads=num_heads,
window_size=window_size,
ape=False,
drop_path_rate=0.3,
patch_norm=True,
use_checkpoint=False,
frozen_stages=frozen_stages
)
embed_dim = 512
decoder_cfg = dict(
in_channels=in_channels,
in_index=[0, 1, 2, 3],
pool_scales=(1, 2, 3, 6),
channels=embed_dim,
dropout_ratio=0.0,
num_classes=32,
norm_cfg=norm_cfg,
align_corners=False
)
self.backbone = SwinTransformer(**backbone_cfg)
v_dim = decoder_cfg['num_classes']*4
win = 7
sam_dims = [128, 256, 512, 1024]
v_dims = [64, 128, 256, embed_dim]
|
########################################################################################################################
class BCP(nn.Module):
""" Multilayer perceptron."""
def __init__(self, max_depth, min_depth, in_features=512, hidden_features=512*4, out_features=256, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
self.min_depth = min_depth
self.max_depth = max_depth
def forward(self, x):
x = torch.mean(x.flatten(start_dim=2), dim = 2)
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
bins = torch.softmax(x, dim=1)
bins = bins / bins.sum(dim=1, keepdim=True)
bin_widths = (self.max_depth - self.min_depth) * bins
bin_widths = nn.functional.pad(bin_widths, (1, 0), mode='constant', value=self.min_depth)
bin_edges = torch.cumsum(bin_widths, dim=1)
centers = 0.5 * (bin_edges[:, :-1] + bin_edges[:, 1:])
n, dout = centers.size()
centers = centers.contiguous().view(n, dout, 1, 1)
return centers
class PixelFormer(nn.Module):
def __init__(self, version=None, inv_depth=False, pretrained=None,
frozen_stages=-1, min_depth=0.1, max_depth=100.0, **kwargs):
super().__init__()
self.inv_depth = inv_depth
self.with_auxiliary_head = False
self.with_neck = False
norm_cfg = dict(type='BN', requires_grad=True)
# norm_cfg = dict(type='GN', requires_grad=True, num_groups=8)
window_size = int(version[-2:])
if version[:-2] == 'base':
embed_dim = 128
depths = [2, 2, 18, 2]
num_heads = [4, 8, 16, 32]
in_channels = [128, 256, 512, 1024]
elif version[:-2] == 'large':
embed_dim = 192
depths = [2, 2, 18, 2]
num_heads = [6, 12, 24, 48]
in_channels = [192, 384, 768, 1536]
elif version[:-2] == 'tiny':
embed_dim = 96
depths = [2, 2, 6, 2]
num_heads = [3, 6, 12, 24]
in_channels = [96, 192, 384, 768]
backbone_cfg = dict(
embed_dim=embed_dim,
depths=depths,
num_heads=num_heads,
window_size=window_size,
ape=False,
drop_path_rate=0.3,
patch_norm=True,
use_checkpoint=False,
frozen_stages=frozen_stages
)
embed_dim = 512
decoder_cfg = dict(
in_channels=in_channels,
in_index=[0, 1, 2, 3],
pool_scales=(1, 2, 3, 6),
channels=embed_dim,
dropout_ratio=0.0,
num_classes=32,
norm_cfg=norm_cfg,
align_corners=False
)
self.backbone = SwinTransformer(**backbone_cfg)
v_dim = decoder_cfg['num_classes']*4
win = 7
sam_dims = [128, 256, 512, 1024]
v_dims = [64, 128, 256, embed_dim] | self.sam4 = SAM(input_dim=in_channels[3], embed_dim=sam_dims[3], window_size=win, v_dim=v_dims[3], num_heads=32) | 2 | 2023-12-13 20:50:32+00:00 | 8k |
kramerlab/PeerLearning | run_peer.py | [
{
"identifier": "DQNPeer",
"path": "dqn_peer.py",
"snippet": "class DQNPeer(make_peer_class(DQN)):\n \"\"\"\n A DQN version to be used with peer learning. Therefore, it features\n a critic function\n \"\"\"\n def critic(self, observations, actions):\n q_values = self.q_net(observat... | import argparse
import datetime
import gym
import wandb
import predefined_agents # noqa: F401
import env as local_envs # noqa: F401
from pathlib import Path
from stable_baselines3 import SAC, TD3
from stable_baselines3.common.utils import set_random_seed, \
update_learning_rate
from wandb.integration.sb3 import WandbCallback
from dqn_peer import DQNPeer
from peer import PeerGroup, make_peer_class
from callbacks import PeerEvalCallback
from utils import str2bool, add_default_values_to_parser, \
log_reward_avg_in_wandb, add_default_values_to_train_parser, \
new_random_seed, make_env, ControllerArguments | 6,437 |
def add_args():
# create arg parser
parser = argparse.ArgumentParser(description="Peer learning.")
# General
parser.add_argument("--save-name", type=str, default="delete_me")
parser = add_default_values_to_parser(parser)
# Training
training = parser.add_argument_group("Training")
|
def add_args():
# create arg parser
parser = argparse.ArgumentParser(description="Peer learning.")
# General
parser.add_argument("--save-name", type=str, default="delete_me")
parser = add_default_values_to_parser(parser)
# Training
training = parser.add_argument_group("Training") | add_default_values_to_train_parser(training) | 7 | 2023-12-13 10:40:55+00:00 | 8k |
ZS-YANG/FemtoDet-v3 | demo/large_image_demo.py | [
{
"identifier": "inference_detector",
"path": "mmdet/apis/inference.py",
"snippet": "def inference_detector(\n model: nn.Module,\n imgs: ImagesType,\n test_pipeline: Optional[Compose] = None,\n text_prompt: Optional[str] = None,\n custom_entities: bool = False,\n) -> Union[DetDataSample, ... | import os
import random
import mmcv
import numpy as np
from argparse import ArgumentParser
from pathlib import Path
from mmengine.config import Config, ConfigDict
from mmengine.logging import print_log
from mmengine.utils import ProgressBar
from mmdet.apis import inference_detector, init_detector
from sahi.slicing import slice_image
from mmdet.registry import VISUALIZERS
from mmdet.utils.large_image import merge_results_by_nms, shift_predictions
from mmdet.utils.misc import get_file_list | 4,768 | 'This may take a while.')
progress_bar = ProgressBar(len(files))
for file in files:
# read image
img = mmcv.imread(file)
# arrange slices
height, width = img.shape[:2]
sliced_image_object = slice_image(
img,
slice_height=args.patch_size,
slice_width=args.patch_size,
auto_slice_resolution=False,
overlap_height_ratio=args.patch_overlap_ratio,
overlap_width_ratio=args.patch_overlap_ratio,
)
# perform sliced inference
slice_results = []
start = 0
while True:
# prepare batch slices
end = min(start + args.batch_size, len(sliced_image_object))
images = []
for sliced_image in sliced_image_object.images[start:end]:
images.append(sliced_image)
# forward the model
slice_results.extend(inference_detector(model, images))
if end >= len(sliced_image_object):
break
start += args.batch_size
if source_type['is_dir']:
filename = os.path.relpath(file, args.img).replace('/', '_')
else:
filename = os.path.basename(file)
img = mmcv.imconvert(img, 'bgr', 'rgb')
out_file = None if args.show else os.path.join(args.out_dir, filename)
# export debug images
if args.debug:
# export sliced image results
name, suffix = os.path.splitext(filename)
shifted_instances = shift_predictions(
slice_results,
sliced_image_object.starting_pixels,
src_image_shape=(height, width))
merged_result = slice_results[0].clone()
merged_result.pred_instances = shifted_instances
debug_file_name = name + '_debug' + suffix
debug_out_file = None if args.show else os.path.join(
args.out_dir, debug_file_name)
visualizer.set_image(img.copy())
debug_grids = []
for starting_point in sliced_image_object.starting_pixels:
start_point_x = starting_point[0]
start_point_y = starting_point[1]
end_point_x = start_point_x + args.patch_size
end_point_y = start_point_y + args.patch_size
debug_grids.append(
[start_point_x, start_point_y, end_point_x, end_point_y])
debug_grids = np.array(debug_grids)
debug_grids[:, 0::2] = np.clip(debug_grids[:, 0::2], 1,
img.shape[1] - 1)
debug_grids[:, 1::2] = np.clip(debug_grids[:, 1::2], 1,
img.shape[0] - 1)
palette = np.random.randint(0, 256, size=(len(debug_grids), 3))
palette = [tuple(c) for c in palette]
line_styles = random.choices(['-', '-.', ':'], k=len(debug_grids))
visualizer.draw_bboxes(
debug_grids,
edge_colors=palette,
alpha=1,
line_styles=line_styles)
visualizer.draw_bboxes(
debug_grids, face_colors=palette, alpha=0.15)
visualizer.draw_texts(
list(range(len(debug_grids))),
debug_grids[:, :2] + 5,
colors='w')
visualizer.add_datasample(
debug_file_name,
visualizer.get_image(),
data_sample=merged_result,
draw_gt=False,
show=args.show,
wait_time=0,
out_file=debug_out_file,
pred_score_thr=args.score_thr,
)
if args.save_patch:
debug_patch_out_dir = os.path.join(args.out_dir,
f'{name}_patch')
for i, slice_result in enumerate(slice_results):
patch_out_file = os.path.join(
debug_patch_out_dir,
f'{filename}_slice_{i}_result.jpg')
image = mmcv.imconvert(sliced_image_object.images[i],
'bgr', 'rgb')
visualizer.add_datasample(
'patch_result',
image,
data_sample=slice_result,
draw_gt=False,
show=False,
wait_time=0,
out_file=patch_out_file,
pred_score_thr=args.score_thr,
)
| # Copyright (c) OpenMMLab. All rights reserved.
"""Perform MMDET inference on large images (as satellite imagery) as:
```shell
wget -P checkpoint https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r101_fpn_2x_coco/faster_rcnn_r101_fpn_2x_coco_bbox_mAP-0.398_20200504_210455-1d2dac9c.pth # noqa: E501, E261.
python demo/large_image_demo.py \
demo/large_image.jpg \
configs/faster_rcnn/faster-rcnn_r101_fpn_2x_coco.py \
checkpoint/faster_rcnn_r101_fpn_2x_coco_bbox_mAP-0.398_20200504_210455-1d2dac9c.pth
```
"""
try:
except ImportError:
raise ImportError('Please run "pip install -U sahi" '
'to install sahi first for large image inference.')
def parse_args():
parser = ArgumentParser(
description='Perform MMDET inference on large images.')
parser.add_argument(
'img', help='Image path, include image file, dir and URL.')
parser.add_argument('config', help='Config file')
parser.add_argument('checkpoint', help='Checkpoint file')
parser.add_argument(
'--out-dir', default='./output', help='Path to output file')
parser.add_argument(
'--device', default='cuda:0', help='Device used for inference')
parser.add_argument(
'--show', action='store_true', help='Show the detection results')
parser.add_argument(
'--tta',
action='store_true',
help='Whether to use test time augmentation')
parser.add_argument(
'--score-thr', type=float, default=0.3, help='Bbox score threshold')
parser.add_argument(
'--patch-size', type=int, default=640, help='The size of patches')
parser.add_argument(
'--patch-overlap-ratio',
type=float,
default=0.25,
help='Ratio of overlap between two patches')
parser.add_argument(
'--merge-iou-thr',
type=float,
default=0.25,
help='IoU threshould for merging results')
parser.add_argument(
'--merge-nms-type',
type=str,
default='nms',
help='NMS type for merging results')
parser.add_argument(
'--batch-size',
type=int,
default=1,
help='Batch size, must greater than or equal to 1')
parser.add_argument(
'--debug',
action='store_true',
help='Export debug results before merging')
parser.add_argument(
'--save-patch',
action='store_true',
help='Save the results of each patch. '
'The `--debug` must be enabled.')
args = parser.parse_args()
return args
def main():
args = parse_args()
config = args.config
if isinstance(config, (str, Path)):
config = Config.fromfile(config)
elif not isinstance(config, Config):
raise TypeError('config must be a filename or Config object, '
f'but got {type(config)}')
if 'init_cfg' in config.model.backbone:
config.model.backbone.init_cfg = None
if args.tta:
assert 'tta_model' in config, 'Cannot find ``tta_model`` in config.' \
" Can't use tta !"
assert 'tta_pipeline' in config, 'Cannot find ``tta_pipeline`` ' \
"in config. Can't use tta !"
config.model = ConfigDict(**config.tta_model, module=config.model)
test_data_cfg = config.test_dataloader.dataset
while 'dataset' in test_data_cfg:
test_data_cfg = test_data_cfg['dataset']
test_data_cfg.pipeline = config.tta_pipeline
# TODO: TTA mode will error if cfg_options is not set.
# This is an mmdet issue and needs to be fixed later.
# build the model from a config file and a checkpoint file
model = init_detector(
config, args.checkpoint, device=args.device, cfg_options={})
if not os.path.exists(args.out_dir) and not args.show:
os.mkdir(args.out_dir)
# init visualizer
visualizer = VISUALIZERS.build(model.cfg.visualizer)
visualizer.dataset_meta = model.dataset_meta
# get file list
files, source_type = get_file_list(args.img)
# start detector inference
print(f'Performing inference on {len(files)} images.... '
'This may take a while.')
progress_bar = ProgressBar(len(files))
for file in files:
# read image
img = mmcv.imread(file)
# arrange slices
height, width = img.shape[:2]
sliced_image_object = slice_image(
img,
slice_height=args.patch_size,
slice_width=args.patch_size,
auto_slice_resolution=False,
overlap_height_ratio=args.patch_overlap_ratio,
overlap_width_ratio=args.patch_overlap_ratio,
)
# perform sliced inference
slice_results = []
start = 0
while True:
# prepare batch slices
end = min(start + args.batch_size, len(sliced_image_object))
images = []
for sliced_image in sliced_image_object.images[start:end]:
images.append(sliced_image)
# forward the model
slice_results.extend(inference_detector(model, images))
if end >= len(sliced_image_object):
break
start += args.batch_size
if source_type['is_dir']:
filename = os.path.relpath(file, args.img).replace('/', '_')
else:
filename = os.path.basename(file)
img = mmcv.imconvert(img, 'bgr', 'rgb')
out_file = None if args.show else os.path.join(args.out_dir, filename)
# export debug images
if args.debug:
# export sliced image results
name, suffix = os.path.splitext(filename)
shifted_instances = shift_predictions(
slice_results,
sliced_image_object.starting_pixels,
src_image_shape=(height, width))
merged_result = slice_results[0].clone()
merged_result.pred_instances = shifted_instances
debug_file_name = name + '_debug' + suffix
debug_out_file = None if args.show else os.path.join(
args.out_dir, debug_file_name)
visualizer.set_image(img.copy())
debug_grids = []
for starting_point in sliced_image_object.starting_pixels:
start_point_x = starting_point[0]
start_point_y = starting_point[1]
end_point_x = start_point_x + args.patch_size
end_point_y = start_point_y + args.patch_size
debug_grids.append(
[start_point_x, start_point_y, end_point_x, end_point_y])
debug_grids = np.array(debug_grids)
debug_grids[:, 0::2] = np.clip(debug_grids[:, 0::2], 1,
img.shape[1] - 1)
debug_grids[:, 1::2] = np.clip(debug_grids[:, 1::2], 1,
img.shape[0] - 1)
palette = np.random.randint(0, 256, size=(len(debug_grids), 3))
palette = [tuple(c) for c in palette]
line_styles = random.choices(['-', '-.', ':'], k=len(debug_grids))
visualizer.draw_bboxes(
debug_grids,
edge_colors=palette,
alpha=1,
line_styles=line_styles)
visualizer.draw_bboxes(
debug_grids, face_colors=palette, alpha=0.15)
visualizer.draw_texts(
list(range(len(debug_grids))),
debug_grids[:, :2] + 5,
colors='w')
visualizer.add_datasample(
debug_file_name,
visualizer.get_image(),
data_sample=merged_result,
draw_gt=False,
show=args.show,
wait_time=0,
out_file=debug_out_file,
pred_score_thr=args.score_thr,
)
if args.save_patch:
debug_patch_out_dir = os.path.join(args.out_dir,
f'{name}_patch')
for i, slice_result in enumerate(slice_results):
patch_out_file = os.path.join(
debug_patch_out_dir,
f'{filename}_slice_{i}_result.jpg')
image = mmcv.imconvert(sliced_image_object.images[i],
'bgr', 'rgb')
visualizer.add_datasample(
'patch_result',
image,
data_sample=slice_result,
draw_gt=False,
show=False,
wait_time=0,
out_file=patch_out_file,
pred_score_thr=args.score_thr,
)
| image_result = merge_results_by_nms( | 3 | 2023-12-11 15:23:03+00:00 | 8k |
Tps-F/rvc-onnx-test | onnxlib/models_onnx.py | [
{
"identifier": "attentions",
"path": "onnxlib/attentions.py",
"snippet": "class Encoder(nn.Module):\nclass Decoder(nn.Module):\nclass MultiHeadAttention(nn.Module):\nclass FFN(nn.Module):\n def __init__(\n self,\n hidden_channels,\n filter_channels,\n n_heads,\n n_... | import logging
import math
import numpy as np
import torch
from torch import nn
from torch.nn import AvgPool1d, Conv1d, Conv2d, ConvTranspose1d
from torch.nn import functional as F
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from onnxlib import attentions, commons, modules
from onnxlib.commons import get_padding, init_weights | 3,606 | self.n_flows = n_flows
self.gin_channels = gin_channels
self.flows = nn.ModuleList()
for i in range(n_flows):
self.flows.append(
modules.ResidualCouplingLayer(
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=gin_channels,
mean_only=True,
)
)
self.flows.append(modules.Flip())
def forward(self, x, x_mask, g=None, reverse=False):
if not reverse:
for flow in self.flows:
x, _ = flow(x, x_mask, g=g, reverse=reverse)
else:
for flow in reversed(self.flows):
x, _ = flow(x, x_mask, g=g, reverse=reverse)
return x
def remove_weight_norm(self):
for i in range(self.n_flows):
self.flows[i * 2].remove_weight_norm()
class PosteriorEncoder(nn.Module):
def __init__(
self,
in_channels,
out_channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=0,
):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.gin_channels = gin_channels
self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
self.enc = modules.WN(
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=gin_channels,
)
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
def forward(self, x, x_lengths, g=None):
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
x.dtype
)
x = self.pre(x) * x_mask
x = self.enc(x, x_mask, g=g)
stats = self.proj(x) * x_mask
m, logs = torch.split(stats, self.out_channels, dim=1)
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
return z, m, logs, x_mask
def remove_weight_norm(self):
self.enc.remove_weight_norm()
class Generator(torch.nn.Module):
def __init__(
self,
initial_channel,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
gin_channels=0,
):
super(Generator, self).__init__()
self.num_kernels = len(resblock_kernel_sizes)
self.num_upsamples = len(upsample_rates)
self.conv_pre = Conv1d(
initial_channel, upsample_initial_channel, 7, 1, padding=3
)
resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
self.ups = nn.ModuleList()
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
self.ups.append(
weight_norm(
ConvTranspose1d(
upsample_initial_channel // (2**i),
upsample_initial_channel // (2 ** (i + 1)),
k,
u,
padding=(k - u) // 2,
)
)
)
self.resblocks = nn.ModuleList()
for i in range(len(self.ups)):
ch = upsample_initial_channel // (2 ** (i + 1))
for j, (k, d) in enumerate(
zip(resblock_kernel_sizes, resblock_dilation_sizes)
):
self.resblocks.append(resblock(ch, k, d))
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False)
|
logger = logging.getLogger(__name__)
class TextEncoder256(nn.Module):
def __init__(
self,
out_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
f0=True,
):
super().__init__()
self.out_channels = out_channels
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.emb_phone = nn.Linear(256, hidden_channels)
self.lrelu = nn.LeakyReLU(0.1, inplace=True)
if f0 == True:
self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
self.encoder = attentions.Encoder(
hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
)
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
def forward(self, phone, pitch, lengths):
if pitch == None:
x = self.emb_phone(phone)
else:
x = self.emb_phone(phone) + self.emb_pitch(pitch)
x = x * math.sqrt(self.hidden_channels) # [b, t, h]
x = self.lrelu(x)
x = torch.transpose(x, 1, -1) # [b, h, t]
x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
x.dtype
)
x = self.encoder(x * x_mask, x_mask)
stats = self.proj(x) * x_mask
m, logs = torch.split(stats, self.out_channels, dim=1)
return m, logs, x_mask
class TextEncoder768(nn.Module):
def __init__(
self,
out_channels,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size,
p_dropout,
f0=True,
):
super().__init__()
self.out_channels = out_channels
self.hidden_channels = hidden_channels
self.filter_channels = filter_channels
self.n_heads = n_heads
self.n_layers = n_layers
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.emb_phone = nn.Linear(768, hidden_channels)
self.lrelu = nn.LeakyReLU(0.1, inplace=True)
if f0 == True:
self.emb_pitch = nn.Embedding(256, hidden_channels) # pitch 256
self.encoder = attentions.Encoder(
hidden_channels, filter_channels, n_heads, n_layers, kernel_size, p_dropout
)
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
def forward(self, phone, pitch, lengths):
if pitch == None:
x = self.emb_phone(phone)
else:
x = self.emb_phone(phone) + self.emb_pitch(pitch)
x = x * math.sqrt(self.hidden_channels) # [b, t, h]
x = self.lrelu(x)
x = torch.transpose(x, 1, -1) # [b, h, t]
x_mask = torch.unsqueeze(commons.sequence_mask(lengths, x.size(2)), 1).to(
x.dtype
)
x = self.encoder(x * x_mask, x_mask)
stats = self.proj(x) * x_mask
m, logs = torch.split(stats, self.out_channels, dim=1)
return m, logs, x_mask
class ResidualCouplingBlock(nn.Module):
def __init__(
self,
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
n_flows=4,
gin_channels=0,
):
super().__init__()
self.channels = channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.n_flows = n_flows
self.gin_channels = gin_channels
self.flows = nn.ModuleList()
for i in range(n_flows):
self.flows.append(
modules.ResidualCouplingLayer(
channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=gin_channels,
mean_only=True,
)
)
self.flows.append(modules.Flip())
def forward(self, x, x_mask, g=None, reverse=False):
if not reverse:
for flow in self.flows:
x, _ = flow(x, x_mask, g=g, reverse=reverse)
else:
for flow in reversed(self.flows):
x, _ = flow(x, x_mask, g=g, reverse=reverse)
return x
def remove_weight_norm(self):
for i in range(self.n_flows):
self.flows[i * 2].remove_weight_norm()
class PosteriorEncoder(nn.Module):
def __init__(
self,
in_channels,
out_channels,
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=0,
):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.hidden_channels = hidden_channels
self.kernel_size = kernel_size
self.dilation_rate = dilation_rate
self.n_layers = n_layers
self.gin_channels = gin_channels
self.pre = nn.Conv1d(in_channels, hidden_channels, 1)
self.enc = modules.WN(
hidden_channels,
kernel_size,
dilation_rate,
n_layers,
gin_channels=gin_channels,
)
self.proj = nn.Conv1d(hidden_channels, out_channels * 2, 1)
def forward(self, x, x_lengths, g=None):
x_mask = torch.unsqueeze(commons.sequence_mask(x_lengths, x.size(2)), 1).to(
x.dtype
)
x = self.pre(x) * x_mask
x = self.enc(x, x_mask, g=g)
stats = self.proj(x) * x_mask
m, logs = torch.split(stats, self.out_channels, dim=1)
z = (m + torch.randn_like(m) * torch.exp(logs)) * x_mask
return z, m, logs, x_mask
def remove_weight_norm(self):
self.enc.remove_weight_norm()
class Generator(torch.nn.Module):
def __init__(
self,
initial_channel,
resblock,
resblock_kernel_sizes,
resblock_dilation_sizes,
upsample_rates,
upsample_initial_channel,
upsample_kernel_sizes,
gin_channels=0,
):
super(Generator, self).__init__()
self.num_kernels = len(resblock_kernel_sizes)
self.num_upsamples = len(upsample_rates)
self.conv_pre = Conv1d(
initial_channel, upsample_initial_channel, 7, 1, padding=3
)
resblock = modules.ResBlock1 if resblock == "1" else modules.ResBlock2
self.ups = nn.ModuleList()
for i, (u, k) in enumerate(zip(upsample_rates, upsample_kernel_sizes)):
self.ups.append(
weight_norm(
ConvTranspose1d(
upsample_initial_channel // (2**i),
upsample_initial_channel // (2 ** (i + 1)),
k,
u,
padding=(k - u) // 2,
)
)
)
self.resblocks = nn.ModuleList()
for i in range(len(self.ups)):
ch = upsample_initial_channel // (2 ** (i + 1))
for j, (k, d) in enumerate(
zip(resblock_kernel_sizes, resblock_dilation_sizes)
):
self.resblocks.append(resblock(ch, k, d))
self.conv_post = Conv1d(ch, 1, 7, 1, padding=3, bias=False) | self.ups.apply(init_weights) | 4 | 2023-12-09 04:08:04+00:00 | 8k |
zengydd/ProphDR | train.py | [
{
"identifier": "load_config",
"path": "utils/optimizer.py",
"snippet": "def load_config(path):\n with open(path, 'r') as f:\n return EasyDict(yaml.safe_load(f))"
},
{
"identifier": "get_optimizer",
"path": "utils/optimizer.py",
"snippet": "def get_optimizer(cfg, model):\n i... | import os, sys
import pandas as pd
import numpy as np
import random
import copy
import time
import datetime
import math
import pickle
import optuna
import yaml
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils import data
from torch.nn.parallel import DataParallel
from torch.autograd import Variable
from torch.optim.lr_scheduler import ReduceLROnPlateau, MultiStepLR
from sklearn.model_selection import train_test_split, KFold
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import SequentialSampler
from prettytable import PrettyTable
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error
from sklearn.metrics import roc_auc_score, average_precision_score, accuracy_score, roc_curve, f1_score, precision_recall_curve
from lifelines.utils import concordance_index
from scipy.stats import pearsonr,spearmanr
from utils.optimizer import load_config, get_optimizer, get_scheduler
from easydict import EasyDict
from collections import defaultdict
from utils.load import load_pickle, save_pickle, set_file
from utils.mydata import mydata, dataset_split, set_random_seed
from Models.Proph_DR import gbz_main_cross
from Models.cross_attention_dual import cross_EncoderBlock_G, cross_EncoderBlock_D | 5,049 | os.environ['NUMEXPR_MAX_THREADS'] = '32'
sys.path.append("..")
torch.set_default_dtype(torch.float32)
config = './utils/train_res.yml'
config = load_config(config)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
float2str = lambda x: '%0.4f' % x
root = os.getcwd()
# root ='/home/yundian/gbz/gbz/'
data_dir = os.path.join(root, 'data_collect/')
unify_dir = os.path.join(root, 'data_collect/unify/')
# drug data
drug_std_dir = os.path.join(unify_dir, 'drug_std/')
drug_smiles_file = os.path.join(data_dir, 'drug_smiles_atom_pad.csv')
drug_smiles_df = pd.read_csv(drug_smiles_file, index_col='drug_id')
atom_pad_dict = load_pickle(data_dir + 'unify/drug_std/atom_pad.pkl')
# omics data
omic_encode = os.path.join(unify_dir, 'omics_std/omics_stk_dict.pkl')
mut_encode = os.path.join(unify_dir, 'omics_std/mut_dict.pkl')
cnv_encode = os.path.join(unify_dir, 'omics_std/cnv_dict.pkl')
exp_encode = os.path.join(unify_dir, 'omics_std/exp_dict.pkl')
mut_cnv = os.path.join(unify_dir, 'omics_std/omics_stk_dict_mut_cnv.pkl')
mut_exp = os.path.join(unify_dir, 'omics_std/omics_stk_dict_mut_exp.pkl')
exp_cnv = os.path.join(unify_dir, 'omics_std/omics_stk_dict_exp_cnv.pkl')
if __name__ == '__main__':
# @@@@@@@@@@@@@@@@@@@
# task: IC50 or binary
# strat: TCGA_DESC, binary, None
# omic_f: omic_encode, omic_encode_origin, mut_encode, cnv_encode, exp_encode
# mut_cnv mut_exp exp_cnv
test_dict = {}
task = 'IC50'
method = 'only2'
torch.cuda.empty_cache()
test_result_list = []
for i in range(0, 10):
seed = i
set_random_seed(seed)
now = datetime.datetime.now()
timestamp = now.strftime('%Y%m%d_%H_%M%S')
model_dir = os.path.join(root, 'result/{}_{}'.format(task, timestamp))
if not os.path.exists(model_dir):
os.makedirs(model_dir)
exp_params = {
'task': task,
'method': method,
'down_sample': False,
'strat': None,
'omic_dim': 3,
'omic_f':omic_encode,
}
response = set_file(root_path =unify_dir ,task=exp_params['task'], method=exp_params['method'], down_sample=exp_params['down_sample'])
response = response.head(100)
| os.environ['NUMEXPR_MAX_THREADS'] = '32'
sys.path.append("..")
torch.set_default_dtype(torch.float32)
config = './utils/train_res.yml'
config = load_config(config)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
float2str = lambda x: '%0.4f' % x
root = os.getcwd()
# root ='/home/yundian/gbz/gbz/'
data_dir = os.path.join(root, 'data_collect/')
unify_dir = os.path.join(root, 'data_collect/unify/')
# drug data
drug_std_dir = os.path.join(unify_dir, 'drug_std/')
drug_smiles_file = os.path.join(data_dir, 'drug_smiles_atom_pad.csv')
drug_smiles_df = pd.read_csv(drug_smiles_file, index_col='drug_id')
atom_pad_dict = load_pickle(data_dir + 'unify/drug_std/atom_pad.pkl')
# omics data
omic_encode = os.path.join(unify_dir, 'omics_std/omics_stk_dict.pkl')
mut_encode = os.path.join(unify_dir, 'omics_std/mut_dict.pkl')
cnv_encode = os.path.join(unify_dir, 'omics_std/cnv_dict.pkl')
exp_encode = os.path.join(unify_dir, 'omics_std/exp_dict.pkl')
mut_cnv = os.path.join(unify_dir, 'omics_std/omics_stk_dict_mut_cnv.pkl')
mut_exp = os.path.join(unify_dir, 'omics_std/omics_stk_dict_mut_exp.pkl')
exp_cnv = os.path.join(unify_dir, 'omics_std/omics_stk_dict_exp_cnv.pkl')
if __name__ == '__main__':
# @@@@@@@@@@@@@@@@@@@
# task: IC50 or binary
# strat: TCGA_DESC, binary, None
# omic_f: omic_encode, omic_encode_origin, mut_encode, cnv_encode, exp_encode
# mut_cnv mut_exp exp_cnv
test_dict = {}
task = 'IC50'
method = 'only2'
torch.cuda.empty_cache()
test_result_list = []
for i in range(0, 10):
seed = i
set_random_seed(seed)
now = datetime.datetime.now()
timestamp = now.strftime('%Y%m%d_%H_%M%S')
model_dir = os.path.join(root, 'result/{}_{}'.format(task, timestamp))
if not os.path.exists(model_dir):
os.makedirs(model_dir)
exp_params = {
'task': task,
'method': method,
'down_sample': False,
'strat': None,
'omic_dim': 3,
'omic_f':omic_encode,
}
response = set_file(root_path =unify_dir ,task=exp_params['task'], method=exp_params['method'], down_sample=exp_params['down_sample'])
response = response.head(100)
| train_set, val_set, test_set = dataset_split(response, random=seed, stratify=exp_params['strat']) | 7 | 2023-12-13 11:56:08+00:00 | 8k |
zhenqincn/FedKSeed | main.py | [
{
"identifier": "Server",
"path": "server.py",
"snippet": "class Server(object):\n def __init__(self, args, eval_loader, candidate_seeds, log_dir):\n self.args = args\n self.eval_loader = eval_loader\n self.candidate_seeds = candidate_seeds\n self.tokenizer = AutoTokenizer... | import argparse
import os
import time
import random
import numpy as np
import torch
import yaml
import json
from server import Server
from client import Client
from utils_data.load_data import get_loaders
from copy import deepcopy | 5,253 |
os.environ["TOKENIZERS_PARALLELISM"] = "false"
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# Federation
parser.add_argument('--num_clients', type=int, default=200, help='N in our paper')
parser.add_argument('-m', type=float, default=0.05, help='ratio of activate clients in each round')
parser.add_argument('--rounds', type=int, default=40, help='the total number of rounds')
parser.add_argument('--local_step', type=int, default=200, help=r'$\tau in our paper')
parser.add_argument('--batch_or_epoch', type=str, default='batch', choices=['epoch', 'batch'])
parser.add_argument('--equal_weight', default=False, action='store_true', help='if `true`, the weights among clients for aggregation are the same')
# Data
## Arguments related to data on both datasets
parser.add_argument('--dataset', type=str, default='instruct', choices=['instruct', 'dolly'])
parser.add_argument('--batch_size', type=int, default=1, help='batch size > 1 may cause error during running')
parser.add_argument('--max_length', type=int, default=1024, help='the max number of tokens of a data instance')
parser.add_argument('--use_prompts', default=True, help='if `true`, the prompt template from alpaca is adopted')
## Arguments related to data only for Dolly-15K
parser.add_argument('--iid', type=str, default='dir0.5', help=r'`dir{alpha}` means that \alpha in Dirichlet distribution, `0` means IID split')
parser.add_argument('--zerotask', default=7, type=int, help='the index of the task for evaluation in dolly-15K')
parser.add_argument('--dataset_subsample', type=float, default=1.0, help='used for sampling a subset from the original dataset, only effective for dolly-15K')
# Model
parser.add_argument('--model', type=str, default='datajuicer/LLaMA-1B-dj-refine-150B')
# Training
parser.add_argument('--lr', type=float, default=0.001, help=r'learning rate \eta')
parser.add_argument('--weight_decay', type=float, default=0.0, help='weight decay in MeZO')
parser.add_argument('--grad_clip', type=float, default=-100.0, help='clip the over large loss value, if < 0, disable this feature')
# Training args only for `FedKSeed`
parser.add_argument('-K', type=int, default=4096, help='ratio of active clients in each round')
parser.add_argument('--zo_eps', type=float, default=0.0005, help=r'\eps in MeZO')
# Training args only for `FedKSeed-Pro`
parser.add_argument('--bias_sampling', default=False, action='store_true', help='if `true`, the probabilities of candidate seeds to be sampled are not identical, i.e., FedKSeed-Pro')
parser.add_argument('--bias_loss_clip', default=1000.0, type=float, help='scalar gradient whose abstract values exceeds this value will be cliped')
parser.add_argument('--grad_initial', default=0.0, type=float, help='initial value of scalar gradient history corresponding to each candidate seed')
# Environment
parser.add_argument('--device', type=int, default=0, help='index of the targeted cuda device')
parser.add_argument('--log', default=False, action='store_true', help='if `true`, running logs will be recorded in files')
parser.add_argument('--log_root', default='logs', help='root path of log files')
parser.add_argument('--seed', default=42, type=int, help='global seed, for reproducibility')
# Evaluation
parser.add_argument('--eval_metric', default='rouge', type=str, choices=['rouge', 'loss'], help='metric to evaluate global model in the last round')
# Checkpoints
parser.add_argument('--save', default=False, action='store_true', help='if `true`, the checkpoint of tuned models will be stored')
time_stamp = str(time.time())
args = parser.parse_args()
eval_avg_acc = []
memory_record_dic = {}
previous_metric = args.eval_metric
args.eval_metric = 'loss'
# set CUDA visibility to targeted cuda device, to avoid the several hundred MB memory consumption of device 0
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.device)
setup_seed(args.seed)
list_train_loader, eval_loader, _ = get_loaders(args)
if args.dataset == 'instruct':
args.iid = 'meta'
log_dir = time_stamp
if args.log_root != '':
log_dir = os.path.join(args.log_root, log_dir)
if args.log:
os.makedirs(log_dir)
config = yaml.dump(args, None)
config = '\n'.join(config.split('\n')[1:])
print('Configs: ')
print(config)
print('=====================')
if args.log:
with open(os.path.join(log_dir, 'config.yaml'), 'w') as writer:
writer.write(config)
# since only CUDA device is available, load all models on device 0
args.device = 0
client_indices_rounds = []
for _ in range(args.rounds):
client_indices_rounds.append(np.random.choice(np.arange(args.num_clients), size=int(args.num_clients * args.m), replace=False))
client_list = []
# sample `K` candidate seeds
candidate_seeds = np.random.randint(1, 100000000000, args.K)
server = Server(args, eval_loader=eval_loader, candidate_seeds=candidate_seeds, log_dir=log_dir)
for idx in range(args.num_clients):
|
os.environ["TOKENIZERS_PARALLELISM"] = "false"
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# Federation
parser.add_argument('--num_clients', type=int, default=200, help='N in our paper')
parser.add_argument('-m', type=float, default=0.05, help='ratio of activate clients in each round')
parser.add_argument('--rounds', type=int, default=40, help='the total number of rounds')
parser.add_argument('--local_step', type=int, default=200, help=r'$\tau in our paper')
parser.add_argument('--batch_or_epoch', type=str, default='batch', choices=['epoch', 'batch'])
parser.add_argument('--equal_weight', default=False, action='store_true', help='if `true`, the weights among clients for aggregation are the same')
# Data
## Arguments related to data on both datasets
parser.add_argument('--dataset', type=str, default='instruct', choices=['instruct', 'dolly'])
parser.add_argument('--batch_size', type=int, default=1, help='batch size > 1 may cause error during running')
parser.add_argument('--max_length', type=int, default=1024, help='the max number of tokens of a data instance')
parser.add_argument('--use_prompts', default=True, help='if `true`, the prompt template from alpaca is adopted')
## Arguments related to data only for Dolly-15K
parser.add_argument('--iid', type=str, default='dir0.5', help=r'`dir{alpha}` means that \alpha in Dirichlet distribution, `0` means IID split')
parser.add_argument('--zerotask', default=7, type=int, help='the index of the task for evaluation in dolly-15K')
parser.add_argument('--dataset_subsample', type=float, default=1.0, help='used for sampling a subset from the original dataset, only effective for dolly-15K')
# Model
parser.add_argument('--model', type=str, default='datajuicer/LLaMA-1B-dj-refine-150B')
# Training
parser.add_argument('--lr', type=float, default=0.001, help=r'learning rate \eta')
parser.add_argument('--weight_decay', type=float, default=0.0, help='weight decay in MeZO')
parser.add_argument('--grad_clip', type=float, default=-100.0, help='clip the over large loss value, if < 0, disable this feature')
# Training args only for `FedKSeed`
parser.add_argument('-K', type=int, default=4096, help='ratio of active clients in each round')
parser.add_argument('--zo_eps', type=float, default=0.0005, help=r'\eps in MeZO')
# Training args only for `FedKSeed-Pro`
parser.add_argument('--bias_sampling', default=False, action='store_true', help='if `true`, the probabilities of candidate seeds to be sampled are not identical, i.e., FedKSeed-Pro')
parser.add_argument('--bias_loss_clip', default=1000.0, type=float, help='scalar gradient whose abstract values exceeds this value will be cliped')
parser.add_argument('--grad_initial', default=0.0, type=float, help='initial value of scalar gradient history corresponding to each candidate seed')
# Environment
parser.add_argument('--device', type=int, default=0, help='index of the targeted cuda device')
parser.add_argument('--log', default=False, action='store_true', help='if `true`, running logs will be recorded in files')
parser.add_argument('--log_root', default='logs', help='root path of log files')
parser.add_argument('--seed', default=42, type=int, help='global seed, for reproducibility')
# Evaluation
parser.add_argument('--eval_metric', default='rouge', type=str, choices=['rouge', 'loss'], help='metric to evaluate global model in the last round')
# Checkpoints
parser.add_argument('--save', default=False, action='store_true', help='if `true`, the checkpoint of tuned models will be stored')
time_stamp = str(time.time())
args = parser.parse_args()
eval_avg_acc = []
memory_record_dic = {}
previous_metric = args.eval_metric
args.eval_metric = 'loss'
# set CUDA visibility to targeted cuda device, to avoid the several hundred MB memory consumption of device 0
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = str(args.device)
setup_seed(args.seed)
list_train_loader, eval_loader, _ = get_loaders(args)
if args.dataset == 'instruct':
args.iid = 'meta'
log_dir = time_stamp
if args.log_root != '':
log_dir = os.path.join(args.log_root, log_dir)
if args.log:
os.makedirs(log_dir)
config = yaml.dump(args, None)
config = '\n'.join(config.split('\n')[1:])
print('Configs: ')
print(config)
print('=====================')
if args.log:
with open(os.path.join(log_dir, 'config.yaml'), 'w') as writer:
writer.write(config)
# since only CUDA device is available, load all models on device 0
args.device = 0
client_indices_rounds = []
for _ in range(args.rounds):
client_indices_rounds.append(np.random.choice(np.arange(args.num_clients), size=int(args.num_clients * args.m), replace=False))
client_list = []
# sample `K` candidate seeds
candidate_seeds = np.random.randint(1, 100000000000, args.K)
server = Server(args, eval_loader=eval_loader, candidate_seeds=candidate_seeds, log_dir=log_dir)
for idx in range(args.num_clients): | client_list.append(Client(idx, args, candidate_seeds, list_train_loader[idx])) | 1 | 2023-12-08 02:58:31+00:00 | 8k |
merlresearch/PixPNet | pixpnet/symbolic/index_layers.py | [
{
"identifier": "AdaptiveAvgPool2d_factory",
"path": "pixpnet/symbolic/base_layers.py",
"snippet": "def flatten(input, start_dim: int = 0, end_dim: int = -1):\ndef cat(tensors, dim=0):\ndef unsqueeze(x, dim):\ndef np_sp_func(func):\n def wrapper(*input, **kwargs):\n def __init__(self) -> None:\n ... | from itertools import chain, product
from math import ceil
from typing import List, Sequence, Tuple, Union
from pixpnet.symbolic.base_layers import ( # noqa: F401
AdaptiveAvgPool2d_factory,
AvgPool2d_factory,
BatchNorm2d_factory,
Conv2d_factory,
Flatten,
Linear_factory,
MaxPool2d_factory,
Module,
ModuleDict,
Sequential,
_AdaptiveAvgPoolNd,
_BatchNorm_factory,
_ConvNd_factory,
_MaxPoolNd,
_NormBase_factory,
cat,
concat,
end_index,
flatten,
np_sp_func,
start_index,
unsqueeze,
)
from pixpnet.symbolic.exceptions import NonPositiveDimError
from pixpnet.symbolic.misc import _pair, unique_syms_factory
import numpy as np
import numbers | 4,110 |
def __init__(self, inplace=False):
super(ReLU, self).__init__()
def forward(self, input: Tensor) -> Tensor:
return input
SiLU = ReLU
Sigmoid = ReLU
GELU = ReLU
def conv2d(input, weight, bias, stride, padding=0, dilation=1, groups=1):
sh, sw = _pair(stride)
ph, pw = _pair(padding)
dh, dw = _pair(dilation)
if not (dh == dw == 1):
raise NotImplementedError
c_out, ci_per_group, kh, kw = weight.shape
co_per_group = c_out // groups
h_in, w_in = input.shape[-2:]
h_out = (h_in + 2 * ph - dh * (kh - 1) - 1) // sh + 1
w_out = (w_in + 2 * pw - dw * (kw - 1) - 1) // sw + 1
single_sample = input.ndim == 3
if single_sample:
input = input.reshape((1, *input.shape))
if any(d <= 0 for d in (c_out, h_out, w_out)):
raise NonPositiveDimError((c_out, h_out, w_out))
# input has identical channels or no groups or there is only 1 channel
identical_channels = has_identical_channels(input)
output = OutputTensor(
(input.shape[0], c_out, h_out, w_out), dtype=input.dtype, identical_channels=identical_channels or groups == 1
)
if not output.identical_channels:
print(
"WARNING: input does not have identical channels in conv2d and "
"groups != 1, this will take longer to compute"
)
for oh in range(h_out):
ih0 = (oh * sh) - ph
ih1 = ih0 + kh
if ih0 < 0:
ih0 = 0
for ow in range(w_out):
iw0 = (ow * sw) - pw
iw1 = iw0 + kw
if iw0 < 0:
iw0 = 0
# slice: n x c x kh x kw
# weight: c_out x c x kh x kw
if identical_channels:
# we can ignore groups. take first channel (arbitrary as all
# channels are the same)
x_slice = input[:, 0, ih0:ih1, iw0:iw1]
for n in range(output.shape[0]):
hc_n = HypercubeCollection(x_slice[n].flatten().tolist())
output[n, :, oh, ow] = hc_n
elif groups == 1:
x_slice = input[:, :, ih0:ih1, iw0:iw1]
for n in range(output.shape[0]):
hc_n = HypercubeCollection(x_slice[n].flatten().tolist())
output[n, :, oh, ow] = hc_n
else:
for g in range(groups):
co0 = g * co_per_group
co1 = co0 + co_per_group
ci0 = g * ci_per_group
ci1 = ci0 + ci_per_group
x_slice = input[:, ci0:ci1, ih0:ih1, iw0:iw1]
for n in range(output.shape[0]):
hc_n = HypercubeCollection(x_slice[n, :].flatten().tolist())
for c in range(co0, co1):
output[n, c, oh, ow] = hc_n
if single_sample:
output = output.squeeze(axis=0)
return output
def linear(input: Tensor, weight: Tensor, bias: Tensor) -> np.ndarray:
# out_features x in_features
output = OutputTensor((input.shape[0], weight.shape[0]), dtype=input.dtype, identical_channels=True)
for n in range(output.shape[0]):
hc_n = HypercubeCollection(input[n].tolist())
output[n, :] = hc_n
return output
def adaptive_avg_pool_2d(
input: np.ndarray, # Tensor
output_size=None,
):
input_height, input_width = input.shape[-2:]
output_height, output_width = _pair(output_size)
output_height = output_height or input_height
output_width = output_width or input_width
single_sample = input.ndim == 3
if single_sample:
input = input.reshape((1, *input.shape))
identical_channels = has_identical_channels(input)
output = OutputTensor(
(input.shape[0], input.shape[1], output_height, output_width),
dtype=input.dtype,
identical_channels=identical_channels,
)
if not identical_channels:
print(
"WARNING: input does not have identical channels in "
"adaptive_avg_pool_2d, this will take longer to compute"
)
for oh in range(output_height):
| # Copyright (c) 2022-2023 Mitsubishi Electric Research Laboratories (MERL)
# Copyright (c) PyTorch Contributors 2022
#
# SPDX-License-Identifier: AGPL-3.0-or-later
# SPDX-License-Identifier: BSD-3-Clause
# Some code based on PyTorch https://github.com/pytorch/pytorch
# noinspection PyUnresolvedReferences
class Tensor(np.ndarray):
__slots__ = ("_names",)
def __new__(cls, shape, name=None, **kwargs):
obj = super().__new__(cls, shape=shape, dtype=object, **kwargs)
names = [*product(*(range(d) for d in shape))]
vcs = [
HypercubeCollection.from_hypercube(Hypercube.from_slices(map(slice, indices)))
for indices in product(*map(range, shape))
]
obj.flat[:] = vcs
obj._names = names
return obj
@property
def names(self):
return self._names
_FULL_SLICE = slice(None)
class OutputTensor(np.ndarray):
__slots__ = "identical_channels", "_underlying"
def __new__(cls, shape, dtype=None, identical_channels=False, **kwargs):
if identical_channels:
shape_orig = shape
n, c, *dims = shape
assert c > 0
shape = (n, 1, *dims)
obj = super().__new__(cls, shape=shape, dtype=dtype, **kwargs)
obj._underlying = None
if identical_channels:
underlying = obj
obj = np.broadcast_to(underlying, shape_orig, subok=True)
obj._underlying = underlying
obj.identical_channels = identical_channels
return obj
def __setitem__(self, key, value):
if self._underlying is None:
super().__setitem__(key, value)
else: # identical_channels memory view trick
if len(key) >= 2:
assert key[1] == _FULL_SLICE
self._underlying[key] = value
def __iadd__(self, other):
if self._underlying is None:
if self.flags["WRITEABLE"]:
super().__iadd__(other)
else:
out = self + other
if self.identical_channels and isinstance(other, OutputTensor) and other.identical_channels:
out.identical_channels = True
return out
else: # identical_channels memory view trick
if isinstance(other, OutputTensor) and other.identical_channels:
self._underlying += other._underlying
elif (isinstance(other, np.ndarray) and other.ndim >= 2 and other.shape[1] == 1) or not isinstance(
other, np.ndarray
):
self._underlying += other
else:
return self + other
return self
def __isub__(self, other):
if self._underlying is None:
if self.flags["WRITEABLE"]:
super().__isub__(other)
else:
out = self - other
if self.identical_channels and isinstance(other, OutputTensor) and other.identical_channels:
out.identical_channels = True
return out
else: # identical_channels memory view trick
if isinstance(other, OutputTensor) and other.identical_channels:
self._underlying -= other._underlying
elif (isinstance(other, np.ndarray) and other.ndim >= 2 and other.shape[1] == 1) or not isinstance(
other, np.ndarray
):
self._underlying -= other
else:
return self - other
return self
def __imul__(self, other):
if self._underlying is None:
if self.flags["WRITEABLE"]:
super().__imul__(other)
else:
out = self * other
if self.identical_channels and isinstance(other, OutputTensor) and other.identical_channels:
out.identical_channels = True
return out
else: # identical_channels memory view trick
if isinstance(other, OutputTensor) and other.identical_channels:
self._underlying *= other._underlying
elif (isinstance(other, np.ndarray) and other.ndim >= 2 and other.shape[1] == 1) or not isinstance(
other, np.ndarray
):
self._underlying *= other
else:
return self * other
return self
def __array_finalize__(self, obj):
if obj is None:
return
if not hasattr(self, "_underlying"):
self._underlying = None
if not hasattr(self, "identical_channels"):
self.identical_channels = self.ndim >= 2 and self.shape[1] == 1
def has_identical_channels(tensor):
return (isinstance(tensor, OutputTensor) and tensor.identical_channels) or (
isinstance(tensor, np.ndarray) and tensor.ndim >= 2 and tensor.shape[1] == 1
)
unique_syms = unique_syms_factory(Tensor)
class Hypercube:
"""NOTE: step is not supported in this function"""
__slots__ = "indices", "ndim"
indices: Tuple[Tuple[int, int], ...]
ndim: int
@classmethod
def from_slices(
cls,
indices: Tuple[slice, ...],
) -> "Hypercube":
indices = tuple((s.stop, s.stop + 1) if s.start is None else (s.start, s.stop) for s in indices)
return cls(indices)
def __init__(
self,
indices: Tuple[Tuple[int, int], ...],
):
self.indices = indices
self.ndim = len(self.indices)
def serialize(self):
return [[*idx] for idx in self.indices]
@classmethod
def deserialize(cls, indices):
return cls(indices)
def union(self, other: "Hypercube") -> Union["Hypercube", Tuple["Hypercube", "Hypercube"]]:
if self == other:
return self
# contains_other # self contains other
# other_contains # other contains self
unequal_count = 0
contains_other = other_contains = concat_dim = None
for d in range(self.ndim):
(r00, r01), (r10, r11) = self.indices[d], other.indices[d]
r_int = r00 if r00 > r10 else r10, r01 if r01 < r11 else r11
adjacent = (r00 == r11) or (r10 == r01)
if not (len(r_int) or adjacent): # no intersection, cannot combine
return self, other
unequal = (r00 != r10) or (r01 != r11)
unequal_count += unequal
if unequal:
concat_dim = d
if contains_other is None or contains_other:
contains_other = r_int == (r10, r11) # r1 contained within r0
if other_contains is None or other_contains:
other_contains = r_int == (r00, r01) # r0 contained within r1
if contains_other:
return self
if other_contains:
return other
if unequal_count == 1:
# This means we can concatenate the hypercubes along a single axis
(r00, r01), (r10, r11) = (self.indices[concat_dim], other.indices[concat_dim])
indices = (
self.indices[:concat_dim]
+ ((r00 if r00 < r10 else r10, r01 if r01 > r11 else r11),)
+ self.indices[concat_dim + 1 :]
)
return Hypercube(indices)
return self, other
def _intersection_indices(self: "Hypercube", other: "Hypercube"):
indices = []
for d in range(self.ndim):
(r00, r01), (r10, r11) = self.indices[d], other.indices[d]
r_int = r00 if r00 > r10 else r10, r01 if r01 < r11 else r11
if not len(r_int): # no intersection
return None
indices.append((r00 if r00 > r10 else r10, r01 if r01 < r11 else r11))
return indices
def intersection(self: "Hypercube", other: "Hypercube") -> Union["Hypercube", None]:
indices = self._intersection_indices(other)
return None if indices is None else Hypercube(indices)
def atoms(self):
return {*product(*(range(a, b) for a, b in self.indices))}
def intersects(self, index: Tuple[int, ...]):
return all(r0 <= index[d] < r1 for d, (r0, r1) in enumerate(self.indices))
def corners(self, indices=None):
if indices is None:
indices = self.indices
return product(*indices)
def edges(self, indices=None):
if indices is None:
indices = self.indices
flags = [(0, 1)] * (len(indices) - 1)
# noinspection PyTypeChecker
flags.append((0,)) # only one side so no duplicate edges
for flags_i in product(*flags):
corner = [idx[flag] for idx, flag in zip(indices, flags_i)]
for j, flag in enumerate(flags_i):
corner_other = corner.copy()
corner_other[j] = indices[j][0 if flag else 1]
yield corner, corner_other
def difference(self, other):
indices = self._intersection_indices(other)
if indices is None:
return self # no intersection
corners = self.corners()
edges = self.edges()
int_corners = self.corners(indices)
int_edges = self.edges(indices)
cubes = []
# create cubes corner to corner (1:1 corners)
for corner, int_corner in zip(corners, int_corners):
indices_cube = []
for d0, d1 in zip(corner, int_corner):
if d0 > d1:
d0, d1 = d1, d0 # swap
indices_cube.append((d0, d1))
cubes.append(Hypercube(indices_cube))
# create cubes edge to edge (1:1 edges)
for edge, int_edge in zip(edges, int_edges):
indices_cube = []
for d0, d1 in zip(edge[0], int_edge[1]):
if d0 > d1:
d0, d1 = d1, d0 # swap
indices_cube.append((d0, d1))
cubes.append(Hypercube(indices_cube))
return HypercubeCollection.from_hypercubes(cubes)
def as_slice(self, all_channels=False): # -> Tuple[slice]
return tuple(
slice(None) if all_channels and i == 1 else slice(i_a, i_b) for i, (i_a, i_b) in enumerate(self.indices)
)
def take_from(self, arr, all_channels=False):
assert self.ndim == arr.ndim
return arr[self.as_slice(all_channels=all_channels)]
def __len__(self):
size = 1
for r0, r1 in self.indices:
size *= r1 - r0
return size
def __eq__(self, other):
return self.indices == other.indices
def __or__(self, other):
return self.union(other)
def __and__(self, other):
return self.intersection(other)
def __sub__(self, other):
return self.difference(other)
def __repr__(self):
return f"Hypercube(indices={self.indices})"
def __str__(self):
return repr(self)
class HypercubeCollection:
__slots__ = ("hypercubes",)
@classmethod
def from_hypercube(cls, hypercube: Hypercube) -> "HypercubeCollection":
obj = HypercubeCollection.__new__(cls)
obj.hypercubes = [hypercube]
return obj
@classmethod
def from_hypercubes(cls, hypercubes: Sequence[Hypercube]) -> "HypercubeCollection":
obj = HypercubeCollection.__new__(cls)
obj.hypercubes = hypercubes
return obj
def __init__(self, *args: Sequence["HypercubeCollection"]):
hypercubes = [*chain.from_iterable(hc.hypercubes for hc in chain.from_iterable(args))]
self.hypercubes = self._reduce_hcs(hypercubes)
def serialize(self):
return [hc.serialize() for hc in self.hypercubes]
@classmethod
def deserialize(cls, arr_indices):
return cls.from_hypercubes([Hypercube.deserialize(indices) for indices in arr_indices])
@staticmethod
def _reduce_hcs(hypercubes: List[Hypercube]) -> List[Hypercube]:
uncombined = []
combined = []
while hypercubes:
hc0 = hypercubes.pop()
HypercubeCollection._compare_hcs(
hc0, compare_src=hypercubes, combined_dest=combined, uncombined_dest=uncombined
)
while combined:
hc0 = combined.pop()
HypercubeCollection._compare_hcs(
hc0, compare_src=uncombined, combined_dest=combined, uncombined_dest=uncombined
)
return uncombined
@staticmethod
def _compare_hcs(hc0: Hypercube, compare_src: List, combined_dest: List, uncombined_dest: List):
idxs_to_drop = []
for i, hc1 in enumerate(compare_src):
hcc = hc0 | hc1
if not isinstance(hcc, tuple):
combined_dest.append(hcc)
idxs_to_drop.append(i)
break
else:
uncombined_dest.append(hc0)
for i in idxs_to_drop:
del compare_src[i]
def atoms(self, *args):
if args:
print("ignored:", args)
return set().union(*(hc.atoms() for hc in self.hypercubes))
def intersects(self, index: Tuple[int]):
for hc in self.hypercubes:
if hc.intersects(index):
return True
return False
def intersecting_indices(self, indices: Sequence[Tuple[int]]):
return [index for index in indices if self.intersects(index)]
def difference(self, other):
if isinstance(other, Hypercube):
hypercubes = [hc.difference(other) for hc in self.hypercubes]
else:
hypercubes = [hc.difference(hc_other) for hc in self.hypercubes for hc_other in other.hypercubes]
return HypercubeCollection(hypercubes)
def take_from(self, arr, all_channels=False):
to_intersect = []
for hc in self.hypercubes:
for hc_i in to_intersect:
hc = hc.difference(hc_i)
to_intersect.append(hc)
if len(to_intersect) == 1:
return to_intersect[0].take_from(arr, all_channels=all_channels)
return [to_int.take_from(arr, all_channels=all_channels) for to_int in to_intersect]
def as_slices(self, all_channels=False):
to_intersect = []
for hc in self.hypercubes:
for hc_i in to_intersect:
hc = hc.difference(hc_i)
to_intersect.append(hc)
return [hc.as_slice(all_channels=all_channels) for hc in to_intersect]
def __len__(self):
size = 0
to_intersect = []
for hc in self.hypercubes:
for hc_i in to_intersect:
hc = hc.difference(hc_i)
size += len(hc)
to_intersect.append(hc)
return size
def __or__(self, other: "HypercubeCollection") -> "HypercubeCollection":
"""Union operator ``self | other``"""
return HypercubeCollection((self, other))
def __add__(self, other: "HypercubeCollection") -> "HypercubeCollection":
return HypercubeCollection((self, other))
def __mul__(self, other: "HypercubeCollection") -> "HypercubeCollection":
return HypercubeCollection((self, other))
def __repr__(self):
return f"HypercubeCollection(hypercubes={self.hypercubes})"
def __str__(self):
return repr(self)
class ReLU(Module):
__slots__ = ()
def __init__(self, inplace=False):
super(ReLU, self).__init__()
def forward(self, input: Tensor) -> Tensor:
return input
SiLU = ReLU
Sigmoid = ReLU
GELU = ReLU
def conv2d(input, weight, bias, stride, padding=0, dilation=1, groups=1):
sh, sw = _pair(stride)
ph, pw = _pair(padding)
dh, dw = _pair(dilation)
if not (dh == dw == 1):
raise NotImplementedError
c_out, ci_per_group, kh, kw = weight.shape
co_per_group = c_out // groups
h_in, w_in = input.shape[-2:]
h_out = (h_in + 2 * ph - dh * (kh - 1) - 1) // sh + 1
w_out = (w_in + 2 * pw - dw * (kw - 1) - 1) // sw + 1
single_sample = input.ndim == 3
if single_sample:
input = input.reshape((1, *input.shape))
if any(d <= 0 for d in (c_out, h_out, w_out)):
raise NonPositiveDimError((c_out, h_out, w_out))
# input has identical channels or no groups or there is only 1 channel
identical_channels = has_identical_channels(input)
output = OutputTensor(
(input.shape[0], c_out, h_out, w_out), dtype=input.dtype, identical_channels=identical_channels or groups == 1
)
if not output.identical_channels:
print(
"WARNING: input does not have identical channels in conv2d and "
"groups != 1, this will take longer to compute"
)
for oh in range(h_out):
ih0 = (oh * sh) - ph
ih1 = ih0 + kh
if ih0 < 0:
ih0 = 0
for ow in range(w_out):
iw0 = (ow * sw) - pw
iw1 = iw0 + kw
if iw0 < 0:
iw0 = 0
# slice: n x c x kh x kw
# weight: c_out x c x kh x kw
if identical_channels:
# we can ignore groups. take first channel (arbitrary as all
# channels are the same)
x_slice = input[:, 0, ih0:ih1, iw0:iw1]
for n in range(output.shape[0]):
hc_n = HypercubeCollection(x_slice[n].flatten().tolist())
output[n, :, oh, ow] = hc_n
elif groups == 1:
x_slice = input[:, :, ih0:ih1, iw0:iw1]
for n in range(output.shape[0]):
hc_n = HypercubeCollection(x_slice[n].flatten().tolist())
output[n, :, oh, ow] = hc_n
else:
for g in range(groups):
co0 = g * co_per_group
co1 = co0 + co_per_group
ci0 = g * ci_per_group
ci1 = ci0 + ci_per_group
x_slice = input[:, ci0:ci1, ih0:ih1, iw0:iw1]
for n in range(output.shape[0]):
hc_n = HypercubeCollection(x_slice[n, :].flatten().tolist())
for c in range(co0, co1):
output[n, c, oh, ow] = hc_n
if single_sample:
output = output.squeeze(axis=0)
return output
def linear(input: Tensor, weight: Tensor, bias: Tensor) -> np.ndarray:
# out_features x in_features
output = OutputTensor((input.shape[0], weight.shape[0]), dtype=input.dtype, identical_channels=True)
for n in range(output.shape[0]):
hc_n = HypercubeCollection(input[n].tolist())
output[n, :] = hc_n
return output
def adaptive_avg_pool_2d(
input: np.ndarray, # Tensor
output_size=None,
):
input_height, input_width = input.shape[-2:]
output_height, output_width = _pair(output_size)
output_height = output_height or input_height
output_width = output_width or input_width
single_sample = input.ndim == 3
if single_sample:
input = input.reshape((1, *input.shape))
identical_channels = has_identical_channels(input)
output = OutputTensor(
(input.shape[0], input.shape[1], output_height, output_width),
dtype=input.dtype,
identical_channels=identical_channels,
)
if not identical_channels:
print(
"WARNING: input does not have identical channels in "
"adaptive_avg_pool_2d, this will take longer to compute"
)
for oh in range(output_height): | ih0 = start_index(oh, output_height, input_height) | 0 | 2023-12-06 23:49:31+00:00 | 8k |
Dinghow/UIM | seg_matting_tool/test.py | [
{
"identifier": "dataset",
"path": "util/dataset.py",
"snippet": "IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm']\n BASE_DIR = 'Combined_Dataset'\nclass Composition1KMatting(Dataset):\nclass Combined4ClassesMatting(Dataset):\nclass RealWorldMatting(Dataset):\n def __init__(self,... | import numpy as np
import os.path
import logging
import argparse
import cv2
import torch.nn.parallel
import numpy as np
import util.helpers as helpers
import os
import random
import time
import cv2
import numpy as np
import logging
import argparse
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch.multiprocessing as mp
import torch.distributed as dist
from PIL import Image
from util import dataset
from util.util import AverageMeter, compute_mse, compute_sad, compute_gradient, compute_connectivity, get_cuda_devices, get_unknown_tensor_from_pred
from torch.nn.functional import upsample
from torchvision import transforms
from tensorboardX import SummaryWriter
from util.custom_transforms import interactiveMattingTransform
from util import dataset, config, helpers
from model.mattingnet import Unified_Interactive_Matting
from model.mattingnet import Unified_Interactive_Matting_trimap | 5,527 | #coding=utf-8
#import apex
def sort_dict(dict_src):
dict_new = {}
for k in sorted(dict_src):
dict_new.update({k: dict_src[k]})
return dict_new
def get_parser():
parser = argparse.ArgumentParser(description='PyTorch Semantic Segmentation')
parser.add_argument('--config', type=str, default='config/ade20k/ade20k_pspnet50.yaml', help='config file')
parser.add_argument('opts', help='see config/ade20k/ade20k_pspnet50.yaml for all options', default=None, nargs=argparse.REMAINDER)
args = parser.parse_args()
assert args.config is not None
cfg = config.load_cfg_from_cfg_file(args.config)
if args.opts is not None:
cfg = config.merge_cfg_from_list(cfg, args.opts)
return cfg
def get_logger():
logger_name = "main-logger"
logger = logging.getLogger(logger_name)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
fmt = "[%(asctime)s %(levelname)s %(filename)s line %(lineno)d %(process)d] %(message)s"
handler.setFormatter(logging.Formatter(fmt))
logger.addHandler(handler)
return logger
def get_relax_pad(relax_pad, extreme_points):
if relax_pad <= 0:
return 0
if relax_pad >= 1:
return int(relax_pad)
x_min, y_min = np.min(extreme_points, axis=0)
x_max, y_max = np.max(extreme_points, axis=0)
x_len = x_max - x_min + 1
y_len = y_max - y_min + 1
return max(20, int(relax_pad * max(x_len, y_len)))
def main():
global args, logger, writer
use_void_pixels=True
logger = get_logger()
args = get_parser()
# writer = SummaryWriter(args.save_folder)
if args.test_gpu:
os.environ["CUDA_VISIBLE_DEVICES"] = ','.join(str(x) for x in args.test_gpu)
else:
args.test_gpu = get_cuda_devices()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
logger.info(args)# 在屏幕上打印信息
if args.manual_seed is not None:
random.seed(args.manual_seed)
np.random.seed(args.manual_seed)
torch.manual_seed(args.manual_seed)
torch.cuda.manual_seed(args.manual_seed)
torch.cuda.manual_seed_all(args.manual_seed)
cudnn.benchmark = False
cudnn.deterministic = True
# transform and dataloader
_interactive_matting_transform = interactiveMattingTransform(channel=args.in_channels, no_crop=args.no_crop, relax_crop=args.relax_crop,\
use_iogpoints=args.use_iogpoints, use_roimasking=args.use_roimasking, use_trimap=args.use_trimap,\
use_in_point=args.use_in_point, use_bbox=args.use_bbox, use_iogdextr=args.use_iogdextr, use_extreme_points=args.use_extreme_points, use_scribble=args.use_scribble,\
rotate_degree=args.rotate_degree, scale=args.scale, shear=args.shear,\
flip=args.flip, crop_size=args.crop_size, mask_type=args.mask_type, bbox_type=args.bbox_type)
composed_transforms_ts = _interactive_matting_transform.getTestTransform()
val_data = dataset.Composition1KMatting(root=args.data_root, split=args.test_split,transform=composed_transforms_ts, task=args.task, num_bgs=args.test_num_bgs)
val_loader = torch.utils.data.DataLoader(val_data, batch_size=args.batch_size_test, shuffle=False, num_workers=args.workers_test, pin_memory=True, sampler=None)
# model
if args.arch == 'uim':
model = Unified_Interactive_Matting(n_classes=args.classes, in_channels=args.in_channels, encoder_layers=args.encoder_layers, decoder_layers=args.decoder_layers, fusion_method=args.fusion_method)
elif args.arch == 'uim_trimap':
model = Unified_Interactive_Matting_trimap(n_classes=args.classes, in_channels=args.in_channels, encoder_layers=args.encoder_layers, decoder_layers=args.decoder_layers, fusion_method=args.fusion_method)
else:
raise RuntimeError('Wrong arch.')
logger.info(model)
model = torch.nn.DataParallel(model)
cudnn.benchmark = True
model = model.to(device)
model.eval()
# checkpoint
model_path = args.model_path
if os.path.isfile(model_path):
logger.info("=> loading checkpoint '{}'".format(model_path))
checkpoint = torch.load(model_path)
model.load_state_dict(checkpoint)
logger.info("=> loaded checkpoint '{}'".format(model_path))
else:
raise RuntimeError("=> no checkpoint found at '{}'".format(model_path))
# evaluate
print('evaluating Network')
eval_result = dict()
| #coding=utf-8
#import apex
def sort_dict(dict_src):
dict_new = {}
for k in sorted(dict_src):
dict_new.update({k: dict_src[k]})
return dict_new
def get_parser():
parser = argparse.ArgumentParser(description='PyTorch Semantic Segmentation')
parser.add_argument('--config', type=str, default='config/ade20k/ade20k_pspnet50.yaml', help='config file')
parser.add_argument('opts', help='see config/ade20k/ade20k_pspnet50.yaml for all options', default=None, nargs=argparse.REMAINDER)
args = parser.parse_args()
assert args.config is not None
cfg = config.load_cfg_from_cfg_file(args.config)
if args.opts is not None:
cfg = config.merge_cfg_from_list(cfg, args.opts)
return cfg
def get_logger():
logger_name = "main-logger"
logger = logging.getLogger(logger_name)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
fmt = "[%(asctime)s %(levelname)s %(filename)s line %(lineno)d %(process)d] %(message)s"
handler.setFormatter(logging.Formatter(fmt))
logger.addHandler(handler)
return logger
def get_relax_pad(relax_pad, extreme_points):
if relax_pad <= 0:
return 0
if relax_pad >= 1:
return int(relax_pad)
x_min, y_min = np.min(extreme_points, axis=0)
x_max, y_max = np.max(extreme_points, axis=0)
x_len = x_max - x_min + 1
y_len = y_max - y_min + 1
return max(20, int(relax_pad * max(x_len, y_len)))
def main():
global args, logger, writer
use_void_pixels=True
logger = get_logger()
args = get_parser()
# writer = SummaryWriter(args.save_folder)
if args.test_gpu:
os.environ["CUDA_VISIBLE_DEVICES"] = ','.join(str(x) for x in args.test_gpu)
else:
args.test_gpu = get_cuda_devices()
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
logger.info(args)# 在屏幕上打印信息
if args.manual_seed is not None:
random.seed(args.manual_seed)
np.random.seed(args.manual_seed)
torch.manual_seed(args.manual_seed)
torch.cuda.manual_seed(args.manual_seed)
torch.cuda.manual_seed_all(args.manual_seed)
cudnn.benchmark = False
cudnn.deterministic = True
# transform and dataloader
_interactive_matting_transform = interactiveMattingTransform(channel=args.in_channels, no_crop=args.no_crop, relax_crop=args.relax_crop,\
use_iogpoints=args.use_iogpoints, use_roimasking=args.use_roimasking, use_trimap=args.use_trimap,\
use_in_point=args.use_in_point, use_bbox=args.use_bbox, use_iogdextr=args.use_iogdextr, use_extreme_points=args.use_extreme_points, use_scribble=args.use_scribble,\
rotate_degree=args.rotate_degree, scale=args.scale, shear=args.shear,\
flip=args.flip, crop_size=args.crop_size, mask_type=args.mask_type, bbox_type=args.bbox_type)
composed_transforms_ts = _interactive_matting_transform.getTestTransform()
val_data = dataset.Composition1KMatting(root=args.data_root, split=args.test_split,transform=composed_transforms_ts, task=args.task, num_bgs=args.test_num_bgs)
val_loader = torch.utils.data.DataLoader(val_data, batch_size=args.batch_size_test, shuffle=False, num_workers=args.workers_test, pin_memory=True, sampler=None)
# model
if args.arch == 'uim':
model = Unified_Interactive_Matting(n_classes=args.classes, in_channels=args.in_channels, encoder_layers=args.encoder_layers, decoder_layers=args.decoder_layers, fusion_method=args.fusion_method)
elif args.arch == 'uim_trimap':
model = Unified_Interactive_Matting_trimap(n_classes=args.classes, in_channels=args.in_channels, encoder_layers=args.encoder_layers, decoder_layers=args.decoder_layers, fusion_method=args.fusion_method)
else:
raise RuntimeError('Wrong arch.')
logger.info(model)
model = torch.nn.DataParallel(model)
cudnn.benchmark = True
model = model.to(device)
model.eval()
# checkpoint
model_path = args.model_path
if os.path.isfile(model_path):
logger.info("=> loading checkpoint '{}'".format(model_path))
checkpoint = torch.load(model_path)
model.load_state_dict(checkpoint)
logger.info("=> loaded checkpoint '{}'".format(model_path))
else:
raise RuntimeError("=> no checkpoint found at '{}'".format(model_path))
# evaluate
print('evaluating Network')
eval_result = dict() | eval_result['all_mse'] = AverageMeter() | 1 | 2023-12-07 09:03:48+00:00 | 8k |
dvmazur/mixtral-offloading | src/build_model.py | [
{
"identifier": "ExpertCache",
"path": "src/expert_cache.py",
"snippet": "class ExpertCache:\n def __init__(self, make_module: callable, main_size: int, offload_size: int, buffer_size: int):\n \"\"\"Dynamically loads an array of modules with identical hyperparameters\"\"\"\n self.module... | import os
import json
import typing as tp
import torch
from functools import cache
from dataclasses import dataclass
from torch import nn
from transformers import AutoConfig
from transformers.models.mixtral import MixtralForCausalLM, MixtralConfig
from safetensors.torch import load_file
from torch import nn
from tqdm.auto import trange
from hqq.core.quantize import BaseQuantizeConfig
from .expert_cache import ExpertCache
from .expert_wrapper import MixtralExpertWrapper
from .custom_layers import (
HQQLinearTritonSavable,
MixtralBLockSparseTop2MLP_HQQ,
SparseMoeWrapper,
)
from .utils import with_default_dtype | 6,774 |
@dataclass(frozen=True)
class OffloadConfig:
main_size: int
offload_size: int
buffer_size: int
offload_per_layer: int
class QuantConfig:
def __init__(
self,
ffn_config: BaseQuantizeConfig,
attn_config: BaseQuantizeConfig,
):
self.ffn_config = ffn_config
self.attn_config = attn_config
@cache
def get_ffn_metas(self, hidden_dim: int, ffn_dim: int) -> tuple[tp.Any, tp.Any]:
return (
HQQLinearTritonSavable.get_hqq_meta((hidden_dim, ffn_dim), self.ffn_config),
HQQLinearTritonSavable.get_hqq_meta((ffn_dim, hidden_dim), self.ffn_config),
)
def replace_attn_layers(
model: MixtralForCausalLM,
config: MixtralConfig,
quant_config: QuantConfig,
device: torch.device,
) -> None:
attn_quant_config = quant_config.attn_config
hidden_size = config.hidden_size
num_heads = config.num_attention_heads
head_dim = hidden_size // num_heads
num_key_value_heads = config.num_key_value_heads
shapes = [
(hidden_size, num_heads * head_dim),
(hidden_size, num_key_value_heads * head_dim),
(hidden_size, num_key_value_heads * head_dim),
(num_heads * head_dim, hidden_size),
]
shape_to_meta = {
shape: HQQLinearTritonSavable.get_hqq_meta(shape, attn_quant_config)
for shape in shapes
}
def patch_fct_hqq(shape, quant_config):
meta = shape_to_meta[shape]
layer = HQQLinearTritonSavable(None, quant_config, meta=meta)
return layer
for layer in model.model.layers:
layer.block_sparse_moe.gate = nn.Linear(
config.hidden_size,
config.num_local_experts,
dtype=torch.float16,
device=device,
bias=False,
)
layer.self_attn.q_proj = patch_fct_hqq(
(hidden_size, num_heads * head_dim), attn_quant_config
)
layer.self_attn.k_proj = patch_fct_hqq(
(hidden_size, num_key_value_heads * head_dim), attn_quant_config
)
layer.self_attn.v_proj = patch_fct_hqq(
(hidden_size, num_key_value_heads * head_dim), attn_quant_config
)
layer.self_attn.o_proj = patch_fct_hqq(
(hidden_size, num_heads * head_dim), attn_quant_config
)
@cache
def get_default_ffn_quant_config(ffn_dim: int = 14336, hidden_dim: int = 4096):
quant_config = BaseQuantizeConfig(
nbits=2,
group_size=16,
quant_zero=True,
quant_scale=True,
)
meta1 = HQQLinearTritonSavable.get_hqq_meta((hidden_dim, ffn_dim), quant_config)
meta2 = HQQLinearTritonSavable.get_hqq_meta((ffn_dim, hidden_dim), quant_config)
return quant_config, meta1, meta2
def make_empty_expert(
model_config: MixtralConfig, quant_config: QuantConfig
|
@dataclass(frozen=True)
class OffloadConfig:
main_size: int
offload_size: int
buffer_size: int
offload_per_layer: int
class QuantConfig:
def __init__(
self,
ffn_config: BaseQuantizeConfig,
attn_config: BaseQuantizeConfig,
):
self.ffn_config = ffn_config
self.attn_config = attn_config
@cache
def get_ffn_metas(self, hidden_dim: int, ffn_dim: int) -> tuple[tp.Any, tp.Any]:
return (
HQQLinearTritonSavable.get_hqq_meta((hidden_dim, ffn_dim), self.ffn_config),
HQQLinearTritonSavable.get_hqq_meta((ffn_dim, hidden_dim), self.ffn_config),
)
def replace_attn_layers(
model: MixtralForCausalLM,
config: MixtralConfig,
quant_config: QuantConfig,
device: torch.device,
) -> None:
attn_quant_config = quant_config.attn_config
hidden_size = config.hidden_size
num_heads = config.num_attention_heads
head_dim = hidden_size // num_heads
num_key_value_heads = config.num_key_value_heads
shapes = [
(hidden_size, num_heads * head_dim),
(hidden_size, num_key_value_heads * head_dim),
(hidden_size, num_key_value_heads * head_dim),
(num_heads * head_dim, hidden_size),
]
shape_to_meta = {
shape: HQQLinearTritonSavable.get_hqq_meta(shape, attn_quant_config)
for shape in shapes
}
def patch_fct_hqq(shape, quant_config):
meta = shape_to_meta[shape]
layer = HQQLinearTritonSavable(None, quant_config, meta=meta)
return layer
for layer in model.model.layers:
layer.block_sparse_moe.gate = nn.Linear(
config.hidden_size,
config.num_local_experts,
dtype=torch.float16,
device=device,
bias=False,
)
layer.self_attn.q_proj = patch_fct_hqq(
(hidden_size, num_heads * head_dim), attn_quant_config
)
layer.self_attn.k_proj = patch_fct_hqq(
(hidden_size, num_key_value_heads * head_dim), attn_quant_config
)
layer.self_attn.v_proj = patch_fct_hqq(
(hidden_size, num_key_value_heads * head_dim), attn_quant_config
)
layer.self_attn.o_proj = patch_fct_hqq(
(hidden_size, num_heads * head_dim), attn_quant_config
)
@cache
def get_default_ffn_quant_config(ffn_dim: int = 14336, hidden_dim: int = 4096):
quant_config = BaseQuantizeConfig(
nbits=2,
group_size=16,
quant_zero=True,
quant_scale=True,
)
meta1 = HQQLinearTritonSavable.get_hqq_meta((hidden_dim, ffn_dim), quant_config)
meta2 = HQQLinearTritonSavable.get_hqq_meta((ffn_dim, hidden_dim), quant_config)
return quant_config, meta1, meta2
def make_empty_expert(
model_config: MixtralConfig, quant_config: QuantConfig | ) -> MixtralBLockSparseTop2MLP_HQQ: | 3 | 2023-12-15 03:32:35+00:00 | 8k |
CircleRadon/Osprey | osprey/datasets/data_modules.py | [
{
"identifier": "IGNORE_INDEX",
"path": "osprey/constants.py",
"snippet": "IGNORE_INDEX = -100"
},
{
"identifier": "COCODataset",
"path": "osprey/datasets/stage2_data.py",
"snippet": "class COCODataset(CustomDataset):\n\n def __init__(self,\n tokenizer=None,\n ... | from dataclasses import dataclass
from torch.utils.data import ConcatDataset
from osprey.constants import IGNORE_INDEX
from .stage2_data import COCODataset, RefCOCO, RefCOCOP
from .vcr import VCRDataset
from .vg import VGDATA
from .stage2_data import PascalPart
from .stage2_data import PartImagenet
from .osprey_724k import OspreyDetailedDescription, OspreyConversations, OspreyShortForm, OspreyPartLevel, OspreyLVISPosNeg
import torch
import transformers
import json | 5,697 | class DataCollatorForDetDataset(object):
tokenizer: transformers.PreTrainedTokenizer
def __call__(self, instances):
input_ids, labels, img_metas, masks = tuple([instance.get(key,None) for instance in instances]
for key in ('input_ids',
'labels',
'img_metas',
'masks'))
input_ids = torch.nn.utils.rnn.pad_sequence(
input_ids,
batch_first=True,
padding_value=self.tokenizer.pad_token_id)
labels = torch.nn.utils.rnn.pad_sequence(labels,
batch_first=True,
padding_value=IGNORE_INDEX)
batch = dict(
input_ids=input_ids,
labels=labels,
attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
img_metas=img_metas,
masks = masks
)
if 'image' in instances[0]:
images = [instance['image'] for instance in instances]
if all(x is not None and x.shape == images[0].shape for x in images):
batch['images'] = torch.stack(images)
else:
batch['images'] = images
return batch
def make_multitask_data_module(tokenizer,
data_args) :
"""Make dataset and collator for supervised fine-tuning."""
if data_args.dataset_config is not None:
dataset_config = json.load(open(data_args.dataset_config))
train_dataset = build_osprey_dataset(dataset_config,
tokenizer=tokenizer,
data_args=data_args)
data_collator = DataCollatorForDetDataset(tokenizer=tokenizer)
return dict(train_dataset=train_dataset,
eval_dataset=None,
data_collator=data_collator)
def build_osprey_dataset(dataset_config,
tokenizer=None,
data_args=None,
**kwargs):
if isinstance(dataset_config, list):
datasets = []
for cfg in dataset_config:
temp_dataset = build_osprey_dataset(cfg, tokenizer=tokenizer, data_args=data_args, **kwargs)
datasets.append(temp_dataset)
for dataset in datasets:
print(type(dataset), f'len = {len(dataset)}')
return ConcatDataset(datasets)
dataset_type = dataset_config.pop('type')
if dataset_type == 'coco_data':
dataset = COCODataset(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'vcr':
dataset = VCRDataset(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'VGDATA':
dataset = VGDATA(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'RefCOCO':
dataset = RefCOCO(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'RefCOCOP':
dataset = RefCOCOP(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'PascalPart':
dataset = PascalPart(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'PartImagenet':
dataset = PartImagenet(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'OspreyDetailedDescription':
|
@dataclass
class DataCollatorForDetDataset(object):
tokenizer: transformers.PreTrainedTokenizer
def __call__(self, instances):
input_ids, labels, img_metas, masks = tuple([instance.get(key,None) for instance in instances]
for key in ('input_ids',
'labels',
'img_metas',
'masks'))
input_ids = torch.nn.utils.rnn.pad_sequence(
input_ids,
batch_first=True,
padding_value=self.tokenizer.pad_token_id)
labels = torch.nn.utils.rnn.pad_sequence(labels,
batch_first=True,
padding_value=IGNORE_INDEX)
batch = dict(
input_ids=input_ids,
labels=labels,
attention_mask=input_ids.ne(self.tokenizer.pad_token_id),
img_metas=img_metas,
masks = masks
)
if 'image' in instances[0]:
images = [instance['image'] for instance in instances]
if all(x is not None and x.shape == images[0].shape for x in images):
batch['images'] = torch.stack(images)
else:
batch['images'] = images
return batch
def make_multitask_data_module(tokenizer,
data_args) :
"""Make dataset and collator for supervised fine-tuning."""
if data_args.dataset_config is not None:
dataset_config = json.load(open(data_args.dataset_config))
train_dataset = build_osprey_dataset(dataset_config,
tokenizer=tokenizer,
data_args=data_args)
data_collator = DataCollatorForDetDataset(tokenizer=tokenizer)
return dict(train_dataset=train_dataset,
eval_dataset=None,
data_collator=data_collator)
def build_osprey_dataset(dataset_config,
tokenizer=None,
data_args=None,
**kwargs):
if isinstance(dataset_config, list):
datasets = []
for cfg in dataset_config:
temp_dataset = build_osprey_dataset(cfg, tokenizer=tokenizer, data_args=data_args, **kwargs)
datasets.append(temp_dataset)
for dataset in datasets:
print(type(dataset), f'len = {len(dataset)}')
return ConcatDataset(datasets)
dataset_type = dataset_config.pop('type')
if dataset_type == 'coco_data':
dataset = COCODataset(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'vcr':
dataset = VCRDataset(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'VGDATA':
dataset = VGDATA(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'RefCOCO':
dataset = RefCOCO(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'RefCOCOP':
dataset = RefCOCOP(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'PascalPart':
dataset = PascalPart(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'PartImagenet':
dataset = PartImagenet(
**dataset_config,
tokenizer=tokenizer,
data_args=data_args,
**kwargs,
)
elif dataset_type == 'OspreyDetailedDescription': | dataset = OspreyDetailedDescription( | 8 | 2023-12-17 16:21:45+00:00 | 8k |
open-mmlab/PIA | animatediff/models/unet_blocks.py | [
{
"identifier": "Transformer3DModel",
"path": "animatediff/models/attention.py",
"snippet": "class Transformer3DModel(ModelMixin, ConfigMixin):\n @register_to_config\n def __init__(\n self,\n num_attention_heads: int = 16,\n attention_head_dim: int = 88,\n in_channels: ... | import torch
import pdb
from torch import nn
from .attention import Transformer3DModel
from .resnet import Downsample3D, ResnetBlock3D, Upsample3D
from .motion_module import get_motion_module | 4,545 | ):
up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
if up_block_type == "UpBlock3D":
return UpBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel,
temb_channels=temb_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
resnet_time_scale_shift=resnet_time_scale_shift,
use_motion_module=use_motion_module,
motion_module_type=motion_module_type,
motion_module_kwargs=motion_module_kwargs,
)
elif up_block_type == "CrossAttnUpBlock3D":
if cross_attention_dim is None:
raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock3D")
return CrossAttnUpBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel,
temb_channels=temb_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
cross_attention_dim=cross_attention_dim,
attn_num_head_channels=attn_num_head_channels,
dual_cross_attention=dual_cross_attention,
use_linear_projection=use_linear_projection,
only_cross_attention=only_cross_attention,
upcast_attention=upcast_attention,
resnet_time_scale_shift=resnet_time_scale_shift,
unet_use_cross_frame_attention=unet_use_cross_frame_attention,
unet_use_temporal_attention=unet_use_temporal_attention,
use_motion_module=use_motion_module,
motion_module_type=motion_module_type,
motion_module_kwargs=motion_module_kwargs,
)
raise ValueError(f"{up_block_type} does not exist.")
class UNetMidBlock3DCrossAttn(nn.Module):
def __init__(
self,
in_channels: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_shift: str = "default",
resnet_act_fn: str = "swish",
resnet_groups: int = 32,
resnet_pre_norm: bool = True,
attn_num_head_channels=1,
output_scale_factor=1.0,
cross_attention_dim=1280,
dual_cross_attention=False,
use_linear_projection=False,
upcast_attention=False,
unet_use_cross_frame_attention=None,
unet_use_temporal_attention=None,
use_motion_module=None,
motion_module_type=None,
motion_module_kwargs=None,
):
super().__init__()
self.has_cross_attention = True
self.attn_num_head_channels = attn_num_head_channels
resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
# there is always at least one resnet
resnets = [
ResnetBlock3D(
in_channels=in_channels,
out_channels=in_channels,
temb_channels=temb_channels,
eps=resnet_eps,
groups=resnet_groups,
dropout=dropout,
time_embedding_norm=resnet_time_scale_shift,
non_linearity=resnet_act_fn,
output_scale_factor=output_scale_factor,
pre_norm=resnet_pre_norm,
)
]
attentions = []
motion_modules = []
for _ in range(num_layers):
if dual_cross_attention:
raise NotImplementedError
attentions.append(
Transformer3DModel(
attn_num_head_channels,
in_channels // attn_num_head_channels,
in_channels=in_channels,
num_layers=1,
cross_attention_dim=cross_attention_dim,
norm_num_groups=resnet_groups,
use_linear_projection=use_linear_projection,
upcast_attention=upcast_attention,
unet_use_cross_frame_attention=unet_use_cross_frame_attention,
unet_use_temporal_attention=unet_use_temporal_attention,
)
)
motion_modules.append(
| # Adapted from https://github.com/guoyww/AnimateDiff
def get_down_block(
down_block_type,
num_layers,
in_channels,
out_channels,
temb_channels,
add_downsample,
resnet_eps,
resnet_act_fn,
attn_num_head_channels,
resnet_groups=None,
cross_attention_dim=None,
downsample_padding=None,
dual_cross_attention=False,
use_linear_projection=False,
only_cross_attention=False,
upcast_attention=False,
resnet_time_scale_shift="default",
unet_use_cross_frame_attention=None,
unet_use_temporal_attention=None,
use_motion_module=None,
motion_module_type=None,
motion_module_kwargs=None,
):
down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_type
if down_block_type == "DownBlock3D":
return DownBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
add_downsample=add_downsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
downsample_padding=downsample_padding,
resnet_time_scale_shift=resnet_time_scale_shift,
use_motion_module=use_motion_module,
motion_module_type=motion_module_type,
motion_module_kwargs=motion_module_kwargs,
)
elif down_block_type == "CrossAttnDownBlock3D":
if cross_attention_dim is None:
raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock3D")
return CrossAttnDownBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
add_downsample=add_downsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
downsample_padding=downsample_padding,
cross_attention_dim=cross_attention_dim,
attn_num_head_channels=attn_num_head_channels,
dual_cross_attention=dual_cross_attention,
use_linear_projection=use_linear_projection,
only_cross_attention=only_cross_attention,
upcast_attention=upcast_attention,
resnet_time_scale_shift=resnet_time_scale_shift,
unet_use_cross_frame_attention=unet_use_cross_frame_attention,
unet_use_temporal_attention=unet_use_temporal_attention,
use_motion_module=use_motion_module,
motion_module_type=motion_module_type,
motion_module_kwargs=motion_module_kwargs,
)
raise ValueError(f"{down_block_type} does not exist.")
def get_up_block(
up_block_type,
num_layers,
in_channels,
out_channels,
prev_output_channel,
temb_channels,
add_upsample,
resnet_eps,
resnet_act_fn,
attn_num_head_channels,
resnet_groups=None,
cross_attention_dim=None,
dual_cross_attention=False,
use_linear_projection=False,
only_cross_attention=False,
upcast_attention=False,
resnet_time_scale_shift="default",
unet_use_cross_frame_attention=None,
unet_use_temporal_attention=None,
use_motion_module=None,
motion_module_type=None,
motion_module_kwargs=None,
):
up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
if up_block_type == "UpBlock3D":
return UpBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel,
temb_channels=temb_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
resnet_time_scale_shift=resnet_time_scale_shift,
use_motion_module=use_motion_module,
motion_module_type=motion_module_type,
motion_module_kwargs=motion_module_kwargs,
)
elif up_block_type == "CrossAttnUpBlock3D":
if cross_attention_dim is None:
raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock3D")
return CrossAttnUpBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel,
temb_channels=temb_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
cross_attention_dim=cross_attention_dim,
attn_num_head_channels=attn_num_head_channels,
dual_cross_attention=dual_cross_attention,
use_linear_projection=use_linear_projection,
only_cross_attention=only_cross_attention,
upcast_attention=upcast_attention,
resnet_time_scale_shift=resnet_time_scale_shift,
unet_use_cross_frame_attention=unet_use_cross_frame_attention,
unet_use_temporal_attention=unet_use_temporal_attention,
use_motion_module=use_motion_module,
motion_module_type=motion_module_type,
motion_module_kwargs=motion_module_kwargs,
)
raise ValueError(f"{up_block_type} does not exist.")
class UNetMidBlock3DCrossAttn(nn.Module):
def __init__(
self,
in_channels: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_shift: str = "default",
resnet_act_fn: str = "swish",
resnet_groups: int = 32,
resnet_pre_norm: bool = True,
attn_num_head_channels=1,
output_scale_factor=1.0,
cross_attention_dim=1280,
dual_cross_attention=False,
use_linear_projection=False,
upcast_attention=False,
unet_use_cross_frame_attention=None,
unet_use_temporal_attention=None,
use_motion_module=None,
motion_module_type=None,
motion_module_kwargs=None,
):
super().__init__()
self.has_cross_attention = True
self.attn_num_head_channels = attn_num_head_channels
resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
# there is always at least one resnet
resnets = [
ResnetBlock3D(
in_channels=in_channels,
out_channels=in_channels,
temb_channels=temb_channels,
eps=resnet_eps,
groups=resnet_groups,
dropout=dropout,
time_embedding_norm=resnet_time_scale_shift,
non_linearity=resnet_act_fn,
output_scale_factor=output_scale_factor,
pre_norm=resnet_pre_norm,
)
]
attentions = []
motion_modules = []
for _ in range(num_layers):
if dual_cross_attention:
raise NotImplementedError
attentions.append(
Transformer3DModel(
attn_num_head_channels,
in_channels // attn_num_head_channels,
in_channels=in_channels,
num_layers=1,
cross_attention_dim=cross_attention_dim,
norm_num_groups=resnet_groups,
use_linear_projection=use_linear_projection,
upcast_attention=upcast_attention,
unet_use_cross_frame_attention=unet_use_cross_frame_attention,
unet_use_temporal_attention=unet_use_temporal_attention,
)
)
motion_modules.append( | get_motion_module( | 4 | 2023-12-21 03:29:34+00:00 | 8k |
3DTopia/OpenLRM | lrm/models/rendering/synthesizer.py | [
{
"identifier": "ImportanceRenderer",
"path": "lrm/models/rendering/utils/renderer.py",
"snippet": "class ImportanceRenderer(torch.nn.Module):\n \"\"\"\n Modified original version to filter out-of-box samples as TensoRF does.\n \n Reference:\n TensoRF: https://github.com/apchenstu/TensoRF... | import itertools
import torch
import torch.nn as nn
from .utils.renderer import ImportanceRenderer
from .utils.ray_sampler import RaySampler | 4,667 | # ORIGINAL LICENSE
# SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# Modified by Zexin He
# The modifications are subject to the same license as the original.
class OSGDecoder(nn.Module):
"""
Triplane decoder that gives RGB and sigma values from sampled features.
Using ReLU here instead of Softplus in the original implementation.
Reference:
EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112
"""
def __init__(self, n_features: int,
hidden_dim: int = 64, num_layers: int = 4, activation: nn.Module = nn.ReLU):
super().__init__()
self.net = nn.Sequential(
nn.Linear(3 * n_features, hidden_dim),
activation(),
*itertools.chain(*[[
nn.Linear(hidden_dim, hidden_dim),
activation(),
] for _ in range(num_layers - 2)]),
nn.Linear(hidden_dim, 1 + 3),
)
# init all bias to zero
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.zeros_(m.bias)
def forward(self, sampled_features, ray_directions):
# Aggregate features by mean
# sampled_features = sampled_features.mean(1)
# Aggregate features by concatenation
_N, n_planes, _M, _C = sampled_features.shape
sampled_features = sampled_features.permute(0, 2, 1, 3).reshape(_N, _M, n_planes*_C)
x = sampled_features
N, M, C = x.shape
x = x.contiguous().view(N*M, C)
x = self.net(x)
x = x.view(N, M, -1)
rgb = torch.sigmoid(x[..., 1:])*(1 + 2*0.001) - 0.001 # Uses sigmoid clamping from MipNeRF
sigma = x[..., 0:1]
return {'rgb': rgb, 'sigma': sigma}
class TriplaneSynthesizer(nn.Module):
"""
Synthesizer that renders a triplane volume with planes and a camera.
Reference:
EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L19
"""
DEFAULT_RENDERING_KWARGS = {
'ray_start': 'auto',
'ray_end': 'auto',
'box_warp': 2.,
'white_back': True,
'disparity_space_sampling': False,
'clamp_mode': 'softplus',
'sampler_bbox_min': -1.,
'sampler_bbox_max': 1.,
}
def __init__(self, triplane_dim: int, samples_per_ray: int):
super().__init__()
# attributes
self.triplane_dim = triplane_dim
self.rendering_kwargs = {
**self.DEFAULT_RENDERING_KWARGS,
'depth_resolution': samples_per_ray // 2,
'depth_resolution_importance': samples_per_ray // 2,
}
# renderings
self.renderer = ImportanceRenderer()
| # ORIGINAL LICENSE
# SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# Modified by Zexin He
# The modifications are subject to the same license as the original.
class OSGDecoder(nn.Module):
"""
Triplane decoder that gives RGB and sigma values from sampled features.
Using ReLU here instead of Softplus in the original implementation.
Reference:
EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112
"""
def __init__(self, n_features: int,
hidden_dim: int = 64, num_layers: int = 4, activation: nn.Module = nn.ReLU):
super().__init__()
self.net = nn.Sequential(
nn.Linear(3 * n_features, hidden_dim),
activation(),
*itertools.chain(*[[
nn.Linear(hidden_dim, hidden_dim),
activation(),
] for _ in range(num_layers - 2)]),
nn.Linear(hidden_dim, 1 + 3),
)
# init all bias to zero
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.zeros_(m.bias)
def forward(self, sampled_features, ray_directions):
# Aggregate features by mean
# sampled_features = sampled_features.mean(1)
# Aggregate features by concatenation
_N, n_planes, _M, _C = sampled_features.shape
sampled_features = sampled_features.permute(0, 2, 1, 3).reshape(_N, _M, n_planes*_C)
x = sampled_features
N, M, C = x.shape
x = x.contiguous().view(N*M, C)
x = self.net(x)
x = x.view(N, M, -1)
rgb = torch.sigmoid(x[..., 1:])*(1 + 2*0.001) - 0.001 # Uses sigmoid clamping from MipNeRF
sigma = x[..., 0:1]
return {'rgb': rgb, 'sigma': sigma}
class TriplaneSynthesizer(nn.Module):
"""
Synthesizer that renders a triplane volume with planes and a camera.
Reference:
EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L19
"""
DEFAULT_RENDERING_KWARGS = {
'ray_start': 'auto',
'ray_end': 'auto',
'box_warp': 2.,
'white_back': True,
'disparity_space_sampling': False,
'clamp_mode': 'softplus',
'sampler_bbox_min': -1.,
'sampler_bbox_max': 1.,
}
def __init__(self, triplane_dim: int, samples_per_ray: int):
super().__init__()
# attributes
self.triplane_dim = triplane_dim
self.rendering_kwargs = {
**self.DEFAULT_RENDERING_KWARGS,
'depth_resolution': samples_per_ray // 2,
'depth_resolution_importance': samples_per_ray // 2,
}
# renderings
self.renderer = ImportanceRenderer() | self.ray_sampler = RaySampler() | 1 | 2023-12-20 10:52:01+00:00 | 8k |
xinghaochen/TinySAM | tinysam/modeling/sam.py | [
{
"identifier": "TinyViT",
"path": "tinysam/modeling/tiny_vit_sam.py",
"snippet": "class TinyViT(nn.Module):\n def __init__(self, img_size=224, in_chans=3, num_classes=1000,\n embed_dims=[96, 192, 384, 768], depths=[2, 2, 6, 2],\n num_heads=[3, 6, 12, 24],\n ... | import torch
from torch import nn
from torch.nn import functional as F
from typing import Any, Dict, List, Tuple, Union
from .tiny_vit_sam import TinyViT
from .image_encoder import ImageEncoderViT
from .mask_decoder import MaskDecoder
from .prompt_encoder import PromptEncoder | 5,529 | # 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: Union[ImageEncoderViT, TinyViT],
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: Union[ImageEncoderViT, TinyViT],
prompt_encoder: PromptEncoder, | mask_decoder: MaskDecoder, | 2 | 2023-12-19 11:25:54+00:00 | 8k |
dcharatan/pixelsplat | src/model/encoder/epipolar/epipolar_transformer.py | [
{
"identifier": "get_depth",
"path": "src/geometry/epipolar_lines.py",
"snippet": "def get_depth(\n origins: Float[Tensor, \"*#batch 3\"],\n directions: Float[Tensor, \"*#batch 3\"],\n xy: Float[Tensor, \"*#batch 2\"],\n extrinsics: Float[Tensor, \"*#batch 4 4\"],\n intrinsics: Float[Tens... | from dataclasses import dataclass
from functools import partial
from typing import Optional
from einops import rearrange
from jaxtyping import Float
from torch import Tensor, nn
from ....geometry.epipolar_lines import get_depth
from ....global_cfg import get_cfg
from ...encodings.positional_encoding import PositionalEncoding
from ...transformer.transformer import Transformer
from .conversions import depth_to_relative_disparity
from .epipolar_sampler import EpipolarSampler, EpipolarSampling
from .image_self_attention import ImageSelfAttention, ImageSelfAttentionCfg | 4,280 |
@dataclass
class EpipolarTransformerCfg:
self_attention: ImageSelfAttentionCfg
num_octaves: int
num_layers: int
num_heads: int
num_samples: int
d_dot: int
d_mlp: int
downscale: int
class EpipolarTransformer(nn.Module):
cfg: EpipolarTransformerCfg
epipolar_sampler: EpipolarSampler
depth_encoding: nn.Sequential
transformer: Transformer
downscaler: Optional[nn.Conv2d]
upscaler: Optional[nn.ConvTranspose2d]
upscale_refinement: Optional[nn.Sequential]
def __init__(
self,
cfg: EpipolarTransformerCfg,
d_in: int,
) -> None:
super().__init__()
self.cfg = cfg
self.epipolar_sampler = EpipolarSampler(
get_cfg().dataset.view_sampler.num_context_views,
cfg.num_samples,
)
if self.cfg.num_octaves > 0:
self.depth_encoding = nn.Sequential(
(pe := PositionalEncoding(cfg.num_octaves)),
nn.Linear(pe.d_out(1), d_in),
)
feed_forward_layer = partial(ConvFeedForward, cfg.self_attention)
self.transformer = Transformer(
d_in,
cfg.num_layers,
cfg.num_heads,
cfg.d_dot,
cfg.d_mlp,
selfatt=False,
kv_dim=d_in,
feed_forward_layer=feed_forward_layer,
)
if cfg.downscale:
self.downscaler = nn.Conv2d(d_in, d_in, cfg.downscale, cfg.downscale)
self.upscaler = nn.ConvTranspose2d(d_in, d_in, cfg.downscale, cfg.downscale)
self.upscale_refinement = nn.Sequential(
nn.Conv2d(d_in, d_in * 2, 7, 1, 3),
nn.GELU(),
nn.Conv2d(d_in * 2, d_in, 7, 1, 3),
)
def forward(
self,
features: Float[Tensor, "batch view channel height width"],
extrinsics: Float[Tensor, "batch view 4 4"],
intrinsics: Float[Tensor, "batch view 3 3"],
near: Float[Tensor, "batch view"],
far: Float[Tensor, "batch view"],
) -> tuple[Float[Tensor, "batch view channel height width"], EpipolarSampling,]:
b, v, _, h, w = features.shape
# If needed, apply downscaling.
if self.downscaler is not None:
features = rearrange(features, "b v c h w -> (b v) c h w")
features = self.downscaler(features)
features = rearrange(features, "(b v) c h w -> b v c h w", b=b, v=v)
# Get the samples used for epipolar attention.
sampling = self.epipolar_sampler.forward(
features, extrinsics, intrinsics, near, far
)
if self.cfg.num_octaves > 0:
# Compute positionally encoded depths for the features.
collect = self.epipolar_sampler.collect
|
@dataclass
class EpipolarTransformerCfg:
self_attention: ImageSelfAttentionCfg
num_octaves: int
num_layers: int
num_heads: int
num_samples: int
d_dot: int
d_mlp: int
downscale: int
class EpipolarTransformer(nn.Module):
cfg: EpipolarTransformerCfg
epipolar_sampler: EpipolarSampler
depth_encoding: nn.Sequential
transformer: Transformer
downscaler: Optional[nn.Conv2d]
upscaler: Optional[nn.ConvTranspose2d]
upscale_refinement: Optional[nn.Sequential]
def __init__(
self,
cfg: EpipolarTransformerCfg,
d_in: int,
) -> None:
super().__init__()
self.cfg = cfg
self.epipolar_sampler = EpipolarSampler(
get_cfg().dataset.view_sampler.num_context_views,
cfg.num_samples,
)
if self.cfg.num_octaves > 0:
self.depth_encoding = nn.Sequential(
(pe := PositionalEncoding(cfg.num_octaves)),
nn.Linear(pe.d_out(1), d_in),
)
feed_forward_layer = partial(ConvFeedForward, cfg.self_attention)
self.transformer = Transformer(
d_in,
cfg.num_layers,
cfg.num_heads,
cfg.d_dot,
cfg.d_mlp,
selfatt=False,
kv_dim=d_in,
feed_forward_layer=feed_forward_layer,
)
if cfg.downscale:
self.downscaler = nn.Conv2d(d_in, d_in, cfg.downscale, cfg.downscale)
self.upscaler = nn.ConvTranspose2d(d_in, d_in, cfg.downscale, cfg.downscale)
self.upscale_refinement = nn.Sequential(
nn.Conv2d(d_in, d_in * 2, 7, 1, 3),
nn.GELU(),
nn.Conv2d(d_in * 2, d_in, 7, 1, 3),
)
def forward(
self,
features: Float[Tensor, "batch view channel height width"],
extrinsics: Float[Tensor, "batch view 4 4"],
intrinsics: Float[Tensor, "batch view 3 3"],
near: Float[Tensor, "batch view"],
far: Float[Tensor, "batch view"],
) -> tuple[Float[Tensor, "batch view channel height width"], EpipolarSampling,]:
b, v, _, h, w = features.shape
# If needed, apply downscaling.
if self.downscaler is not None:
features = rearrange(features, "b v c h w -> (b v) c h w")
features = self.downscaler(features)
features = rearrange(features, "(b v) c h w -> b v c h w", b=b, v=v)
# Get the samples used for epipolar attention.
sampling = self.epipolar_sampler.forward(
features, extrinsics, intrinsics, near, far
)
if self.cfg.num_octaves > 0:
# Compute positionally encoded depths for the features.
collect = self.epipolar_sampler.collect | depths = get_depth( | 0 | 2023-12-20 19:45:59+00:00 | 8k |
hutaiHang/Faster-Diffusion | controlnet_demo.py | [
{
"identifier": "register_controlnet_pipeline",
"path": "utils_sd.py",
"snippet": "def register_controlnet_pipeline(pipe):\r\n def new_call(self):\r\n @torch.no_grad()\r\n def call(\r\n prompt: Union[str, List[str]] = None,\r\n image: Union[\r\n torc... | import numpy as np
import cv2
import time
import torch
from PIL import Image
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, UniPCMultistepScheduler, DDIMScheduler
from controlnet_aux import HEDdetector, OpenposeDetector
from diffusers.utils import load_image
from utils_sd import register_controlnet_pipeline, register_faster_forward, seed_everything | 6,000 |
image = load_image("images/condition.jpeg")
image = np.array(image)
low_threshold = 100
high_threshold = 200
image = cv2.Canny(image, low_threshold, high_threshold)
image = image[:, :, None]
image = np.concatenate([image, image, image], axis=2)
image_condition = Image.fromarray(image)
controlnet = ControlNetModel.from_pretrained(
"lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16
).to('cuda')
pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
).to('cuda')
print('Warm up of the gpu')
for i in range(2):
image = pipe("Mona Lisa", image_condition).images[0]
#-------------------
print("Start Generating")
seed_everything(8888)
start_time = time.time()
image = pipe("Mona Lisa", image_condition).images[0]
end_time = time.time()
print("Origin Pipeline: {:.3f} seconds".format(end_time-start_time))
image.save('images/canny_out_origin.png')
register_controlnet_pipeline(pipe)
|
image = load_image("images/condition.jpeg")
image = np.array(image)
low_threshold = 100
high_threshold = 200
image = cv2.Canny(image, low_threshold, high_threshold)
image = image[:, :, None]
image = np.concatenate([image, image, image], axis=2)
image_condition = Image.fromarray(image)
controlnet = ControlNetModel.from_pretrained(
"lllyasviel/sd-controlnet-canny", torch_dtype=torch.float16
).to('cuda')
pipe = StableDiffusionControlNetPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16
).to('cuda')
print('Warm up of the gpu')
for i in range(2):
image = pipe("Mona Lisa", image_condition).images[0]
#-------------------
print("Start Generating")
seed_everything(8888)
start_time = time.time()
image = pipe("Mona Lisa", image_condition).images[0]
end_time = time.time()
print("Origin Pipeline: {:.3f} seconds".format(end_time-start_time))
image.save('images/canny_out_origin.png')
register_controlnet_pipeline(pipe) | register_faster_forward(pipe.unet) | 1 | 2023-12-15 05:03:37+00:00 | 8k |
FoundationVision/GLEE | app/GLEE/glee/backbone/eva02-dino.py | [
{
"identifier": "PatchEmbed",
"path": "app/GLEE/glee/backbone/eva_02_utils.py",
"snippet": "class PatchEmbed(nn.Module):\n \"\"\"\n Image to Patch Embedding.\n \"\"\"\n\n def __init__(\n self, kernel_size=(16, 16), stride=(16, 16), padding=(0, 0), in_chans=3, embed_dim=768\n ):\n ... | import logging
import math
import fvcore.nn.weight_init as weight_init
import torch
import torch.nn as nn
import torch.nn.functional as F
import xformers.ops as xops
from functools import partial
from detectron2.layers import CNNBlockBase, Conv2d, get_norm
from detectron2.modeling.backbone.fpn import _assert_strides_are_log2_contiguous
from detectron2.modeling.backbone import Backbone
from .eva_02_utils import (
PatchEmbed,
add_decomposed_rel_pos,
get_abs_pos,
window_partition,
window_unpartition,
VisionRotaryEmbeddingFast,
)
from timm.models.layers import DropPath
from fairscale.nn.checkpoint import checkpoint_wrapper | 4,384 | "bottleneck" conv layers.
norm (str or callable): normalization for all conv layers.
See :func:`layers.get_norm` for supported format.
act_layer (callable): activation for all conv layers.
"""
super().__init__(in_channels, out_channels, 1)
self.conv1 = Conv2d(in_channels, bottleneck_channels, 1, bias=False)
self.norm1 = get_norm(norm, bottleneck_channels)
self.act1 = act_layer()
self.conv2 = Conv2d(
bottleneck_channels,
bottleneck_channels,
3,
padding=1,
bias=False,
)
self.norm2 = get_norm(norm, bottleneck_channels)
self.act2 = act_layer()
self.conv3 = Conv2d(bottleneck_channels, out_channels, 1, bias=False)
self.norm3 = get_norm(norm, out_channels)
for layer in [self.conv1, self.conv2, self.conv3]:
weight_init.c2_msra_fill(layer)
for layer in [self.norm1, self.norm2]:
layer.weight.data.fill_(1.0)
layer.bias.data.zero_()
# zero init last norm layer.
self.norm3.weight.data.zero_()
self.norm3.bias.data.zero_()
def forward(self, x):
out = x
for layer in self.children():
out = layer(out)
out = x + out
return out
class Block(nn.Module):
"""Transformer blocks with support of window attention and residual propagation blocks"""
def __init__(
self,
dim,
num_heads,
mlp_ratio=4*2/3,
qkv_bias=True,
drop_path=0.0,
norm_layer=partial(nn.LayerNorm, eps=1e-6),
window_size=0,
use_residual_block=False,
rope=None,
xattn=True,
):
"""
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads in each ViT block.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool): If True, add a learnable bias to query, key, value.
drop_path (float): Stochastic depth rate.
norm_layer (nn.Module): Normalization layer.
act_layer (nn.Module): Activation layer.
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
window_size (int): Window size for window attention blocks. If it equals 0, then not
use window attention.
use_residual_block (bool): If True, use a residual block after the MLP block.
input_size (int or None): Input resolution for calculating the relative positional
parameter size.
"""
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(
dim,
num_heads=num_heads,
qkv_bias=qkv_bias,
rope=rope,
xattn=xattn,
)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
self.mlp = SwiGLU(
in_features=dim,
hidden_features=int(dim * mlp_ratio),
subln=True,
norm_layer=norm_layer,
)
self.window_size = window_size
self.use_residual_block = use_residual_block
if use_residual_block:
# Use a residual block with bottleneck channel as dim // 2
self.residual = ResBottleneckBlock(
in_channels=dim,
out_channels=dim,
bottleneck_channels=dim // 2,
norm="LN",
)
def forward(self, x):
shortcut = x
x = self.norm1(x)
# Window partition
if self.window_size > 0:
H, W = x.shape[1], x.shape[2]
x, pad_hw = window_partition(x, self.window_size)
x = self.attn(x)
# Reverse window partition
if self.window_size > 0:
|
try:
HAS_XFORMER=True
except:
HAS_XFORMER=False
pass
logger = logging.getLogger(__name__)
__all__ = ["EVA02_ViT", "SimpleFeaturePyramid", "get_vit_lr_decay_rate"]
class SwiGLU(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.SiLU, drop=0.,
norm_layer=nn.LayerNorm, subln=False
):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.w1 = nn.Linear(in_features, hidden_features)
self.w2 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.ffn_ln = norm_layer(hidden_features) if subln else nn.Identity()
self.w3 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x1 = self.w1(x)
x2 = self.w2(x)
hidden = self.act(x1) * x2
x = self.ffn_ln(hidden)
x = self.w3(x)
x = self.drop(x)
return x
class Attention(nn.Module):
def __init__(
self,
dim,
num_heads=8,
qkv_bias=True,
qk_scale=None,
attn_head_dim=None,
rope=None,
xattn=True,
):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
if attn_head_dim is not None:
head_dim = attn_head_dim
all_head_dim = head_dim * self.num_heads
self.scale = qk_scale or head_dim ** -0.5
self.q_proj = nn.Linear(dim, all_head_dim, bias=False)
self.k_proj = nn.Linear(dim, all_head_dim, bias=False)
self.v_proj = nn.Linear(dim, all_head_dim, bias=False)
if qkv_bias:
self.q_bias = nn.Parameter(torch.zeros(all_head_dim))
self.v_bias = nn.Parameter(torch.zeros(all_head_dim))
else:
self.q_bias = None
self.v_bias = None
self.rope = rope
self.xattn = xattn
self.proj = nn.Linear(all_head_dim, dim)
if not HAS_XFORMER:
self.xattn = False
def forward(self, x):
B, H, W, C = x.shape
x = x.view(B, -1, C)
N = H * W
q = F.linear(input=x, weight=self.q_proj.weight, bias=self.q_bias)
k = F.linear(input=x, weight=self.k_proj.weight, bias=None)
v = F.linear(input=x, weight=self.v_proj.weight, bias=self.v_bias)
q = q.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3) # B, num_heads, N, C
k = k.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
v = v.reshape(B, N, self.num_heads, -1).permute(0, 2, 1, 3)
## rope
q = self.rope(q).type_as(v)
k = self.rope(k).type_as(v)
if self.xattn:
q = q.permute(0, 2, 1, 3) # B, num_heads, N, C -> B, N, num_heads, C
k = k.permute(0, 2, 1, 3)
v = v.permute(0, 2, 1, 3)
x = xops.memory_efficient_attention(q, k, v)
x = x.reshape(B, N, -1)
else:
q = q * self.scale
attn = (q @ k.transpose(-2, -1))
attn = attn.softmax(dim=-1).type_as(x)
x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
x = self.proj(x)
x = x.view(B, H, W, C)
return x
class ResBottleneckBlock(CNNBlockBase):
"""
The standard bottleneck residual block without the last activation layer.
It contains 3 conv layers with kernels 1x1, 3x3, 1x1.
"""
def __init__(
self,
in_channels,
out_channels,
bottleneck_channels,
norm="LN",
act_layer=nn.GELU,
):
"""
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
bottleneck_channels (int): number of output channels for the 3x3
"bottleneck" conv layers.
norm (str or callable): normalization for all conv layers.
See :func:`layers.get_norm` for supported format.
act_layer (callable): activation for all conv layers.
"""
super().__init__(in_channels, out_channels, 1)
self.conv1 = Conv2d(in_channels, bottleneck_channels, 1, bias=False)
self.norm1 = get_norm(norm, bottleneck_channels)
self.act1 = act_layer()
self.conv2 = Conv2d(
bottleneck_channels,
bottleneck_channels,
3,
padding=1,
bias=False,
)
self.norm2 = get_norm(norm, bottleneck_channels)
self.act2 = act_layer()
self.conv3 = Conv2d(bottleneck_channels, out_channels, 1, bias=False)
self.norm3 = get_norm(norm, out_channels)
for layer in [self.conv1, self.conv2, self.conv3]:
weight_init.c2_msra_fill(layer)
for layer in [self.norm1, self.norm2]:
layer.weight.data.fill_(1.0)
layer.bias.data.zero_()
# zero init last norm layer.
self.norm3.weight.data.zero_()
self.norm3.bias.data.zero_()
def forward(self, x):
out = x
for layer in self.children():
out = layer(out)
out = x + out
return out
class Block(nn.Module):
"""Transformer blocks with support of window attention and residual propagation blocks"""
def __init__(
self,
dim,
num_heads,
mlp_ratio=4*2/3,
qkv_bias=True,
drop_path=0.0,
norm_layer=partial(nn.LayerNorm, eps=1e-6),
window_size=0,
use_residual_block=False,
rope=None,
xattn=True,
):
"""
Args:
dim (int): Number of input channels.
num_heads (int): Number of attention heads in each ViT block.
mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
qkv_bias (bool): If True, add a learnable bias to query, key, value.
drop_path (float): Stochastic depth rate.
norm_layer (nn.Module): Normalization layer.
act_layer (nn.Module): Activation layer.
use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
window_size (int): Window size for window attention blocks. If it equals 0, then not
use window attention.
use_residual_block (bool): If True, use a residual block after the MLP block.
input_size (int or None): Input resolution for calculating the relative positional
parameter size.
"""
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = Attention(
dim,
num_heads=num_heads,
qkv_bias=qkv_bias,
rope=rope,
xattn=xattn,
)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
self.mlp = SwiGLU(
in_features=dim,
hidden_features=int(dim * mlp_ratio),
subln=True,
norm_layer=norm_layer,
)
self.window_size = window_size
self.use_residual_block = use_residual_block
if use_residual_block:
# Use a residual block with bottleneck channel as dim // 2
self.residual = ResBottleneckBlock(
in_channels=dim,
out_channels=dim,
bottleneck_channels=dim // 2,
norm="LN",
)
def forward(self, x):
shortcut = x
x = self.norm1(x)
# Window partition
if self.window_size > 0:
H, W = x.shape[1], x.shape[2]
x, pad_hw = window_partition(x, self.window_size)
x = self.attn(x)
# Reverse window partition
if self.window_size > 0: | x = window_unpartition(x, self.window_size, pad_hw, (H, W)) | 4 | 2023-12-15 01:12:36+00:00 | 8k |
SHI-Labs/VCoder | vcoder_llava/eval/model_seg_loader.py | [
{
"identifier": "IMAGE_TOKEN_INDEX",
"path": "vcoder_llava/constants.py",
"snippet": "IMAGE_TOKEN_INDEX = -200"
},
{
"identifier": "DEFAULT_IMAGE_TOKEN",
"path": "vcoder_llava/constants.py",
"snippet": "DEFAULT_IMAGE_TOKEN = \"<image>\""
},
{
"identifier": "SEG_TOKEN_INDEX",
... | import argparse
import torch
import os
import json
import shortuuid
import random
import glob
import math
from tqdm import tqdm
from vcoder_llava.constants import (
IMAGE_TOKEN_INDEX, DEFAULT_IMAGE_TOKEN,
SEG_TOKEN_INDEX, DEFAULT_SEG_TOKEN,
)
from vcoder_llava.vcoder_conversation import conv_templates, SeparatorStyle
from vcoder_llava.model.builder import load_pretrained_model
from vcoder_llava.utils import disable_torch_init
from vcoder_llava.mm_utils import process_images, tokenizer_seg_token, tokenizer_image_token, get_model_name_from_path, KeywordsStoppingCriteria
from torch.utils.data import Dataset, DataLoader
from vcoder_llava.questions import QUESTIONS
from PIL import Image | 4,770 |
def split_list(lst, n):
"""Split a list into n (roughly) equal-sized chunks"""
chunk_size = math.ceil(len(lst) / n) # integer division
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
def get_chunk(lst, n, k):
chunks = split_list(lst, n)
return chunks[k]
# Custom dataset class
class CustomDataset(Dataset):
def __init__(self, questions, args, seg_image_folder, tokenizer, image_processor, seg_image_processor, model_config):
self.questions = questions
self.image_folder = args.image_folder
self.seg_image_folder = seg_image_folder
self.images = glob.glob(os.path.join(args.image_folder, '*.jpg'))
self.images = get_chunk(self.images, args.num_chunks, args.chunk_idx)
if seg_image_folder is not None:
self.seg_images = glob.glob(os.path.join(seg_image_folder, '*.jpg'))
self.seg_images = get_chunk(self.seg_images, args.num_chunks, args.chunk_idx)
assert len(self.images) == len(self.seg_images), f"Number of images ({len(self.images)}) and seg images ({len(self.seg_images)}) must be the same"
else:
self.seg_images = None
self.tokenizer = tokenizer
self.image_processor = image_processor
self.seg_image_processor = seg_image_processor
self.model_config = model_config
def __getitem__(self, index):
image_file = self.images[index]
if self.seg_images is not None:
seg_image_file = self.seg_images[index]
else:
seg_image_file = None
ques = random.choice(self.questions)
qs = DEFAULT_IMAGE_TOKEN + '\n' + ques
image = Image.open(os.path.join(image_file)).convert('RGB')
image_tensor = process_images([image], self.image_processor, self.model_config)[0]
if seg_image_file is not None:
seg_image = Image.open(os.path.join(seg_image_file)).convert('RGB')
seg_image_tensor = process_images([seg_image], self.seg_image_processor, self.model_config)[0]
qs = DEFAULT_SEG_TOKEN + '\n' + qs
else:
seg_image_tensor = image_tensor
qs = qs + " Return the answer in the paragraph format: 'The objects present in the image are: ...' and then list the objects with their count in word format (if greater than 1) in front of them, like 'two people'."
conv = conv_templates[args.conv_mode].copy()
conv.append_message(conv.roles[0], qs)
conv.append_message(conv.roles[1], None)
prompt = conv.get_prompt()
if seg_image_file is None:
input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt')
else:
input_ids = tokenizer_seg_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, SEG_TOKEN_INDEX, return_tensors='pt')
return input_ids, image_tensor, seg_image_tensor, image_file.split("/")[-1], ques
def __len__(self):
return len(self.images)
# DataLoader
def create_data_loader(questions, args, seg_image_folder, tokenizer, image_processor, seg_image_processor, model_config, batch_size=1, num_workers=4):
assert batch_size == 1, "batch_size must be 1"
dataset = CustomDataset(questions, args, seg_image_folder, tokenizer, image_processor, seg_image_processor, model_config)
data_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False)
return data_loader
def eval_model(args, task):
# Model
disable_torch_init()
model_path = os.path.expanduser(args.model_path)
model_name = get_model_name_from_path(model_path)
tokenizer, model, image_processor, seg_image_processor, _, context_len = load_pretrained_model(model_path, args.model_base, model_name)
questions = QUESTIONS[task]
answers_file = os.path.expanduser(args.output_file)
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
answers_file = answers_file + f'_{task}_{args.num_chunks}_{args.chunk_idx}.txt'
if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode:
args.conv_mode = args.conv_mode + '_mmtag'
print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.')
if not args.use_seg:
seg_image_folder = None
else:
seg_image_folder = os.path.join(args.seg_image_folder, f'{task}_inference')
data_loader = create_data_loader(questions, args, seg_image_folder, tokenizer, image_processor, seg_image_processor, model.config)
for input_ids, image_tensor, seg_image_tensor, image_file, ques in tqdm(data_loader, total=len(data_loader), desc=f'Generating {task} answers...'):
|
def split_list(lst, n):
"""Split a list into n (roughly) equal-sized chunks"""
chunk_size = math.ceil(len(lst) / n) # integer division
return [lst[i:i+chunk_size] for i in range(0, len(lst), chunk_size)]
def get_chunk(lst, n, k):
chunks = split_list(lst, n)
return chunks[k]
# Custom dataset class
class CustomDataset(Dataset):
def __init__(self, questions, args, seg_image_folder, tokenizer, image_processor, seg_image_processor, model_config):
self.questions = questions
self.image_folder = args.image_folder
self.seg_image_folder = seg_image_folder
self.images = glob.glob(os.path.join(args.image_folder, '*.jpg'))
self.images = get_chunk(self.images, args.num_chunks, args.chunk_idx)
if seg_image_folder is not None:
self.seg_images = glob.glob(os.path.join(seg_image_folder, '*.jpg'))
self.seg_images = get_chunk(self.seg_images, args.num_chunks, args.chunk_idx)
assert len(self.images) == len(self.seg_images), f"Number of images ({len(self.images)}) and seg images ({len(self.seg_images)}) must be the same"
else:
self.seg_images = None
self.tokenizer = tokenizer
self.image_processor = image_processor
self.seg_image_processor = seg_image_processor
self.model_config = model_config
def __getitem__(self, index):
image_file = self.images[index]
if self.seg_images is not None:
seg_image_file = self.seg_images[index]
else:
seg_image_file = None
ques = random.choice(self.questions)
qs = DEFAULT_IMAGE_TOKEN + '\n' + ques
image = Image.open(os.path.join(image_file)).convert('RGB')
image_tensor = process_images([image], self.image_processor, self.model_config)[0]
if seg_image_file is not None:
seg_image = Image.open(os.path.join(seg_image_file)).convert('RGB')
seg_image_tensor = process_images([seg_image], self.seg_image_processor, self.model_config)[0]
qs = DEFAULT_SEG_TOKEN + '\n' + qs
else:
seg_image_tensor = image_tensor
qs = qs + " Return the answer in the paragraph format: 'The objects present in the image are: ...' and then list the objects with their count in word format (if greater than 1) in front of them, like 'two people'."
conv = conv_templates[args.conv_mode].copy()
conv.append_message(conv.roles[0], qs)
conv.append_message(conv.roles[1], None)
prompt = conv.get_prompt()
if seg_image_file is None:
input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt')
else:
input_ids = tokenizer_seg_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, SEG_TOKEN_INDEX, return_tensors='pt')
return input_ids, image_tensor, seg_image_tensor, image_file.split("/")[-1], ques
def __len__(self):
return len(self.images)
# DataLoader
def create_data_loader(questions, args, seg_image_folder, tokenizer, image_processor, seg_image_processor, model_config, batch_size=1, num_workers=4):
assert batch_size == 1, "batch_size must be 1"
dataset = CustomDataset(questions, args, seg_image_folder, tokenizer, image_processor, seg_image_processor, model_config)
data_loader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False)
return data_loader
def eval_model(args, task):
# Model
disable_torch_init()
model_path = os.path.expanduser(args.model_path)
model_name = get_model_name_from_path(model_path)
tokenizer, model, image_processor, seg_image_processor, _, context_len = load_pretrained_model(model_path, args.model_base, model_name)
questions = QUESTIONS[task]
answers_file = os.path.expanduser(args.output_file)
os.makedirs(os.path.dirname(answers_file), exist_ok=True)
answers_file = answers_file + f'_{task}_{args.num_chunks}_{args.chunk_idx}.txt'
if 'plain' in model_name and 'finetune' not in model_name.lower() and 'mmtag' not in args.conv_mode:
args.conv_mode = args.conv_mode + '_mmtag'
print(f'It seems that this is a plain model, but it is not using a mmtag prompt, auto switching to {args.conv_mode}.')
if not args.use_seg:
seg_image_folder = None
else:
seg_image_folder = os.path.join(args.seg_image_folder, f'{task}_inference')
data_loader = create_data_loader(questions, args, seg_image_folder, tokenizer, image_processor, seg_image_processor, model.config)
for input_ids, image_tensor, seg_image_tensor, image_file, ques in tqdm(data_loader, total=len(data_loader), desc=f'Generating {task} answers...'):
| stop_str = conv_templates[args.conv_mode].sep if conv_templates[args.conv_mode].sep_style != SeparatorStyle.TWO else conv_templates[args.conv_mode].sep2 | 4 | 2023-12-17 07:46:27+00:00 | 8k |
OSU-NLP-Group/SeeAct | src/data_utils/prompts.py | [
{
"identifier": "data_format_input_multichoice",
"path": "src/data_utils/format_prompt_utils.py",
"snippet": "def data_format_input_multichoice(\n sample, candidate_ids, gt=-1, previous_k=5, keep_html_brackets=False\n):\n # Parse html into a dom tree\n dom_tree = lxml.etree.fromstring(sampl... | from .format_prompt_utils import data_format_input_multichoice, \
format_options, generate_option_name, generate_new_referring_prompt, generate_new_query_prompt | 4,876 |
exp3_prompt_dict = {
"system_prompt": sys_prompt,
"question_description": question_description_new_exp3,
"referring_description": f"""""",
"element_format": """(Final Answer)
Finally, conclude your answer using the format below. Ensure your answer is strictly adhering to the format provided below. Please do not leave any explanation in your answers of the final standardized format part, and this final part should be clear and certain. The element, element type, element text, action and value should be in five separate lines.
Format:
ELEMENT: Please describe which element you need to operate with. Describe it as detailed as possible, including what it is and where it is.
ELEMENT TYPE: Please specify its type from these options: BUTTON, TEXTBOX, SELECTBOX, or LINK.
ELEMENT TEXT: Please provide the exact text displayed on the element. Do not invent or modify the text; reproduce it as-is from the screenshot.""",
"action_format": f"{action_format}",
"value_format": f"{value_format}"
}
##### SeeAct Online Prompts
seeact_online_sys_prompt = '''Imagine that you are imitating humans doing web navigation for a task step by step. At each stage, you can see the webpage like humans by a screenshot and know the previous actions before the current step decided by yourself through recorded history. You need to decide on the first following action to take. You can click on an element with the mouse, select an option, type text or press Enter with the keyboard. (For your understanding, they are like the click(), select_option() type() and keyboard.press('Enter') functions in playwright respectively) One next step means one operation within the four. Unlike humans, for typing (e.g., in text areas, text boxes) and selecting (e.g., from dropdown menus or <select> elements), you should try directly typing the input or selecting the choice, bypassing the need for an initial click. You should not attempt to create accounts, log in or do the final submission. Terminate when you deem the task complete or if it requires potentially harmful actions.'''
seeact_online_question_description_new_exp4 = '''The screenshot below shows the webpage you see. Follow the following guidance to think step by step before outlining the next action step at the current stage:
(Current Webpage Identification)
Firstly, think about what the current webpage is.
(Previous Action Analysis)
Secondly, combined with the screenshot, analyze each step of the previous action history and their intention one by one. Particularly, pay more attention to the last step, which may be more related to what you should do now as the next step. Specifically, if the last action involved a TYPE, always evaluate whether it necessitates a confirmation step, because typically a single TYPE action does not make effect. (often, simply pressing 'Enter', assuming the default element involved in the last action, unless other clear elements are present for operation).
(Screenshot Details Analysis)
Closely examine the screenshot to check the status of every part of the webpage to understand what you can operate with and what has been set or completed. You should closely examine the screenshot details to see what steps have been completed by previous actions even though you are given the textual previous actions. Because the textual history may not clearly and sufficiently record some effects of previous actions, you should closely evaluate the status of every part of the webpage to understand what you have done.
(Next Action Based on Webpage and Analysis)
Then, based on your analysis, in conjunction with human web browsing habits and the logic of web design, decide on the following action. And clearly outline which element in the webpage users will operate with as the first next target element, its detailed location, and the corresponding operation.
To be successful, it is important to follow the following rules:
1. You should only issue a valid action given the current observation.
2. You should only issue one action at a time
3. For handling the select dropdown elements on the webpage, it's not necessary for you to provide completely accurate options right now. The full list of options for these elements will be supplied later.'''
seeact_online_action_format = "ACTION: Choose an action from {CLICK, SELECT, TYPE, PRESS ENTER, TERMINATE, NONE}."
seeact_online_value_format = "VALUE: Provide additional input based on ACTION.\n\nThe VALUE means:\nIf ACTION == TYPE, specify the " \
"text to be typed.\nIf ACTION == SELECT, indicate the option to be chosen. Revise the selection value to align with the available options within the element.\nIf ACTION == CLICK, PRESS ENTER, TERMINATE or NONE, " \
"write \"None\"."
seeact_choice_prompt_dict = {
"system_prompt": seeact_online_sys_prompt,
"question_description": seeact_online_question_description_new_exp4,
"referring_description": f"""(Reiteration)
First, reiterate your next target element, its detailed location, and the corresponding operation.
(Multichoice Question)
Below is a multi-choice question, where the choices are elements in the webpage. All elements are arranged in the order based on their height on the webpage, from top to bottom (and from left to right). This arrangement can be used to locate them. From the screenshot, find out where and what each one is on the webpage, taking into account both their text content and HTML details. Then, determine whether one matches your target element. Please examine the choices one by one. Choose the matching one. If multiple options match your answer, choose the most likely one by re-examining the screenshot, the choices, and your further reasoning.""",
"element_format": """(Final Answer)
Finally, conclude your answer using the format below. Ensure your answer is strictly adhering to the format provided below. Please do not leave any explanation in your answers of the final standardized format part, and this final part should be clear and certain. The element choice, action, and value should be in three separate lines.
Format:
ELEMENT: The uppercase letter of your choice. (No need for PRESS ENTER)""",
"action_format": f"{seeact_online_action_format}",
"value_format": f"{seeact_online_value_format}"
}
def generate_prompt(experiment_split, task=None, previous=None, choices=None):
assert experiment_split != None, "Please specify the experiment split."
assert task != None, "Please input the task."
assert previous != None, "Please input the previous actions."
prompt_list = []
system_prompt_input = None
question_description_input = None
referring_input = None
element_format_input = None
action_format_input = None
value_format_input = None
if experiment_split in ["text","text_choice","4api"]:
system_prompt_input = exp4_prompt_dict["system_prompt"]
question_description_input = exp4_prompt_dict["question_description"]
referring_input = exp4_prompt_dict["referring_description"]
element_format_input = exp4_prompt_dict["element_format"]
action_format_input = exp4_prompt_dict["action_format"]
value_format_input = exp4_prompt_dict["value_format"]
prompt_list.extend(
generate_new_query_prompt(system_prompt=system_prompt_input, task=task, previous_actions=previous,
question_description=question_description_input))
prompt_list.append(
| # -*- coding: utf-8 -*-
# Copyright (c) 2024 OSU Natural Language Processing Group
#
# Licensed under the OpenRAIL-S License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.licenses.ai/ai-pubs-open-rails-vz1
#
# 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.
sys_prompt = '''Imagine that you are imitating humans doing web navigation for a task step by step. At each stage, you can see the webpage like humans by a screenshot and know the previous actions before the current step decided by yourself through recorded history. You need to decide on the first following action to take. You can click an element with the mouse, select an option, or type text with the keyboard. (For your understanding, they are like the click(), select_option() and type() functions in playwright respectively) One next step means one operation within the three.'''
action_format = "ACTION: Choose an action from {CLICK, TYPE, SELECT}."
value_format = "VALUE: Provide additional input based on ACTION.\n\nThe VALUE means:\nIf ACTION == TYPE, specify the " \
"text to be typed.\nIf ACTION == SELECT, specify the option to be chosen.\nIf ACTION == CLICK, " \
"write \"None\"."
question_description_new_exp4 = '''The screenshot below shows the webpage you see. Follow the following guidance to think step by step before outlining the next action step at the current stage:
(Current Webpage Identification)
Firstly, think about what the current webpage is.
(Previous Action Analysis)
Secondly, combined with the screenshot, analyze each step of the previous action history and their intention one by one. Particularly, pay more attention to the last step, which may be more related to what you should do now as the next step.
(Screenshot Details Analysis)
Closely examine the screenshot to check the status of every part of the webpage to understand what you can operate with and what has been set or completed. You should closely examine the screenshot details to see what steps have been completed by previous actions even though you are given the textual previous actions. Because the textual history may not clearly and sufficiently record some effects of previous actions, you should closely evaluate the status of every part of the webpage to understand what you have done.
(Next Action Based on Webpage and Analysis)
Then, based on your analysis, in conjunction with human web browsing habits and the logic of web design, decide on the following action. And clearly outline which element in the webpage users will operate with as the first next target element, its detailed location, and the corresponding operation.
To be successful, it is important to follow the following rules:
1. You should only issue a valid action given the current observation.
2. You should only issue one action at a time'''
question_description_new_exp2 = '''The screenshot below shows the webpage you see. In the screenshot, some red bounding boxes and white-on-black uppercase letters at the bottom left corner of the bounding boxes have been manually added. You should ignore them for now. Follow the following guidance to think step by step before outlining the next action step at the current stage:
(Current Webpage Identification)
Firstly, think about what the current webpage is.
(Previous Action Analysis)
Secondly, combined with the screenshot, analyze each step of the previous action history and their intention one by one. Particularly, pay more attention to the last step, which may be more related to what you should do now as the next step.
(Screenshot Details Analysis)
Closely examine the screenshot to check the status of every part of the webpage to understand what you can operate with and what has been set or completed. You should closely examine the screenshot details to see what steps have been completed by previous actions even though you are given the textual previous actions. Because the textual history may not clearly and sufficiently record some effects of previous actions, you should closely evaluate the status of every part of the webpage to understand what you have done.
(Next Action Based on Webpage and Analysis)
Then, based on your analysis, in conjunction with human web browsing habits and the logic of web design, decide on the following action. And clearly outline which element in the webpage users will operate with as the first next target element, its detailed location, and the corresponding operation.
To be successful, it is important to follow the following rules:
1. You should only issue a valid action given the current observation.
2. You should only issue one action at a time.'''
question_description_new_exp3 = '''The screenshot below shows the webpage you see. Follow the following guidance to think step by step before outlining the next action step at the current stage:
(Current Webpage Identification)
Firstly, think about what the current webpage is.
(Previous Action Analysis)
Secondly, combined with the screenshot, analyze each step of the previous action history and their intention one by one. Particularly, pay more attention to the last step, which may be more related to what you should do now as the next step.
(Screenshot Details Analysis)
Closely examine the screenshot to check the status of every part of the webpage to understand what you can operate with and what has been set or completed. You should closely examine the screenshot details to see what steps have been completed by previous actions even though you are given the textual previous actions. Because the textual history may not clearly and sufficiently record some effects of previous actions, you should closely evaluate the status of every part of the webpage to understand what you have done.
(Next Action Based on Webpage and Analysis)
Then, based on your analysis, in conjunction with human web browsing habits and the logic of web design, decide on the following action. And clearly outline which element in the webpage users will operate with as the first next target element, its detailed location, and the corresponding operation. Please also closely examine the screenshot to adequately describe its position relative to nearby elements and its textual or visual content (if it has). If you find multiple elements similar to your target element, use a more precise description to ensure people can distinguish your target element from them through your answer.
To be successful, it is important to follow the following rules:
1. You should only issue a valid action given the current observation.
2. You should only issue one action at a time.'''
exp4_prompt_dict = {
"system_prompt": sys_prompt,
"question_description": question_description_new_exp4,
"referring_description": f"""(Reiteration)
First, reiterate your next target element, its detailed location, and the corresponding operation.
(Multichoice Question)
Below is a multi-choice question, where the choices are elements in the webpage. From the screenshot, find out where and what each one is on the webpage. Then, determine whether one matches your target element. Please examine the choices one by one. Choose the matching one. If multiple options match your answer, choose the most likely one by re-examining the screenshot, the choices, and your further reasoning.""",
"element_format": """(Final Answer)
Finally, conclude your answer using the format below. Ensure your answer is strictly adhering to the format provided below. Please do not leave any explanation in your answers of the final standardized format part, and this final part should be clear and certain. The element choice, action, and value should be in three separate lines.
Format:
ELEMENT: The uppercase letter of your choice.""",
"action_format": f"{action_format}",
"value_format": f"{value_format}"
}
exp2_prompt_dict = {
"system_prompt": sys_prompt,
"question_description": question_description_new_exp2,
"referring_description": f"""(Reiteration)
First, reiterate your next target element, its detailed location, and the corresponding operation.
(Verification with the Screenshot)
Then, please closely re-examine the screenshot to find whether your target element is marked by a red bounding box and has a white uppercase letter on a black background at the bottom left corner of the bounding box, which is positioned closely next to the bounding box. If yes, use that letter for your final answer. If not, please do not make them up. If it is not marked, please output "NA" as your target element in the following final answer part.""",
"element_format": """(Final Answer)
Finally, conclude your answer using the format below. Ensure your answer is strictly adhering to the format provided below. Please do not leave any explanation in your answers of the final standardized format part, and this final part should be clear and certain. The element choice, action, and value should be in three separate lines.
Format:
ELEMENT: The uppercase letter of your choice.""",
"action_format": f"{action_format}",
"value_format": f"{value_format}"
}
exp3_prompt_dict = {
"system_prompt": sys_prompt,
"question_description": question_description_new_exp3,
"referring_description": f"""""",
"element_format": """(Final Answer)
Finally, conclude your answer using the format below. Ensure your answer is strictly adhering to the format provided below. Please do not leave any explanation in your answers of the final standardized format part, and this final part should be clear and certain. The element, element type, element text, action and value should be in five separate lines.
Format:
ELEMENT: Please describe which element you need to operate with. Describe it as detailed as possible, including what it is and where it is.
ELEMENT TYPE: Please specify its type from these options: BUTTON, TEXTBOX, SELECTBOX, or LINK.
ELEMENT TEXT: Please provide the exact text displayed on the element. Do not invent or modify the text; reproduce it as-is from the screenshot.""",
"action_format": f"{action_format}",
"value_format": f"{value_format}"
}
##### SeeAct Online Prompts
seeact_online_sys_prompt = '''Imagine that you are imitating humans doing web navigation for a task step by step. At each stage, you can see the webpage like humans by a screenshot and know the previous actions before the current step decided by yourself through recorded history. You need to decide on the first following action to take. You can click on an element with the mouse, select an option, type text or press Enter with the keyboard. (For your understanding, they are like the click(), select_option() type() and keyboard.press('Enter') functions in playwright respectively) One next step means one operation within the four. Unlike humans, for typing (e.g., in text areas, text boxes) and selecting (e.g., from dropdown menus or <select> elements), you should try directly typing the input or selecting the choice, bypassing the need for an initial click. You should not attempt to create accounts, log in or do the final submission. Terminate when you deem the task complete or if it requires potentially harmful actions.'''
seeact_online_question_description_new_exp4 = '''The screenshot below shows the webpage you see. Follow the following guidance to think step by step before outlining the next action step at the current stage:
(Current Webpage Identification)
Firstly, think about what the current webpage is.
(Previous Action Analysis)
Secondly, combined with the screenshot, analyze each step of the previous action history and their intention one by one. Particularly, pay more attention to the last step, which may be more related to what you should do now as the next step. Specifically, if the last action involved a TYPE, always evaluate whether it necessitates a confirmation step, because typically a single TYPE action does not make effect. (often, simply pressing 'Enter', assuming the default element involved in the last action, unless other clear elements are present for operation).
(Screenshot Details Analysis)
Closely examine the screenshot to check the status of every part of the webpage to understand what you can operate with and what has been set or completed. You should closely examine the screenshot details to see what steps have been completed by previous actions even though you are given the textual previous actions. Because the textual history may not clearly and sufficiently record some effects of previous actions, you should closely evaluate the status of every part of the webpage to understand what you have done.
(Next Action Based on Webpage and Analysis)
Then, based on your analysis, in conjunction with human web browsing habits and the logic of web design, decide on the following action. And clearly outline which element in the webpage users will operate with as the first next target element, its detailed location, and the corresponding operation.
To be successful, it is important to follow the following rules:
1. You should only issue a valid action given the current observation.
2. You should only issue one action at a time
3. For handling the select dropdown elements on the webpage, it's not necessary for you to provide completely accurate options right now. The full list of options for these elements will be supplied later.'''
seeact_online_action_format = "ACTION: Choose an action from {CLICK, SELECT, TYPE, PRESS ENTER, TERMINATE, NONE}."
seeact_online_value_format = "VALUE: Provide additional input based on ACTION.\n\nThe VALUE means:\nIf ACTION == TYPE, specify the " \
"text to be typed.\nIf ACTION == SELECT, indicate the option to be chosen. Revise the selection value to align with the available options within the element.\nIf ACTION == CLICK, PRESS ENTER, TERMINATE or NONE, " \
"write \"None\"."
seeact_choice_prompt_dict = {
"system_prompt": seeact_online_sys_prompt,
"question_description": seeact_online_question_description_new_exp4,
"referring_description": f"""(Reiteration)
First, reiterate your next target element, its detailed location, and the corresponding operation.
(Multichoice Question)
Below is a multi-choice question, where the choices are elements in the webpage. All elements are arranged in the order based on their height on the webpage, from top to bottom (and from left to right). This arrangement can be used to locate them. From the screenshot, find out where and what each one is on the webpage, taking into account both their text content and HTML details. Then, determine whether one matches your target element. Please examine the choices one by one. Choose the matching one. If multiple options match your answer, choose the most likely one by re-examining the screenshot, the choices, and your further reasoning.""",
"element_format": """(Final Answer)
Finally, conclude your answer using the format below. Ensure your answer is strictly adhering to the format provided below. Please do not leave any explanation in your answers of the final standardized format part, and this final part should be clear and certain. The element choice, action, and value should be in three separate lines.
Format:
ELEMENT: The uppercase letter of your choice. (No need for PRESS ENTER)""",
"action_format": f"{seeact_online_action_format}",
"value_format": f"{seeact_online_value_format}"
}
def generate_prompt(experiment_split, task=None, previous=None, choices=None):
assert experiment_split != None, "Please specify the experiment split."
assert task != None, "Please input the task."
assert previous != None, "Please input the previous actions."
prompt_list = []
system_prompt_input = None
question_description_input = None
referring_input = None
element_format_input = None
action_format_input = None
value_format_input = None
if experiment_split in ["text","text_choice","4api"]:
system_prompt_input = exp4_prompt_dict["system_prompt"]
question_description_input = exp4_prompt_dict["question_description"]
referring_input = exp4_prompt_dict["referring_description"]
element_format_input = exp4_prompt_dict["element_format"]
action_format_input = exp4_prompt_dict["action_format"]
value_format_input = exp4_prompt_dict["value_format"]
prompt_list.extend(
generate_new_query_prompt(system_prompt=system_prompt_input, task=task, previous_actions=previous,
question_description=question_description_input))
prompt_list.append( | generate_new_referring_prompt(referring_description=referring_input, element_format=element_format_input, | 3 | 2023-12-21 18:22:11+00:00 | 8k |
DeepWok/mase | machop/chop/models/manual/opt_quantized/modeling_opt.py | [
{
"identifier": "get_quantized_cls",
"path": "machop/chop/models/manual/quant_utils.py",
"snippet": "def get_quantized_cls(mase_op: str, quant_config: dict) -> type:\n quant_arith = quant_config[\"name\"]\n return quantized_module_map[f\"{mase_op}_{quant_arith}\"]"
},
{
"identifier": "get_... | import random
import torch
import torch.utils.checkpoint
from typing import List, Optional, Tuple, Union
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers.activations import ACT2FN
from transformers.modeling_outputs import (
BaseModelOutputWithPast,
CausalLMOutputWithPast,
QuestionAnsweringModelOutput,
SequenceClassifierOutputWithPast,
)
from transformers.modeling_utils import PreTrainedModel
from transformers.utils import (
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from ..quant_utils import get_quantized_cls, get_quantized_func
from .configuration_opt import OPTQuantizedConfig | 3,926 | # and adjust num_embeddings appropriately. Other models don't have this hack
self.offset = 2
super().__init__(num_embeddings + self.offset, embedding_dim)
def forward(
self, attention_mask: torch.LongTensor, past_key_values_length: int = 0
):
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
attention_mask = attention_mask.long()
# create positions depending on attention_mask
positions = (
torch.cumsum(attention_mask, dim=1).type_as(attention_mask) * attention_mask
).long() - 1
# cut positions if `past_key_values_length` is > 0
positions = positions[:, past_key_values_length:]
return super().forward(positions + self.offset)
class OPTQauntizedAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
quant_config: dict = None,
):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
if (self.head_dim * num_heads) != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
f" and `num_heads`: {num_heads})."
)
self.scaling = self.head_dim**-0.5
self.is_decoder = is_decoder
# fmt:off
self.k_proj = get_quantized_cls("linear", quant_config["k_proj"])(embed_dim, embed_dim, bias=bias, config=quant_config["k_proj"])
self.q_proj = get_quantized_cls("linear", quant_config["q_proj"])(embed_dim, embed_dim, bias=bias, config=quant_config["q_proj"])
self.v_proj = get_quantized_cls("linear", quant_config["v_proj"])(embed_dim, embed_dim, bias=bias, config=quant_config["v_proj"])
self.out_proj = get_quantized_cls("linear", quant_config["out_proj"])(embed_dim, embed_dim, bias=bias, config=quant_config["out_proj"])
self.quant_config = quant_config
# fmt:on
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
return (
tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
.transpose(1, 2)
.contiguous()
)
def forward(
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
past_key_value: Optional[Tuple[torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None,
layer_head_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
is_cross_attention = key_value_states is not None
bsz, tgt_len, _ = hidden_states.size()
# get query proj
query_states = self.q_proj(hidden_states) * self.scaling
# get key, value proj
if is_cross_attention and past_key_value is not None:
# reuse k,v, cross_attentions
key_states = past_key_value[0]
value_states = past_key_value[1]
elif is_cross_attention:
# cross_attentions
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
elif past_key_value is not None:
# reuse k, v, self_attention
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
key_states = torch.cat([past_key_value[0], key_states], dim=2)
value_states = torch.cat([past_key_value[1], value_states], dim=2)
else:
# self_attention
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
if self.is_decoder:
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
# Further calls to cross_attention layer can then reuse all cross-attention
# key/value_states (first "if" case)
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
# all previous decoder key/value_states. Further calls to uni-directional self-attention
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
# if encoder bi-directional self-attention `past_key_value` is always `None`
past_key_value = (key_states, value_states)
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
key_states = key_states.view(*proj_shape)
value_states = value_states.view(*proj_shape)
src_len = key_states.size(1)
# *: bmm
# attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
# fmt:off
| # coding=utf-8
# Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" PyTorch OPT model."""
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "facebook/opt-350m"
_CONFIG_FOR_DOC = "OPTConfig"
# Base model docstring
_EXPECTED_OUTPUT_SHAPE = [1, 8, 1024]
# SequenceClassification docstring
_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "ArthurZ/opt-350m-dummy-sc"
_SEQ_CLASS_EXPECTED_LOSS = 1.71
_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_0'"
OPT_PRETRAINED_MODEL_ARCHIVE_LIST = [
"facebook/opt-125m",
"facebook/opt-350m",
"facebook/opt-1.3b",
"facebook/opt-2.7b",
"facebook/opt-6.7b",
"facebook/opt-13b",
"facebook/opt-30b",
# See all OPT models at https://huggingface.co/models?filter=opt
]
# Copied from transformers.models.bart.modeling_bart._make_causal_mask
def _make_causal_mask(
input_ids_shape: torch.Size,
dtype: torch.dtype,
device: torch.device,
past_key_values_length: int = 0,
):
"""
Make causal mask used for bi-directional self-attention.
"""
bsz, tgt_len = input_ids_shape
mask = torch.full(
(tgt_len, tgt_len),
torch.tensor(torch.finfo(dtype).min, device=device),
device=device,
)
mask_cond = torch.arange(mask.size(-1), device=device)
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
mask = mask.to(dtype)
if past_key_values_length > 0:
mask = torch.cat(
[
torch.zeros(
tgt_len, past_key_values_length, dtype=dtype, device=device
),
mask,
],
dim=-1,
)
return mask[None, None, :, :].expand(
bsz, 1, tgt_len, tgt_len + past_key_values_length
)
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
"""
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
"""
bsz, src_len = mask.size()
tgt_len = tgt_len if tgt_len is not None else src_len
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
inverted_mask = 1.0 - expanded_mask
return inverted_mask.masked_fill(
inverted_mask.to(torch.bool), torch.finfo(dtype).min
)
class OPTLearnedPositionalEmbedding(nn.Embedding):
"""
This module learns positional embeddings up to a fixed maximum size.
"""
def __init__(self, num_embeddings: int, embedding_dim: int):
# OPT is set up so that if padding_idx is specified then offset the embedding ids by 2
# and adjust num_embeddings appropriately. Other models don't have this hack
self.offset = 2
super().__init__(num_embeddings + self.offset, embedding_dim)
def forward(
self, attention_mask: torch.LongTensor, past_key_values_length: int = 0
):
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
attention_mask = attention_mask.long()
# create positions depending on attention_mask
positions = (
torch.cumsum(attention_mask, dim=1).type_as(attention_mask) * attention_mask
).long() - 1
# cut positions if `past_key_values_length` is > 0
positions = positions[:, past_key_values_length:]
return super().forward(positions + self.offset)
class OPTQauntizedAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
quant_config: dict = None,
):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
if (self.head_dim * num_heads) != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
f" and `num_heads`: {num_heads})."
)
self.scaling = self.head_dim**-0.5
self.is_decoder = is_decoder
# fmt:off
self.k_proj = get_quantized_cls("linear", quant_config["k_proj"])(embed_dim, embed_dim, bias=bias, config=quant_config["k_proj"])
self.q_proj = get_quantized_cls("linear", quant_config["q_proj"])(embed_dim, embed_dim, bias=bias, config=quant_config["q_proj"])
self.v_proj = get_quantized_cls("linear", quant_config["v_proj"])(embed_dim, embed_dim, bias=bias, config=quant_config["v_proj"])
self.out_proj = get_quantized_cls("linear", quant_config["out_proj"])(embed_dim, embed_dim, bias=bias, config=quant_config["out_proj"])
self.quant_config = quant_config
# fmt:on
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
return (
tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
.transpose(1, 2)
.contiguous()
)
def forward(
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
past_key_value: Optional[Tuple[torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None,
layer_head_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
is_cross_attention = key_value_states is not None
bsz, tgt_len, _ = hidden_states.size()
# get query proj
query_states = self.q_proj(hidden_states) * self.scaling
# get key, value proj
if is_cross_attention and past_key_value is not None:
# reuse k,v, cross_attentions
key_states = past_key_value[0]
value_states = past_key_value[1]
elif is_cross_attention:
# cross_attentions
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
elif past_key_value is not None:
# reuse k, v, self_attention
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
key_states = torch.cat([past_key_value[0], key_states], dim=2)
value_states = torch.cat([past_key_value[1], value_states], dim=2)
else:
# self_attention
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
if self.is_decoder:
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
# Further calls to cross_attention layer can then reuse all cross-attention
# key/value_states (first "if" case)
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
# all previous decoder key/value_states. Further calls to uni-directional self-attention
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
# if encoder bi-directional self-attention `past_key_value` is always `None`
past_key_value = (key_states, value_states)
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
key_states = key_states.view(*proj_shape)
value_states = value_states.view(*proj_shape)
src_len = key_states.size(1)
# *: bmm
# attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
# fmt:off | attn_weights = get_quantized_func("bmm", self.quant_config["bmm_0"])(query_states, key_states.transpose(1, 2), config=self.quant_config["bmm_0"]) | 1 | 2023-12-18 12:50:53+00:00 | 8k |
byeongjun-park/HarmonyView | ldm/models/diffusion/sync_dreamer_attention.py | [
{
"identifier": "default",
"path": "ldm/modules/attention.py",
"snippet": "def exists(val):\ndef uniq(arr):\ndef default(val, d):\ndef max_neg_value(t):\ndef init_(tensor):\n def __init__(self, dim_in, dim_out):\n def forward(self, x):\n def __init__(self, dim_in, dim_out):\n def forward(sel... | import torch
import torch.nn as nn
from ldm.modules.attention import default, zero_module, checkpoint
from ldm.modules.diffusionmodules.openaimodel import UNetModel
from ldm.modules.diffusionmodules.util import timestep_embedding | 5,595 |
class DepthAttention(nn.Module):
def __init__(self, query_dim, context_dim, heads, dim_head, output_bias=True):
super().__init__()
inner_dim = dim_head * heads
context_dim = default(context_dim, query_dim)
self.scale = dim_head ** -0.5
self.heads = heads
self.dim_head = dim_head
self.to_q = nn.Conv2d(query_dim, inner_dim, 1, 1, bias=False)
self.to_k = nn.Conv3d(context_dim, inner_dim, 1, 1, bias=False)
self.to_v = nn.Conv3d(context_dim, inner_dim, 1, 1, bias=False)
if output_bias:
self.to_out = nn.Conv2d(inner_dim, query_dim, 1, 1)
else:
self.to_out = nn.Conv2d(inner_dim, query_dim, 1, 1, bias=False)
def forward(self, x, context):
"""
@param x: b,f0,h,w
@param context: b,f1,d,h,w
@return:
"""
hn, hd = self.heads, self.dim_head
b, _, h, w = x.shape
b, _, d, h, w = context.shape
q = self.to_q(x).reshape(b,hn,hd,h,w) # b,t,h,w
k = self.to_k(context).reshape(b,hn,hd,d,h,w) # b,t,d,h,w
v = self.to_v(context).reshape(b,hn,hd,d,h,w) # b,t,d,h,w
sim = torch.sum(q.unsqueeze(3) * k, 2) * self.scale # b,hn,d,h,w
attn = sim.softmax(dim=2)
# b,hn,hd,d,h,w * b,hn,1,d,h,w
out = torch.sum(v * attn.unsqueeze(2), 3) # b,hn,hd,h,w
out = out.reshape(b,hn*hd,h,w)
return self.to_out(out)
class DepthTransformer(nn.Module):
def __init__(self, dim, n_heads, d_head, context_dim=None, checkpoint=True):
super().__init__()
inner_dim = n_heads * d_head
self.proj_in = nn.Sequential(
nn.Conv2d(dim, inner_dim, 1, 1),
nn.GroupNorm(8, inner_dim),
nn.SiLU(True),
)
self.proj_context = nn.Sequential(
nn.Conv3d(context_dim, context_dim, 1, 1, bias=False), # no bias
nn.GroupNorm(8, context_dim),
nn.ReLU(True), # only relu, because we want input is 0, output is 0
)
self.depth_attn = DepthAttention(query_dim=inner_dim, heads=n_heads, dim_head=d_head, context_dim=context_dim, output_bias=False) # is a self-attention if not self.disable_self_attn
self.proj_out = nn.Sequential(
nn.GroupNorm(8, inner_dim),
nn.ReLU(True),
nn.Conv2d(inner_dim, inner_dim, 3, 1, 1, bias=False),
nn.GroupNorm(8, inner_dim),
nn.ReLU(True),
zero_module(nn.Conv2d(inner_dim, dim, 3, 1, 1, bias=False)),
)
self.checkpoint = checkpoint
def forward(self, x, context=None):
return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)
def _forward(self, x, context):
x_in = x
x = self.proj_in(x)
context = self.proj_context(context)
x = self.depth_attn(x, context)
x = self.proj_out(x) + x_in
return x
class DepthWiseAttention(UNetModel):
def __init__(self, volume_dims=(5,16,32,64), *args, **kwargs):
super().__init__(*args, **kwargs)
# num_heads = 4
model_channels = kwargs['model_channels']
channel_mult = kwargs['channel_mult']
d0,d1,d2,d3 = volume_dims
# 4
ch = model_channels*channel_mult[2]
self.middle_conditions = DepthTransformer(ch, 4, d3 // 2, context_dim=d3)
self.output_conditions=nn.ModuleList()
self.output_b2c = {3:0,4:1,5:2,6:3,7:4,8:5,9:6,10:7,11:8}
# 8
ch = model_channels*channel_mult[2]
self.output_conditions.append(DepthTransformer(ch, 4, d2 // 2, context_dim=d2)) # 0
self.output_conditions.append(DepthTransformer(ch, 4, d2 // 2, context_dim=d2)) # 1
# 16
self.output_conditions.append(DepthTransformer(ch, 4, d1 // 2, context_dim=d1)) # 2
ch = model_channels*channel_mult[1]
self.output_conditions.append(DepthTransformer(ch, 4, d1 // 2, context_dim=d1)) # 3
self.output_conditions.append(DepthTransformer(ch, 4, d1 // 2, context_dim=d1)) # 4
# 32
self.output_conditions.append(DepthTransformer(ch, 4, d0 // 2, context_dim=d0)) # 5
ch = model_channels*channel_mult[0]
self.output_conditions.append(DepthTransformer(ch, 4, d0 // 2, context_dim=d0)) # 6
self.output_conditions.append(DepthTransformer(ch, 4, d0 // 2, context_dim=d0)) # 7
self.output_conditions.append(DepthTransformer(ch, 4, d0 // 2, context_dim=d0)) # 8
def forward(self, x, timesteps=None, context=None, source_dict=None, **kwargs):
hs = []
|
class DepthAttention(nn.Module):
def __init__(self, query_dim, context_dim, heads, dim_head, output_bias=True):
super().__init__()
inner_dim = dim_head * heads
context_dim = default(context_dim, query_dim)
self.scale = dim_head ** -0.5
self.heads = heads
self.dim_head = dim_head
self.to_q = nn.Conv2d(query_dim, inner_dim, 1, 1, bias=False)
self.to_k = nn.Conv3d(context_dim, inner_dim, 1, 1, bias=False)
self.to_v = nn.Conv3d(context_dim, inner_dim, 1, 1, bias=False)
if output_bias:
self.to_out = nn.Conv2d(inner_dim, query_dim, 1, 1)
else:
self.to_out = nn.Conv2d(inner_dim, query_dim, 1, 1, bias=False)
def forward(self, x, context):
"""
@param x: b,f0,h,w
@param context: b,f1,d,h,w
@return:
"""
hn, hd = self.heads, self.dim_head
b, _, h, w = x.shape
b, _, d, h, w = context.shape
q = self.to_q(x).reshape(b,hn,hd,h,w) # b,t,h,w
k = self.to_k(context).reshape(b,hn,hd,d,h,w) # b,t,d,h,w
v = self.to_v(context).reshape(b,hn,hd,d,h,w) # b,t,d,h,w
sim = torch.sum(q.unsqueeze(3) * k, 2) * self.scale # b,hn,d,h,w
attn = sim.softmax(dim=2)
# b,hn,hd,d,h,w * b,hn,1,d,h,w
out = torch.sum(v * attn.unsqueeze(2), 3) # b,hn,hd,h,w
out = out.reshape(b,hn*hd,h,w)
return self.to_out(out)
class DepthTransformer(nn.Module):
def __init__(self, dim, n_heads, d_head, context_dim=None, checkpoint=True):
super().__init__()
inner_dim = n_heads * d_head
self.proj_in = nn.Sequential(
nn.Conv2d(dim, inner_dim, 1, 1),
nn.GroupNorm(8, inner_dim),
nn.SiLU(True),
)
self.proj_context = nn.Sequential(
nn.Conv3d(context_dim, context_dim, 1, 1, bias=False), # no bias
nn.GroupNorm(8, context_dim),
nn.ReLU(True), # only relu, because we want input is 0, output is 0
)
self.depth_attn = DepthAttention(query_dim=inner_dim, heads=n_heads, dim_head=d_head, context_dim=context_dim, output_bias=False) # is a self-attention if not self.disable_self_attn
self.proj_out = nn.Sequential(
nn.GroupNorm(8, inner_dim),
nn.ReLU(True),
nn.Conv2d(inner_dim, inner_dim, 3, 1, 1, bias=False),
nn.GroupNorm(8, inner_dim),
nn.ReLU(True),
zero_module(nn.Conv2d(inner_dim, dim, 3, 1, 1, bias=False)),
)
self.checkpoint = checkpoint
def forward(self, x, context=None):
return checkpoint(self._forward, (x, context), self.parameters(), self.checkpoint)
def _forward(self, x, context):
x_in = x
x = self.proj_in(x)
context = self.proj_context(context)
x = self.depth_attn(x, context)
x = self.proj_out(x) + x_in
return x
class DepthWiseAttention(UNetModel):
def __init__(self, volume_dims=(5,16,32,64), *args, **kwargs):
super().__init__(*args, **kwargs)
# num_heads = 4
model_channels = kwargs['model_channels']
channel_mult = kwargs['channel_mult']
d0,d1,d2,d3 = volume_dims
# 4
ch = model_channels*channel_mult[2]
self.middle_conditions = DepthTransformer(ch, 4, d3 // 2, context_dim=d3)
self.output_conditions=nn.ModuleList()
self.output_b2c = {3:0,4:1,5:2,6:3,7:4,8:5,9:6,10:7,11:8}
# 8
ch = model_channels*channel_mult[2]
self.output_conditions.append(DepthTransformer(ch, 4, d2 // 2, context_dim=d2)) # 0
self.output_conditions.append(DepthTransformer(ch, 4, d2 // 2, context_dim=d2)) # 1
# 16
self.output_conditions.append(DepthTransformer(ch, 4, d1 // 2, context_dim=d1)) # 2
ch = model_channels*channel_mult[1]
self.output_conditions.append(DepthTransformer(ch, 4, d1 // 2, context_dim=d1)) # 3
self.output_conditions.append(DepthTransformer(ch, 4, d1 // 2, context_dim=d1)) # 4
# 32
self.output_conditions.append(DepthTransformer(ch, 4, d0 // 2, context_dim=d0)) # 5
ch = model_channels*channel_mult[0]
self.output_conditions.append(DepthTransformer(ch, 4, d0 // 2, context_dim=d0)) # 6
self.output_conditions.append(DepthTransformer(ch, 4, d0 // 2, context_dim=d0)) # 7
self.output_conditions.append(DepthTransformer(ch, 4, d0 // 2, context_dim=d0)) # 8
def forward(self, x, timesteps=None, context=None, source_dict=None, **kwargs):
hs = [] | t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) | 2 | 2023-12-21 04:44:00+00:00 | 8k |
OPPOMKLab/u-LLaVA | models/ullava.py | [
{
"identifier": "registry",
"path": "utils/registry.py",
"snippet": "class Registry:\n def register_builder(cls, name):\n def wrap(builder_cls):\n def register_model(cls, name):\n def wrap(model_cls):\n def register_processor(cls, name):\n def wrap(processor_cls):\n def ... | import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import List
from utils.registry import registry
from models.segment_anything import build_sam_vit_h
from models.ullava_core import UllavaCoreConfig, UllavaCoreForCausalLM
from transformers import AutoModelForCausalLM, PreTrainedModel, PretrainedConfig, AutoConfig | 5,003 | """
u-LLaVA with segmentation module
SAM patch is Adapted form: https://github.com/dvlab-research/LISA/blob/main/model/LISA.py
"""
def dice_loss(
inputs: torch.Tensor,
targets: torch.Tensor,
num_masks: float,
scale=1000,
eps=1e-6,
):
"""
Compute the DICE loss, similar to generalized IOU for masks
Args:
inputs: A float tensor of arbitrary shape.
The predictions for each example.
targets: A float tensor with the same shape as inputs. Stores the binary
classification label for each element in inputs
(0 for the negative class and 1 for the positive class).
num_masks:
scale:
eps:
"""
inputs = inputs.sigmoid()
inputs = inputs.flatten(1, 2)
targets = targets.flatten(1, 2)
numerator = 2 * (inputs / scale * targets).sum(-1)
denominator = (inputs / scale).sum(-1) + (targets / scale).sum(-1)
loss = 1 - (numerator + eps) / (denominator + eps)
loss = loss.sum() / (num_masks + 1e-8)
return loss
def sigmoid_ce_loss(
inputs: torch.Tensor,
targets: torch.Tensor,
num_masks: float,
):
"""
Args:
inputs: A float tensor of arbitrary shape.
The predictions for each example.
targets: A float tensor with the same shape as inputs. Stores the binary
classification label for each element in inputs
(0 for the negative class and 1 for the positive class).
num_masks:
Returns:
Loss tensor
"""
loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
loss = loss.flatten(1, 2).mean(1).sum() / (num_masks + 1e-8)
return loss
class UllavaConfig(PretrainedConfig):
model_type = "ullava"
is_composition = True
def __init__(self,
llm_config=None,
ce_weight=0.5,
bce_weight=0.5,
dice_weight=-1,
out_dim=256,
seg_token_idx=32007,
train_mask_decoder=True,
**kwargs
):
super(UllavaConfig, self).__init__(**kwargs)
self.llm_config = UllavaCoreConfig(**llm_config) if llm_config else {}
self.ce_weight = ce_weight
self.bce_weight = bce_weight
self.out_dim = out_dim
self.dice_weight = dice_weight
self.seg_token_idx = seg_token_idx
self.train_mask_decoder = train_mask_decoder
def to_dict(self):
"""
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
Returns:
`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
"""
output = copy.deepcopy(self.__dict__)
output["llm_config"] = self.llm_config.to_dict() if self.llm_config else {}
output["ce_weight"] = self.ce_weight
output["bce_weight"] = self.bce_weight
output["dice_weight"] = self.dice_weight
output["out_dim"] = self.out_dim
output["seg_token_idx"] = self.seg_token_idx
output["train_mask_decoder"] = self.train_mask_decoder
output["model_type"] = self.__class__.model_type
return output
@registry.register_model('ullava')
class UllavaForCausalLM(PreTrainedModel):
config_class = UllavaConfig
def __init__(self, config):
super().__init__(config)
self.config = config
llm_config = config.llm_config
self.llm = UllavaCoreForCausalLM(llm_config)
# initialize sam and projector without checkpoint
self.visual_model, self.text_hidden_fcs = self.init_seg_modules(llm_config.hidden_size)
def init_seg_modules(self, hidden_size):
# SAM
| """
u-LLaVA with segmentation module
SAM patch is Adapted form: https://github.com/dvlab-research/LISA/blob/main/model/LISA.py
"""
def dice_loss(
inputs: torch.Tensor,
targets: torch.Tensor,
num_masks: float,
scale=1000,
eps=1e-6,
):
"""
Compute the DICE loss, similar to generalized IOU for masks
Args:
inputs: A float tensor of arbitrary shape.
The predictions for each example.
targets: A float tensor with the same shape as inputs. Stores the binary
classification label for each element in inputs
(0 for the negative class and 1 for the positive class).
num_masks:
scale:
eps:
"""
inputs = inputs.sigmoid()
inputs = inputs.flatten(1, 2)
targets = targets.flatten(1, 2)
numerator = 2 * (inputs / scale * targets).sum(-1)
denominator = (inputs / scale).sum(-1) + (targets / scale).sum(-1)
loss = 1 - (numerator + eps) / (denominator + eps)
loss = loss.sum() / (num_masks + 1e-8)
return loss
def sigmoid_ce_loss(
inputs: torch.Tensor,
targets: torch.Tensor,
num_masks: float,
):
"""
Args:
inputs: A float tensor of arbitrary shape.
The predictions for each example.
targets: A float tensor with the same shape as inputs. Stores the binary
classification label for each element in inputs
(0 for the negative class and 1 for the positive class).
num_masks:
Returns:
Loss tensor
"""
loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
loss = loss.flatten(1, 2).mean(1).sum() / (num_masks + 1e-8)
return loss
class UllavaConfig(PretrainedConfig):
model_type = "ullava"
is_composition = True
def __init__(self,
llm_config=None,
ce_weight=0.5,
bce_weight=0.5,
dice_weight=-1,
out_dim=256,
seg_token_idx=32007,
train_mask_decoder=True,
**kwargs
):
super(UllavaConfig, self).__init__(**kwargs)
self.llm_config = UllavaCoreConfig(**llm_config) if llm_config else {}
self.ce_weight = ce_weight
self.bce_weight = bce_weight
self.out_dim = out_dim
self.dice_weight = dice_weight
self.seg_token_idx = seg_token_idx
self.train_mask_decoder = train_mask_decoder
def to_dict(self):
"""
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`].
Returns:
`Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
"""
output = copy.deepcopy(self.__dict__)
output["llm_config"] = self.llm_config.to_dict() if self.llm_config else {}
output["ce_weight"] = self.ce_weight
output["bce_weight"] = self.bce_weight
output["dice_weight"] = self.dice_weight
output["out_dim"] = self.out_dim
output["seg_token_idx"] = self.seg_token_idx
output["train_mask_decoder"] = self.train_mask_decoder
output["model_type"] = self.__class__.model_type
return output
@registry.register_model('ullava')
class UllavaForCausalLM(PreTrainedModel):
config_class = UllavaConfig
def __init__(self, config):
super().__init__(config)
self.config = config
llm_config = config.llm_config
self.llm = UllavaCoreForCausalLM(llm_config)
# initialize sam and projector without checkpoint
self.visual_model, self.text_hidden_fcs = self.init_seg_modules(llm_config.hidden_size)
def init_seg_modules(self, hidden_size):
# SAM | visual_model = build_sam_vit_h(checkpoint=None) | 1 | 2023-12-21 08:10:23+00:00 | 8k |
chinhsuanwu/ifusion | ifusion.py | [
{
"identifier": "FinetuneIterableDataset",
"path": "dataset/finetune.py",
"snippet": "class FinetuneIterableDataset(IterableDataset, FinetuneDataset):\n def __init__(self, transform_fp):\n super().__init__(transform_fp)\n\n def __iter__(self):\n while True:\n index = torch... | import json
import numpy as np
import torch
from glob import glob
from einops import rearrange
from liegroups.torch import SE3
from tqdm import trange
from dataset.finetune import FinetuneIterableDataset
from dataset.inference import MultiImageInferenceDataset, SingleImageInferenceDataset
from util.pose import latlon2mat, make_T, mat2latlon
from util.typing import *
from util.util import load_image, parse_optimizer, parse_scheduler
from util.viz import plot_image | 3,716 | transform_fp: str,
demo_fp: str,
default_latlon: List[float] = [0, 0, 1],
**kwargs,
):
image_fps = sorted(glob(image_dir + "/*.png") + glob(image_dir + "/*.jpg"))
image_fps = [fp for fp in image_fps if fp != demo_fp]
# FIXME: always pick the first image as reference
ref_image = load_image(image_fps[0])
qry_images = [load_image(image_fps[i]) for i in range(1, len(image_fps))]
out_dict = {"camera_angle_x": np.deg2rad(49.1), "frames": []}
out_dict["frames"].append(
{
"file_path": image_fps[0].replace(image_dir + "/", ""),
"transform_matrix": latlon2mat(torch.tensor([default_latlon])).tolist(),
"latlon": list(default_latlon),
}
)
for qry_fp, qry_image in zip(image_fps[1:], qry_images):
assert ref_image.shape == qry_image.shape
pose = optimize_pose_pair(
model=model, ref_image=ref_image, qry_image=qry_image, **kwargs
)
pose = np.add(default_latlon, pose.unsqueeze(0))
out_dict["frames"].append(
{
"file_path": qry_fp.replace(image_dir + "/", ""),
"transform_matrix": latlon2mat(pose.clone()).tolist(),
"latlon": pose.squeeze().tolist(),
}
)
# save poses to json
with open(transform_fp, "w") as f:
json.dump(out_dict, f, indent=4)
def finetune(
model,
transform_fp: str,
lora_ckpt_fp: str,
lora_rank: int,
lora_target_replace_module: List[str],
args,
):
model.inject_lora(
rank=lora_rank,
target_replace_module=lora_target_replace_module,
)
train_dataset = FinetuneIterableDataset(transform_fp)
train_loader = train_dataset.loader(args.batch_size)
optimizer = parse_optimizer(args.optimizer, model.require_grad_params)
scheduler = parse_scheduler(args.scheduler, optimizer)
train_loader = iter(train_loader)
with trange(args.max_step) as pbar:
for step in pbar:
optimizer.zero_grad()
batch = next(train_loader)
batch = {k: v.to(model.device) for k, v in batch.items()}
loss = model(batch)
pbar.set_description(f"step: {step}, loss: {loss.item():.4f}")
loss.backward()
optimizer.step()
scheduler.step()
model.save_lora(lora_ckpt_fp)
model.remove_lora()
def inference(
model,
transform_fp: str,
lora_ckpt_fp: str,
demo_fp: str,
lora_rank: int,
lora_target_replace_module: List[str],
use_multi_view_condition: bool,
n_views: int,
theta: float,
radius: float,
args,
):
if lora_ckpt_fp:
model.inject_lora(
ckpt_fp=lora_ckpt_fp,
rank=lora_rank,
target_replace_module=lora_target_replace_module,
)
if use_multi_view_condition:
test_dataset = MultiImageInferenceDataset
generate_fn = model.generate_from_tensor_multi_cond
else:
test_dataset = SingleImageInferenceDataset
generate_fn = model.generate_from_tensor
test_dataset = test_dataset(
transform_fp=transform_fp, n_views=n_views, theta=theta, radius=radius
)
test_loader = test_dataset.loader(args.batch_size)
for batch in test_loader:
batch = {k: v.to(model.device) for k, v in batch.items()}
out = generate_fn(
image=batch["image_cond"],
theta=batch["theta"],
azimuth=batch["azimuth"],
distance=batch["distance"],
)
if lora_ckpt_fp:
model.remove_lora()
out = rearrange(out, "b c h w -> 1 c h (b w)")
|
def optimize_pose_loop(
model,
image_cond: Float[Tensor, "2 3 256 256"],
image_target: Float[Tensor, "2 3 256 256"],
T: Float[Tensor, "4 4"],
default_radius: float,
search_radius_range: float,
use_step_ratio: bool,
args,
**kwargs,
):
# init xi in se(3)
xi = torch.randn(6) * 1e-6
xi.requires_grad_()
optimizer = parse_optimizer(args.optimizer, [xi])
scheduler = parse_scheduler(args.scheduler, optimizer)
total_loss = 0.0
with trange(args.max_step) as pbar:
for step in pbar:
optimizer.zero_grad()
# se(3) -> SE(3)
T_delta = SE3.exp(xi).as_matrix()
T_ = T @ T_delta
latlon = mat2latlon(T_).squeeze()
theta, azimuth = latlon[0], latlon[1]
distance = (
torch.sin(torch.norm(T_[:3, 3]) - default_radius) * search_radius_range
)
idx = [0, 1] if torch.rand(1) < 0.5 else [1, 0]
batch = {
"image_cond": image_cond[idx],
"image_target": image_target[idx],
"T": torch.stack(
(
make_T(theta, azimuth, distance),
make_T(-theta, -azimuth, -distance),
)
)[idx].to(model.device),
}
if use_step_ratio:
loss = model(batch, step_ratio=step / args.max_step)
else:
loss = model(batch)
total_loss += loss
pbar.set_description(
f"step: {step}, total_loss: {total_loss:.4f}, loss: {loss.item():.2f}, theta: {theta.rad2deg().item():.2f}, azimuth: {azimuth.rad2deg().item():.2f}, distance: {distance.item():.2f}"
)
loss.backward()
optimizer.step()
scheduler.step(total_loss)
return total_loss, theta, azimuth, distance
def optimize_pose_pair(
model,
ref_image: Float[Tensor, "1 3 256 256"],
qry_image: Float[Tensor, "1 3 256 256"],
init_latlon: List[List],
**kwargs,
):
image_cond = torch.cat((ref_image, qry_image)).to(model.device)
image_target = torch.cat((qry_image, ref_image)).to(model.device)
init_T = latlon2mat(torch.tensor(init_latlon))
results = []
for T in init_T:
total_loss, theta, azimuth, distance = optimize_pose_loop(
model,
image_cond=image_cond,
image_target=image_target,
T=T,
**kwargs,
)
results.append(
(
total_loss.item(),
theta.rad2deg().item(),
azimuth.rad2deg().item(),
distance.item(),
)
)
results = torch.tensor(results)
best_idx = torch.argmin(results[:, 0])
pred_pose = results[best_idx][1:]
print(
f"[INFO] Best pose: theta: {pred_pose[0]:.2f}, azimuth: {pred_pose[1]:.2f}, distance: {pred_pose[2]:.2f}"
)
return pred_pose
def optimize_pose(
model,
image_dir: str,
transform_fp: str,
demo_fp: str,
default_latlon: List[float] = [0, 0, 1],
**kwargs,
):
image_fps = sorted(glob(image_dir + "/*.png") + glob(image_dir + "/*.jpg"))
image_fps = [fp for fp in image_fps if fp != demo_fp]
# FIXME: always pick the first image as reference
ref_image = load_image(image_fps[0])
qry_images = [load_image(image_fps[i]) for i in range(1, len(image_fps))]
out_dict = {"camera_angle_x": np.deg2rad(49.1), "frames": []}
out_dict["frames"].append(
{
"file_path": image_fps[0].replace(image_dir + "/", ""),
"transform_matrix": latlon2mat(torch.tensor([default_latlon])).tolist(),
"latlon": list(default_latlon),
}
)
for qry_fp, qry_image in zip(image_fps[1:], qry_images):
assert ref_image.shape == qry_image.shape
pose = optimize_pose_pair(
model=model, ref_image=ref_image, qry_image=qry_image, **kwargs
)
pose = np.add(default_latlon, pose.unsqueeze(0))
out_dict["frames"].append(
{
"file_path": qry_fp.replace(image_dir + "/", ""),
"transform_matrix": latlon2mat(pose.clone()).tolist(),
"latlon": pose.squeeze().tolist(),
}
)
# save poses to json
with open(transform_fp, "w") as f:
json.dump(out_dict, f, indent=4)
def finetune(
model,
transform_fp: str,
lora_ckpt_fp: str,
lora_rank: int,
lora_target_replace_module: List[str],
args,
):
model.inject_lora(
rank=lora_rank,
target_replace_module=lora_target_replace_module,
)
train_dataset = FinetuneIterableDataset(transform_fp)
train_loader = train_dataset.loader(args.batch_size)
optimizer = parse_optimizer(args.optimizer, model.require_grad_params)
scheduler = parse_scheduler(args.scheduler, optimizer)
train_loader = iter(train_loader)
with trange(args.max_step) as pbar:
for step in pbar:
optimizer.zero_grad()
batch = next(train_loader)
batch = {k: v.to(model.device) for k, v in batch.items()}
loss = model(batch)
pbar.set_description(f"step: {step}, loss: {loss.item():.4f}")
loss.backward()
optimizer.step()
scheduler.step()
model.save_lora(lora_ckpt_fp)
model.remove_lora()
def inference(
model,
transform_fp: str,
lora_ckpt_fp: str,
demo_fp: str,
lora_rank: int,
lora_target_replace_module: List[str],
use_multi_view_condition: bool,
n_views: int,
theta: float,
radius: float,
args,
):
if lora_ckpt_fp:
model.inject_lora(
ckpt_fp=lora_ckpt_fp,
rank=lora_rank,
target_replace_module=lora_target_replace_module,
)
if use_multi_view_condition:
test_dataset = MultiImageInferenceDataset
generate_fn = model.generate_from_tensor_multi_cond
else:
test_dataset = SingleImageInferenceDataset
generate_fn = model.generate_from_tensor
test_dataset = test_dataset(
transform_fp=transform_fp, n_views=n_views, theta=theta, radius=radius
)
test_loader = test_dataset.loader(args.batch_size)
for batch in test_loader:
batch = {k: v.to(model.device) for k, v in batch.items()}
out = generate_fn(
image=batch["image_cond"],
theta=batch["theta"],
azimuth=batch["azimuth"],
distance=batch["distance"],
)
if lora_ckpt_fp:
model.remove_lora()
out = rearrange(out, "b c h w -> 1 c h (b w)") | plot_image(out, fp=demo_fp) | 9 | 2023-12-17 12:45:38+00:00 | 8k |
wangzhecheng/SkyScript | src/open_clip/coca_model.py | [
{
"identifier": "LayerNormFp32",
"path": "src/open_clip/transformer.py",
"snippet": "class LayerNormFp32(nn.LayerNorm):\n \"\"\"Subclass torch's LayerNorm to handle fp16 (by casting to float32 and back).\"\"\"\n\n def forward(self, x: torch.Tensor):\n orig_type = x.dtype\n x = F.laye... | from typing import Optional
from torch import nn
from torch.nn import functional as F
from dataclasses import dataclass
from .transformer import (
LayerNormFp32,
LayerNorm,
QuickGELU,
MultimodalTransformer,
)
from .model import CLIPTextCfg, CLIPVisionCfg, _build_vision_tower, _build_text_tower
from transformers import (
BeamSearchScorer,
LogitsProcessorList,
TopPLogitsWarper,
TopKLogitsWarper,
RepetitionPenaltyLogitsProcessor,
MinLengthLogitsProcessor,
MaxLengthCriteria,
StoppingCriteriaList
)
import torch
import numpy as np | 3,666 | """
Adapted from https://github.com/mlfoundations/open_clip. Copyright (c) 2012-2021 Gabriel Ilharco, Mitchell Wortsman, Nicholas Carlini, Rohan Taori, Achal Dave, Vaishaal Shankar, John Miller, Hongseok Namkoong, Hannaneh Hajishirzi, Ali Farhadi, Ludwig Schmidt
"""
try:
GENERATION_TYPES = {
"top_k": TopKLogitsWarper,
"top_p": TopPLogitsWarper,
"beam_search": "beam_search"
}
_has_transformers = True
except ImportError as e:
GENERATION_TYPES = {
"top_k": None,
"top_p": None,
"beam_search": "beam_search"
}
_has_transformers = False
@dataclass
class MultimodalCfg(CLIPTextCfg):
mlp_ratio: int = 4
dim_head: int = 64
heads: int = 8
n_queries: int = 256
attn_pooler_heads: int = 8
def _build_text_decoder_tower(
embed_dim,
multimodal_cfg,
quick_gelu: bool = False,
cast_dtype: Optional[torch.dtype] = None,
):
multimodal_cfg = MultimodalCfg(**multimodal_cfg) if isinstance(multimodal_cfg, dict) else multimodal_cfg
act_layer = QuickGELU if quick_gelu else nn.GELU
norm_layer = (
LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm
)
decoder = MultimodalTransformer(
context_length=multimodal_cfg.context_length,
width=multimodal_cfg.width,
heads=multimodal_cfg.heads,
layers=multimodal_cfg.layers,
ls_init_value=multimodal_cfg.ls_init_value,
output_dim=embed_dim,
act_layer=act_layer,
norm_layer=norm_layer,
)
return decoder
class CoCa(nn.Module):
def __init__(
self,
embed_dim,
multimodal_cfg: MultimodalCfg,
text_cfg: CLIPTextCfg,
vision_cfg: CLIPVisionCfg,
quick_gelu: bool = False,
cast_dtype: Optional[torch.dtype] = None,
pad_id: int = 0,
):
super().__init__()
multimodal_cfg = MultimodalCfg(**multimodal_cfg) if isinstance(multimodal_cfg, dict) else multimodal_cfg
text_cfg = CLIPTextCfg(**text_cfg) if isinstance(text_cfg, dict) else text_cfg
vision_cfg = CLIPVisionCfg(**vision_cfg) if isinstance(vision_cfg, dict) else vision_cfg
| """
Adapted from https://github.com/mlfoundations/open_clip. Copyright (c) 2012-2021 Gabriel Ilharco, Mitchell Wortsman, Nicholas Carlini, Rohan Taori, Achal Dave, Vaishaal Shankar, John Miller, Hongseok Namkoong, Hannaneh Hajishirzi, Ali Farhadi, Ludwig Schmidt
"""
try:
GENERATION_TYPES = {
"top_k": TopKLogitsWarper,
"top_p": TopPLogitsWarper,
"beam_search": "beam_search"
}
_has_transformers = True
except ImportError as e:
GENERATION_TYPES = {
"top_k": None,
"top_p": None,
"beam_search": "beam_search"
}
_has_transformers = False
@dataclass
class MultimodalCfg(CLIPTextCfg):
mlp_ratio: int = 4
dim_head: int = 64
heads: int = 8
n_queries: int = 256
attn_pooler_heads: int = 8
def _build_text_decoder_tower(
embed_dim,
multimodal_cfg,
quick_gelu: bool = False,
cast_dtype: Optional[torch.dtype] = None,
):
multimodal_cfg = MultimodalCfg(**multimodal_cfg) if isinstance(multimodal_cfg, dict) else multimodal_cfg
act_layer = QuickGELU if quick_gelu else nn.GELU
norm_layer = (
LayerNormFp32 if cast_dtype in (torch.float16, torch.bfloat16) else LayerNorm
)
decoder = MultimodalTransformer(
context_length=multimodal_cfg.context_length,
width=multimodal_cfg.width,
heads=multimodal_cfg.heads,
layers=multimodal_cfg.layers,
ls_init_value=multimodal_cfg.ls_init_value,
output_dim=embed_dim,
act_layer=act_layer,
norm_layer=norm_layer,
)
return decoder
class CoCa(nn.Module):
def __init__(
self,
embed_dim,
multimodal_cfg: MultimodalCfg,
text_cfg: CLIPTextCfg,
vision_cfg: CLIPVisionCfg,
quick_gelu: bool = False,
cast_dtype: Optional[torch.dtype] = None,
pad_id: int = 0,
):
super().__init__()
multimodal_cfg = MultimodalCfg(**multimodal_cfg) if isinstance(multimodal_cfg, dict) else multimodal_cfg
text_cfg = CLIPTextCfg(**text_cfg) if isinstance(text_cfg, dict) else text_cfg
vision_cfg = CLIPVisionCfg(**vision_cfg) if isinstance(vision_cfg, dict) else vision_cfg
| self.text = _build_text_tower( | 7 | 2023-12-19 11:50:56+00:00 | 8k |
JarodMica/ai-voice-cloning | modules/rvc/infer-web.py | [
{
"identifier": "uvr",
"path": "modules/rvc/infer/modules/uvr5/modules.py",
"snippet": "def uvr(model_name, inp_root, save_root_vocal, paths, save_root_ins, agg, format0):\n infos = []\n try:\n inp_root = inp_root.strip(\" \").strip('\"').strip(\"\\n\").strip('\"').strip(\" \")\n sav... | import os, sys
import logging
import shutil
import threading
import traceback
import warnings
import json
import pathlib
import fairseq
import faiss
import gradio as gr
import numpy as np
import torch
from random import shuffle
from subprocess import Popen
from time import sleep
from dotenv import load_dotenv
from sklearn.cluster import MiniBatchKMeans
from configs.config import Config
from i18n.i18n import I18nAuto
from modules.rvc.infer.lib.train.process_ckpt import (
change_info,
extract_small_model,
merge,
show_info,
)
from modules.rvc.infer.modules.uvr5.modules import uvr
from modules.rvc.infer.modules.vc.modules import VC
from modules.rvc.infer.modules.onnx.export import export_onnx as eo | 3,728 |
now_dir = os.getcwd()
sys.path.append(now_dir)
logging.getLogger("numba").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
tmp = os.path.join(now_dir, "TEMP")
shutil.rmtree(tmp, ignore_errors=True)
shutil.rmtree("%s/runtime/Lib/site-packages/infer_pack" % (now_dir), ignore_errors=True)
shutil.rmtree("%s/runtime/Lib/site-packages/uvr5_pack" % (now_dir), ignore_errors=True)
os.makedirs(tmp, exist_ok=True)
os.makedirs(os.path.join(now_dir, "logs"), exist_ok=True)
os.makedirs(os.path.join(now_dir, "assets/weights"), exist_ok=True)
os.environ["TEMP"] = tmp
warnings.filterwarnings("ignore")
torch.manual_seed(114514)
load_dotenv()
config = Config()
|
now_dir = os.getcwd()
sys.path.append(now_dir)
logging.getLogger("numba").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
tmp = os.path.join(now_dir, "TEMP")
shutil.rmtree(tmp, ignore_errors=True)
shutil.rmtree("%s/runtime/Lib/site-packages/infer_pack" % (now_dir), ignore_errors=True)
shutil.rmtree("%s/runtime/Lib/site-packages/uvr5_pack" % (now_dir), ignore_errors=True)
os.makedirs(tmp, exist_ok=True)
os.makedirs(os.path.join(now_dir, "logs"), exist_ok=True)
os.makedirs(os.path.join(now_dir, "assets/weights"), exist_ok=True)
os.environ["TEMP"] = tmp
warnings.filterwarnings("ignore")
torch.manual_seed(114514)
load_dotenv()
config = Config() | vc = VC(config) | 1 | 2023-12-18 00:10:23+00:00 | 8k |
penghao-wu/vstar | VisualSearch/model/owlvit/owlvit.py | [
{
"identifier": "box_ops",
"path": "VisualSearch/model/owlvit/util/box_ops.py",
"snippet": "def box_cxcywh_to_xyxy(x):\ndef box_xyxy_to_cxcywh(x):\ndef box_iou(boxes1, boxes2):\ndef generalized_box_iou(boxes1, boxes2):\ndef masks_to_boxes(masks):"
},
{
"identifier": "nested_tensor_from_tensor_li... | import torch
import torch.nn.functional as F
import numpy as np
import math
import copy
from torch import nn
from typing import Any, Dict, Optional, Tuple, Union
from transformers import OwlViTForObjectDetection, OwlViTConfig
from .util import box_ops
from .util.misc import (nested_tensor_from_tensor_list,
accuracy, interpolate, inverse_sigmoid)
from .matcher import HungarianMatcher
from .segmentation import dice_loss, sigmoid_focal_loss
from .matcher import HungarianMatcher | 5,482 | pred_boxes += self.compute_box_bias(feature_map)
pred_boxes = self.sigmoid(pred_boxes)
return pred_boxes
def class_predictor(
self,
image_feats: torch.FloatTensor,
query_embeds: Optional[torch.FloatTensor] = None,
query_mask: Optional[torch.Tensor] = None,
) -> Tuple[torch.FloatTensor]:
"""
Args:
image_feats:
Features extracted from the `image_text_embedder`.
query_embeds:
Text query embeddings.
query_mask:
Must be provided with query_embeddings. A mask indicating which query embeddings are valid.
"""
(pred_logits, image_class_embeds) = self.class_head(image_feats, query_embeds, query_mask)
return (pred_logits, image_class_embeds)
def get_visual_embs(self, image):
vision_outputs = self.vision_model(
pixel_values=image,
output_hidden_states=self.vision_model.config.output_hidden_states,
return_dict=self.vision_model.config.use_return_dict,
)
# Get image embeddings
last_hidden_state = vision_outputs[0]
image_embeds = self.vision_model.post_layernorm(last_hidden_state)
# Resize class token
new_size = tuple(np.array(image_embeds.shape) - np.array((0, 1, 0)))
class_token_out = torch.broadcast_to(image_embeds[:, :1, :], new_size)
# Merge image embedding with class tokens
image_embeds = image_embeds[:, 1:, :] * class_token_out
image_embeds = self.layer_norm(image_embeds)
# Resize to [batch_size, num_patches, num_patches, hidden_size]
new_size = (
image_embeds.shape[0],
int(np.sqrt(image_embeds.shape[1])),
int(np.sqrt(image_embeds.shape[1])),
image_embeds.shape[-1],
)
feature_map = image_embeds.reshape(new_size)
return feature_map
def forward(
self,
image_embeddings: torch.Tensor,
prompt_embeddings: torch.Tensor,
):
feature_map = image_embeddings
batch_size, num_patches, num_patches, hidden_dim = feature_map.shape
image_feats = torch.reshape(feature_map, (batch_size, num_patches * num_patches, hidden_dim))
query_embeds = prompt_embeddings.reshape(batch_size, 1, prompt_embeddings.shape[-1])
# Predict object classes [batch_size, num_patches, num_queries+1]
(pred_logits, class_embeds) = self.class_predictor(image_feats, query_embeds)
# Predict object boxes
pred_boxes = self.box_predictor(image_feats, feature_map)
out = {'pred_logits': pred_logits, 'pred_boxes': pred_boxes}
return out
class SetCriterion(nn.Module):
""" This class computes the loss for DETR.
The process happens in two steps:
1) we compute hungarian assignment between ground truth boxes and the outputs of the model
2) we supervise each pair of matched ground-truth / prediction (supervise class and box)
"""
def __init__(self, num_classes, matcher, weight_dict, losses, focal_alpha=0.25):
""" Create the criterion.
Parameters:
num_classes: number of object categories, omitting the special no-object category
matcher: module able to compute a matching between targets and proposals
weight_dict: dict containing as key the names of the losses and as values their relative weight.
losses: list of all the losses to be applied. See get_loss for list of available losses.
focal_alpha: alpha in Focal Loss
"""
super().__init__()
self.num_classes = num_classes
self.matcher = matcher
self.weight_dict = weight_dict
self.losses = losses
self.focal_alpha = focal_alpha
def loss_labels(self, outputs, targets, indices, num_boxes, log=True):
"""Classification loss (NLL)
targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes]
"""
assert 'pred_logits' in outputs
src_logits = outputs['pred_logits']
idx = self._get_src_permutation_idx(indices)
target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)])
target_classes = torch.full(src_logits.shape[:2], self.num_classes,
dtype=torch.int64, device=src_logits.device)
target_classes[idx] = target_classes_o
target_classes_onehot = torch.zeros([src_logits.shape[0], src_logits.shape[1], src_logits.shape[2] + 1],
dtype=src_logits.dtype, layout=src_logits.layout, device=src_logits.device)
target_classes_onehot.scatter_(2, target_classes.unsqueeze(-1), 1)
target_classes_onehot = target_classes_onehot[:,:,:-1]
loss_ce = sigmoid_focal_loss(src_logits, target_classes_onehot, num_boxes, alpha=self.focal_alpha, gamma=2) * src_logits.shape[1]
losses = {'loss_ce': loss_ce}
if log:
# TODO this should probably be a separate loss, not hacked in this one here
|
class OwlViT(nn.Module):
def __init__(self, num_classes, is_eval=False):
super().__init__()
if is_eval:
owlViT_config = OwlViTConfig.from_pretrained("google/owlvit-base-patch16")
model_owlViT = OwlViTForObjectDetection(owlViT_config)
else:
model_owlViT = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch16")
self.vision_model = model_owlViT.owlvit.vision_model
self.class_head = model_owlViT.class_head
self.box_head = model_owlViT.box_head
self.layer_norm = model_owlViT.layer_norm
self.sigmoid = nn.Sigmoid()
del model_owlViT
self.matcher = HungarianMatcher(cost_class=2, cost_bbox=5, cost_giou=2)
self.weight_dict = {'loss_ce': 2, 'loss_bbox': 5, 'loss_giou': 2}
self.losses = ['labels', 'boxes']
# num_classes, matcher, weight_dict, losses, focal_alpha=0.25
self.criterion = SetCriterion(num_classes, self.matcher, self.weight_dict, self.losses, focal_alpha=0.25)
def normalize_grid_corner_coordinates(self, feature_map: torch.FloatTensor):
# Computes normalized xy corner coordinates from feature_map.
if not feature_map.ndim == 4:
raise ValueError("Expected input shape is [batch_size, num_patches, num_patches, hidden_dim]")
device = feature_map.device
num_patches = feature_map.shape[1]
box_coordinates = np.stack(
np.meshgrid(np.arange(1, num_patches + 1), np.arange(1, num_patches + 1)), axis=-1
).astype(np.float32)
box_coordinates /= np.array([num_patches, num_patches], np.float32)
# Flatten (h, w, 2) -> (h*w, 2)
box_coordinates = box_coordinates.reshape(
box_coordinates.shape[0] * box_coordinates.shape[1], box_coordinates.shape[2]
)
box_coordinates = torch.from_numpy(box_coordinates).to(device)
return box_coordinates
def compute_box_bias(self, feature_map: torch.FloatTensor) -> torch.FloatTensor:
# The box center is biased to its position on the feature grid
box_coordinates = self.normalize_grid_corner_coordinates(feature_map)
box_coordinates = torch.clip(box_coordinates, 0.0, 1.0)
# Unnormalize xy
box_coord_bias = torch.log(box_coordinates + 1e-4) - torch.log1p(-box_coordinates + 1e-4)
# The box size is biased to the patch size
box_size = torch.full_like(box_coord_bias, 1.0 / feature_map.shape[-2])
box_size_bias = torch.log(box_size + 1e-4) - torch.log1p(-box_size + 1e-4)
# Compute box bias
box_bias = torch.cat([box_coord_bias, box_size_bias], dim=-1)
return box_bias
def box_predictor(
self,
image_feats: torch.FloatTensor,
feature_map: torch.FloatTensor,
) -> torch.FloatTensor:
"""
Args:
image_feats:
Features extracted from the image, returned by the `image_text_embedder` method.
feature_map:
A spatial re-arrangement of image_features, also returned by the `image_text_embedder` method.
Returns:
pred_boxes:
List of predicted boxes (cxcywh normalized to 0, 1) nested within a dictionary.
"""
# Bounding box detection head [batch_size, num_boxes, 4].
pred_boxes = self.box_head(image_feats)
# Compute the location of each token on the grid and use it to compute a bias for the bbox prediction
pred_boxes += self.compute_box_bias(feature_map)
pred_boxes = self.sigmoid(pred_boxes)
return pred_boxes
def class_predictor(
self,
image_feats: torch.FloatTensor,
query_embeds: Optional[torch.FloatTensor] = None,
query_mask: Optional[torch.Tensor] = None,
) -> Tuple[torch.FloatTensor]:
"""
Args:
image_feats:
Features extracted from the `image_text_embedder`.
query_embeds:
Text query embeddings.
query_mask:
Must be provided with query_embeddings. A mask indicating which query embeddings are valid.
"""
(pred_logits, image_class_embeds) = self.class_head(image_feats, query_embeds, query_mask)
return (pred_logits, image_class_embeds)
def get_visual_embs(self, image):
vision_outputs = self.vision_model(
pixel_values=image,
output_hidden_states=self.vision_model.config.output_hidden_states,
return_dict=self.vision_model.config.use_return_dict,
)
# Get image embeddings
last_hidden_state = vision_outputs[0]
image_embeds = self.vision_model.post_layernorm(last_hidden_state)
# Resize class token
new_size = tuple(np.array(image_embeds.shape) - np.array((0, 1, 0)))
class_token_out = torch.broadcast_to(image_embeds[:, :1, :], new_size)
# Merge image embedding with class tokens
image_embeds = image_embeds[:, 1:, :] * class_token_out
image_embeds = self.layer_norm(image_embeds)
# Resize to [batch_size, num_patches, num_patches, hidden_size]
new_size = (
image_embeds.shape[0],
int(np.sqrt(image_embeds.shape[1])),
int(np.sqrt(image_embeds.shape[1])),
image_embeds.shape[-1],
)
feature_map = image_embeds.reshape(new_size)
return feature_map
def forward(
self,
image_embeddings: torch.Tensor,
prompt_embeddings: torch.Tensor,
):
feature_map = image_embeddings
batch_size, num_patches, num_patches, hidden_dim = feature_map.shape
image_feats = torch.reshape(feature_map, (batch_size, num_patches * num_patches, hidden_dim))
query_embeds = prompt_embeddings.reshape(batch_size, 1, prompt_embeddings.shape[-1])
# Predict object classes [batch_size, num_patches, num_queries+1]
(pred_logits, class_embeds) = self.class_predictor(image_feats, query_embeds)
# Predict object boxes
pred_boxes = self.box_predictor(image_feats, feature_map)
out = {'pred_logits': pred_logits, 'pred_boxes': pred_boxes}
return out
class SetCriterion(nn.Module):
""" This class computes the loss for DETR.
The process happens in two steps:
1) we compute hungarian assignment between ground truth boxes and the outputs of the model
2) we supervise each pair of matched ground-truth / prediction (supervise class and box)
"""
def __init__(self, num_classes, matcher, weight_dict, losses, focal_alpha=0.25):
""" Create the criterion.
Parameters:
num_classes: number of object categories, omitting the special no-object category
matcher: module able to compute a matching between targets and proposals
weight_dict: dict containing as key the names of the losses and as values their relative weight.
losses: list of all the losses to be applied. See get_loss for list of available losses.
focal_alpha: alpha in Focal Loss
"""
super().__init__()
self.num_classes = num_classes
self.matcher = matcher
self.weight_dict = weight_dict
self.losses = losses
self.focal_alpha = focal_alpha
def loss_labels(self, outputs, targets, indices, num_boxes, log=True):
"""Classification loss (NLL)
targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes]
"""
assert 'pred_logits' in outputs
src_logits = outputs['pred_logits']
idx = self._get_src_permutation_idx(indices)
target_classes_o = torch.cat([t["labels"][J] for t, (_, J) in zip(targets, indices)])
target_classes = torch.full(src_logits.shape[:2], self.num_classes,
dtype=torch.int64, device=src_logits.device)
target_classes[idx] = target_classes_o
target_classes_onehot = torch.zeros([src_logits.shape[0], src_logits.shape[1], src_logits.shape[2] + 1],
dtype=src_logits.dtype, layout=src_logits.layout, device=src_logits.device)
target_classes_onehot.scatter_(2, target_classes.unsqueeze(-1), 1)
target_classes_onehot = target_classes_onehot[:,:,:-1]
loss_ce = sigmoid_focal_loss(src_logits, target_classes_onehot, num_boxes, alpha=self.focal_alpha, gamma=2) * src_logits.shape[1]
losses = {'loss_ce': loss_ce}
if log:
# TODO this should probably be a separate loss, not hacked in this one here | losses['class_error'] = 100 - accuracy(src_logits[idx], target_classes_o)[0] | 2 | 2023-12-15 14:58:24+00:00 | 8k |
worm128/AI-YinMei | text-generation-webui/extensions/superboogav2/api.py | [
{
"identifier": "ChromaCollector",
"path": "text-generation-webui/extensions/superboogav2/chromadb.py",
"snippet": "class ChromaCollector(Collecter):\n def __init__(self, embedder: Embedder):\n super().__init__()\n self.chroma_client = chromadb.Client(Settings(anonymized_telemetry=False... | import json
import extensions.superboogav2.parameters as parameters
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs
from threading import Thread
from modules import shared
from modules.logging_colors import logger
from .chromadb import ChromaCollector
from .data_processor import process_and_add_to_collector | 4,544 | """
This module is responsible for the VectorDB API. It currently supports:
* DELETE api/v1/clear
- Clears the whole DB.
* POST api/v1/add
- Add some corpus to the DB. You can also specify metadata to be added alongside it.
* POST api/v1/delete
- Delete specific records with given metadata.
* POST api/v1/get
- Get results from chromaDB.
"""
class CustomThreadingHTTPServer(ThreadingHTTPServer):
def __init__(self, server_address, RequestHandlerClass, collector: ChromaCollector, bind_and_activate=True):
self.collector = collector
super().__init__(server_address, RequestHandlerClass, bind_and_activate)
def finish_request(self, request, client_address):
self.RequestHandlerClass(request, client_address, self, self.collector)
class Handler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server, collector: ChromaCollector):
self.collector = collector
super().__init__(request, client_address, server)
def _send_412_error(self, message):
self.send_response(412)
self.send_header("Content-type", "application/json")
self.end_headers()
response = json.dumps({"error": message})
self.wfile.write(response.encode('utf-8'))
def _send_404_error(self):
self.send_response(404)
self.send_header("Content-type", "application/json")
self.end_headers()
response = json.dumps({"error": "Resource not found"})
self.wfile.write(response.encode('utf-8'))
def _send_400_error(self, error_message: str):
self.send_response(400)
self.send_header("Content-type", "application/json")
self.end_headers()
response = json.dumps({"error": error_message})
self.wfile.write(response.encode('utf-8'))
def _send_200_response(self, message: str):
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
if isinstance(message, str):
response = json.dumps({"message": message})
else:
response = json.dumps(message)
self.wfile.write(response.encode('utf-8'))
def _handle_get(self, search_strings: list[str], n_results: int, max_token_count: int, sort_param: str):
if sort_param == parameters.SORT_DISTANCE:
results = self.collector.get_sorted_by_dist(search_strings, n_results, max_token_count)
elif sort_param == parameters.SORT_ID:
results = self.collector.get_sorted_by_id(search_strings, n_results, max_token_count)
else: # Default is dist
results = self.collector.get_sorted_by_dist(search_strings, n_results, max_token_count)
return {
"results": results
}
def do_GET(self):
self._send_404_error()
def do_POST(self):
try:
content_length = int(self.headers['Content-Length'])
body = json.loads(self.rfile.read(content_length).decode('utf-8'))
parsed_path = urlparse(self.path)
path = parsed_path.path
query_params = parse_qs(parsed_path.query)
if path in ['/api/v1/add', '/api/add']:
corpus = body.get('corpus')
if corpus is None:
self._send_412_error("Missing parameter 'corpus'")
return
clear_before_adding = body.get('clear_before_adding', False)
metadata = body.get('metadata')
| """
This module is responsible for the VectorDB API. It currently supports:
* DELETE api/v1/clear
- Clears the whole DB.
* POST api/v1/add
- Add some corpus to the DB. You can also specify metadata to be added alongside it.
* POST api/v1/delete
- Delete specific records with given metadata.
* POST api/v1/get
- Get results from chromaDB.
"""
class CustomThreadingHTTPServer(ThreadingHTTPServer):
def __init__(self, server_address, RequestHandlerClass, collector: ChromaCollector, bind_and_activate=True):
self.collector = collector
super().__init__(server_address, RequestHandlerClass, bind_and_activate)
def finish_request(self, request, client_address):
self.RequestHandlerClass(request, client_address, self, self.collector)
class Handler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server, collector: ChromaCollector):
self.collector = collector
super().__init__(request, client_address, server)
def _send_412_error(self, message):
self.send_response(412)
self.send_header("Content-type", "application/json")
self.end_headers()
response = json.dumps({"error": message})
self.wfile.write(response.encode('utf-8'))
def _send_404_error(self):
self.send_response(404)
self.send_header("Content-type", "application/json")
self.end_headers()
response = json.dumps({"error": "Resource not found"})
self.wfile.write(response.encode('utf-8'))
def _send_400_error(self, error_message: str):
self.send_response(400)
self.send_header("Content-type", "application/json")
self.end_headers()
response = json.dumps({"error": error_message})
self.wfile.write(response.encode('utf-8'))
def _send_200_response(self, message: str):
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
if isinstance(message, str):
response = json.dumps({"message": message})
else:
response = json.dumps(message)
self.wfile.write(response.encode('utf-8'))
def _handle_get(self, search_strings: list[str], n_results: int, max_token_count: int, sort_param: str):
if sort_param == parameters.SORT_DISTANCE:
results = self.collector.get_sorted_by_dist(search_strings, n_results, max_token_count)
elif sort_param == parameters.SORT_ID:
results = self.collector.get_sorted_by_id(search_strings, n_results, max_token_count)
else: # Default is dist
results = self.collector.get_sorted_by_dist(search_strings, n_results, max_token_count)
return {
"results": results
}
def do_GET(self):
self._send_404_error()
def do_POST(self):
try:
content_length = int(self.headers['Content-Length'])
body = json.loads(self.rfile.read(content_length).decode('utf-8'))
parsed_path = urlparse(self.path)
path = parsed_path.path
query_params = parse_qs(parsed_path.query)
if path in ['/api/v1/add', '/api/add']:
corpus = body.get('corpus')
if corpus is None:
self._send_412_error("Missing parameter 'corpus'")
return
clear_before_adding = body.get('clear_before_adding', False)
metadata = body.get('metadata') | process_and_add_to_collector(corpus, self.collector, clear_before_adding, metadata) | 1 | 2023-12-20 14:13:38+00:00 | 8k |
sinoyou/nelf-pro | nerfstudio/models/base_model.py | [
{
"identifier": "RayBundle",
"path": "nerfstudio/cameras/rays.py",
"snippet": "class RayBundle(TensorDataclass):\n \"\"\"A bundle of ray parameters.\"\"\"\n\n # TODO(ethan): make sure the sizes with ... are correct\n origins: TensorType[..., 3]\n \"\"\"Ray origins (XYZ)\"\"\"\n directions... | from abc import abstractmethod
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple, Type
from torch import nn
from torch.nn import Parameter
from nerfstudio.cameras.rays import RayBundle
from nerfstudio.configs.base_config import InstantiateConfig
from nerfstudio.configs.config_utils import to_immutable_dict
from nerfstudio.data.scene_box import SceneBox
from nerfstudio.engine.callbacks import TrainingCallback, TrainingCallbackAttributes
from nerfstudio.model_components.scene_colliders import NearFarCollider
import torch | 4,056 | # Copyright 2022 The Nerfstudio Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Base Model implementation which takes in RayBundles
"""
from __future__ import annotations
# Model related configs
@dataclass
class ModelConfig(InstantiateConfig):
"""Configuration for model instantiation"""
_target: Type = field(default_factory=lambda: Model)
"""target class to instantiate"""
enable_collider: bool = True
"""Whether to create a scene collider to filter rays."""
collider_params: Optional[Dict[str, float]] = to_immutable_dict({"near_plane": 2.0, "far_plane": 6.0})
"""parameters to instantiate scene collider with"""
loss_coefficients: Dict[str, float] = to_immutable_dict({"rgb_loss_coarse": 1.0, "rgb_loss_fine": 1.0})
"""parameters to instantiate density field with"""
eval_num_rays_per_chunk: int = 4096
"""specifies number of rays per chunk during eval"""
class Model(nn.Module):
"""Model class
Where everything (Fields, Optimizers, Samplers, Visualization, etc) is linked together. This should be
subclassed for custom NeRF model.
Args:
config: configuration for instantiating model
scene_box: dataset scene box
"""
config: ModelConfig
def __init__(
self,
config: ModelConfig,
scene_box: SceneBox,
num_train_data: int,
world_size: int = 1,
local_rank: int = 0,
load_step: int = None,
**kwargs,
) -> None:
super().__init__()
self.config = config
self.scene_box = scene_box
self.num_train_data = num_train_data
self.kwargs = kwargs
self.collider = None
self.world_size = world_size
self.local_rank = local_rank
self.load_step = load_step
self.populate_modules() # populate the modules
self.callbacks = None
# to keep track of which device the nn.Module is on
self.device_indicator_param = nn.Parameter(torch.empty(0))
@property
def device(self):
"""Returns the device that the model is on."""
return self.device_indicator_param.device
def get_training_callbacks( # pylint:disable=no-self-use
self, training_callback_attributes: TrainingCallbackAttributes # pylint: disable=unused-argument
) -> List[TrainingCallback]:
"""Returns a list of callbacks that run functions at the specified training iterations."""
return []
def populate_modules(self):
"""Set the necessary modules to get the network working."""
# default instantiates optional modules that are common among many networks
# NOTE: call `super().populate_modules()` in subclasses
if self.config.enable_collider:
| # Copyright 2022 The Nerfstudio Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Base Model implementation which takes in RayBundles
"""
from __future__ import annotations
# Model related configs
@dataclass
class ModelConfig(InstantiateConfig):
"""Configuration for model instantiation"""
_target: Type = field(default_factory=lambda: Model)
"""target class to instantiate"""
enable_collider: bool = True
"""Whether to create a scene collider to filter rays."""
collider_params: Optional[Dict[str, float]] = to_immutable_dict({"near_plane": 2.0, "far_plane": 6.0})
"""parameters to instantiate scene collider with"""
loss_coefficients: Dict[str, float] = to_immutable_dict({"rgb_loss_coarse": 1.0, "rgb_loss_fine": 1.0})
"""parameters to instantiate density field with"""
eval_num_rays_per_chunk: int = 4096
"""specifies number of rays per chunk during eval"""
class Model(nn.Module):
"""Model class
Where everything (Fields, Optimizers, Samplers, Visualization, etc) is linked together. This should be
subclassed for custom NeRF model.
Args:
config: configuration for instantiating model
scene_box: dataset scene box
"""
config: ModelConfig
def __init__(
self,
config: ModelConfig,
scene_box: SceneBox,
num_train_data: int,
world_size: int = 1,
local_rank: int = 0,
load_step: int = None,
**kwargs,
) -> None:
super().__init__()
self.config = config
self.scene_box = scene_box
self.num_train_data = num_train_data
self.kwargs = kwargs
self.collider = None
self.world_size = world_size
self.local_rank = local_rank
self.load_step = load_step
self.populate_modules() # populate the modules
self.callbacks = None
# to keep track of which device the nn.Module is on
self.device_indicator_param = nn.Parameter(torch.empty(0))
@property
def device(self):
"""Returns the device that the model is on."""
return self.device_indicator_param.device
def get_training_callbacks( # pylint:disable=no-self-use
self, training_callback_attributes: TrainingCallbackAttributes # pylint: disable=unused-argument
) -> List[TrainingCallback]:
"""Returns a list of callbacks that run functions at the specified training iterations."""
return []
def populate_modules(self):
"""Set the necessary modules to get the network working."""
# default instantiates optional modules that are common among many networks
# NOTE: call `super().populate_modules()` in subclasses
if self.config.enable_collider: | self.collider = NearFarCollider( | 6 | 2023-12-15 20:07:22+00:00 | 8k |
Infleqtion/qLDPC | qldpc/codes.py | [
{
"identifier": "abstract",
"path": "qldpc/abstract.py",
"snippet": "DEFAULT_FIELD_ORDER = 2\nclass GroupMember(comb.Permutation):\nclass Group:\nclass Element:\nclass Protograph:\nclass TrivialGroup(Group):\nclass CyclicGroup(Group):\nclass DihedralGroup(Group):\nclass QuaternionGroup(Group):\n def ... | import abc
import functools
import itertools
import cachetools
import galois
import ldpc.mod2
import networkx as nx
import numpy as np
import numpy.typing as npt
import qldpc
from collections.abc import Collection, Iterable, Sequence
from typing import TYPE_CHECKING, Literal
from qldpc import abstract
from qldpc.objects import CayleyComplex, Node, Pauli, QuditOperator
from typing_extensions import Self | 5,509 | """Error correction code constructions
Copyright 2023 The qLDPC Authors and Infleqtion Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import annotations
if TYPE_CHECKING:
DEFAULT_FIELD_ORDER = abstract.DEFAULT_FIELD_ORDER
################################################################################
# template error correction code classes
class AbstractCode(abc.ABC):
"""Template class for error-correcting codes."""
_field_order: int
def __init__(
self,
matrix: Self | npt.NDArray[np.int_] | Sequence[Sequence[int]],
field: int | None = None,
) -> None:
"""Construct a code from a parity check matrix over a finite field.
The base field is taken to be F_2 by default.
"""
self._matrix: galois.FieldArray
if isinstance(matrix, type(self)):
self._field_order = matrix.field.order
if not (field is None or field == self._field_order):
raise ValueError(
f"Field argument {field} is inconsistent with the given code, which is defined"
f" over F_{self._field_order}"
)
self._matrix = matrix.matrix
elif isinstance(matrix, galois.FieldArray):
self._field_order = type(matrix).order
self._matrix = matrix
else:
self._field_order = field or DEFAULT_FIELD_ORDER
self._matrix = self.field(np.array(matrix))
@property
def field(self) -> type[galois.FieldArray]:
"""Base field over which this code is defined."""
return galois.GF(self._field_order)
@property
def matrix(self) -> galois.FieldArray:
"""Parity check matrix of this code."""
return self._matrix
@functools.cached_property
def graph(self) -> nx.DiGraph:
"""Tanner graph of this code."""
return self.matrix_to_graph(self.matrix)
@classmethod
@abc.abstractmethod
def matrix_to_graph(cls, matrix: npt.NDArray[np.int_] | Sequence[Sequence[int]]) -> nx.DiGraph:
"""Convert a parity check matrix into a Tanner graph."""
@classmethod
@abc.abstractmethod
def graph_to_matrix(cls, graph: nx.DiGraph) -> galois.FieldArray:
"""Convert a Tanner graph into a parity check matrix."""
class ClassicalCode(AbstractCode):
"""Classical linear error-correcting code over a finite field F_q.
A classical binary code C = {x} is a set of vectors x (with entries in F_q) called code words.
We consider only linear codes, for which any linear combination of code words is also code word.
Operationally, we define a classical code by a parity check matrix H with dimensions
(num_checks, num_bits). Each row of H represents a linear constraint (a "check") that code
words must satisfy. A vector x is a code word iff H @ x = 0.
"""
def __contains__(self, word: npt.NDArray[np.int_] | Sequence[int]) -> bool:
return not np.any(self.matrix @ self.field(word))
@classmethod
def matrix_to_graph(cls, matrix: npt.NDArray[np.int_] | Sequence[Sequence[int]]) -> nx.DiGraph:
"""Convert a parity check matrix H into a Tanner graph.
The Tanner graph is a bipartite graph with (num_checks, num_bits) vertices, respectively
identified with the checks and bits of the code. The check vertex c and the bit vertex b
share an edge iff c addresses b; that is, edge (c, b) is in the graph iff H[c, b] != 0.
"""
graph = nx.DiGraph()
for row, col in zip(*np.nonzero(matrix)):
| """Error correction code constructions
Copyright 2023 The qLDPC Authors and Infleqtion Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import annotations
if TYPE_CHECKING:
DEFAULT_FIELD_ORDER = abstract.DEFAULT_FIELD_ORDER
################################################################################
# template error correction code classes
class AbstractCode(abc.ABC):
"""Template class for error-correcting codes."""
_field_order: int
def __init__(
self,
matrix: Self | npt.NDArray[np.int_] | Sequence[Sequence[int]],
field: int | None = None,
) -> None:
"""Construct a code from a parity check matrix over a finite field.
The base field is taken to be F_2 by default.
"""
self._matrix: galois.FieldArray
if isinstance(matrix, type(self)):
self._field_order = matrix.field.order
if not (field is None or field == self._field_order):
raise ValueError(
f"Field argument {field} is inconsistent with the given code, which is defined"
f" over F_{self._field_order}"
)
self._matrix = matrix.matrix
elif isinstance(matrix, galois.FieldArray):
self._field_order = type(matrix).order
self._matrix = matrix
else:
self._field_order = field or DEFAULT_FIELD_ORDER
self._matrix = self.field(np.array(matrix))
@property
def field(self) -> type[galois.FieldArray]:
"""Base field over which this code is defined."""
return galois.GF(self._field_order)
@property
def matrix(self) -> galois.FieldArray:
"""Parity check matrix of this code."""
return self._matrix
@functools.cached_property
def graph(self) -> nx.DiGraph:
"""Tanner graph of this code."""
return self.matrix_to_graph(self.matrix)
@classmethod
@abc.abstractmethod
def matrix_to_graph(cls, matrix: npt.NDArray[np.int_] | Sequence[Sequence[int]]) -> nx.DiGraph:
"""Convert a parity check matrix into a Tanner graph."""
@classmethod
@abc.abstractmethod
def graph_to_matrix(cls, graph: nx.DiGraph) -> galois.FieldArray:
"""Convert a Tanner graph into a parity check matrix."""
class ClassicalCode(AbstractCode):
"""Classical linear error-correcting code over a finite field F_q.
A classical binary code C = {x} is a set of vectors x (with entries in F_q) called code words.
We consider only linear codes, for which any linear combination of code words is also code word.
Operationally, we define a classical code by a parity check matrix H with dimensions
(num_checks, num_bits). Each row of H represents a linear constraint (a "check") that code
words must satisfy. A vector x is a code word iff H @ x = 0.
"""
def __contains__(self, word: npt.NDArray[np.int_] | Sequence[int]) -> bool:
return not np.any(self.matrix @ self.field(word))
@classmethod
def matrix_to_graph(cls, matrix: npt.NDArray[np.int_] | Sequence[Sequence[int]]) -> nx.DiGraph:
"""Convert a parity check matrix H into a Tanner graph.
The Tanner graph is a bipartite graph with (num_checks, num_bits) vertices, respectively
identified with the checks and bits of the code. The check vertex c and the bit vertex b
share an edge iff c addresses b; that is, edge (c, b) is in the graph iff H[c, b] != 0.
"""
graph = nx.DiGraph()
for row, col in zip(*np.nonzero(matrix)): | node_c = Node(index=int(row), is_data=False) | 2 | 2023-12-19 22:29:42+00:00 | 8k |
CosmicLaca/ComfyUI_Primere_Nodes | Nodes/modules/image_meta_reader.py | [
{
"identifier": "Automatic1111",
"path": "Nodes/modules/exif/automatic1111.py",
"snippet": "class Automatic1111(BaseFormat):\n def __init__(self, info: dict = None, raw: str = \"\"):\n super().__init__(info, raw)\n if not self._raw:\n self._raw = self._info.get(\"parameters\"... | import json
import piexif
import pyexiv2
import piexif.helper
from PIL import Image
from .exif.automatic1111 import Automatic1111
from .exif.primere import Primere
from .exif.comfyui import ComfyUI | 5,078 |
# OopCompanion:suppressRename
class ImageExifReader:
def __init__(self, file):
self._raw = ""
self._parser = {}
self._parameter = {}
self._tool = ""
self.read_data(file)
def read_data(self, file):
def is_json(jsoninput):
try:
json.loads(jsoninput)
except ValueError as e:
return False
return True
with Image.open(file) as f:
p2metadata = pyexiv2.Image(file)
is_primere = p2metadata.read_exif()
if 'Exif.Image.ImageDescription' in is_primere:
primere_exif_string = is_primere.get('Exif.Image.ImageDescription').strip()
if is_json(primere_exif_string) == True:
json_object = json.loads(primere_exif_string)
# keysList = {'positive', 'negative', 'positive_l', 'negative_l', 'positive_r', 'negative_r', 'seed', 'model_hash', 'model_name', 'sampler_name'}
# if not (keysList - json_object.keys()):
self._tool = "Primere"
|
# OopCompanion:suppressRename
class ImageExifReader:
def __init__(self, file):
self._raw = ""
self._parser = {}
self._parameter = {}
self._tool = ""
self.read_data(file)
def read_data(self, file):
def is_json(jsoninput):
try:
json.loads(jsoninput)
except ValueError as e:
return False
return True
with Image.open(file) as f:
p2metadata = pyexiv2.Image(file)
is_primere = p2metadata.read_exif()
if 'Exif.Image.ImageDescription' in is_primere:
primere_exif_string = is_primere.get('Exif.Image.ImageDescription').strip()
if is_json(primere_exif_string) == True:
json_object = json.loads(primere_exif_string)
# keysList = {'positive', 'negative', 'positive_l', 'negative_l', 'positive_r', 'negative_r', 'seed', 'model_hash', 'model_name', 'sampler_name'}
# if not (keysList - json_object.keys()):
self._tool = "Primere" | self._parser = Primere(info=json_object) | 1 | 2023-12-17 20:42:27+00:00 | 8k |
amazon-science/c2f-seg | train_vq.py | [
{
"identifier": "load_dataset",
"path": "data/dataloader_vqgan.py",
"snippet": "def load_dataset(args, config):\n if args.dataset==\"KINS\":\n train_dataset = KINS_VQ_dataset(config, mode='train')\n val_dataset = KINS_VQ_dataset(config, mode='test')\n elif args.dataset==\"MOViD_A\":\... | import os
import cv2
import random
import numpy as np
import torch
import argparse
import time
from shutil import copyfile
from torch.utils.data import DataLoader
from data.dataloader_vqgan import load_dataset
from utils.evaluation import get_IoU
from utils.logger import setup_logger
from utils.utils import Config, Progbar, to_cuda, stitch_images
from utils.utils import get_lr_schedule_with_steps, torch_init_model
from taming_src.vqperceptual import VQLPIPSWithDiscriminator, adopt_weight
from taming_src.taming_models import VQModel | 6,397 |
def restore(ckpt_file, g_model, d_model, g_opt, d_opt):
torch_init_model(g_model, ckpt_file, "g_model")
torch_init_model(d_model, ckpt_file, "d_model")
saving = torch.load(ckpt_file, map_location='cpu')
# if 'optimizer_states' in saving:
# opt_state = saving['optimizer_states']
# # print(opt_state[0])
# g_opt.load_state_dict(opt_state[0])
# d_opt.load_state_dict(opt_state[1])
print(f"Restored from {ckpt_file}")
return g_opt, d_opt
def save(g_model, d_model, m_path, prefix=None, g_opt=None, d_opt=None):
if prefix is not None:
save_path = m_path + "_{}.pth".format(prefix)
else:
save_path = m_path + ".pth"
print('\nsaving {}...\n'.format(save_path))
all_saving = {'g_model': g_model.state_dict(),
'd_model': d_model.state_dict(),
'optimizer_states': [g_opt.state_dict(), d_opt.state_dict()]}
torch.save(all_saving, save_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--path', type=str, required=True, help='model checkpoints path')
parser.add_argument('--finetune_path', type=str, required=False, default=None)
parser.add_argument('--local_rank', default=-1, type=int)
parser.add_argument('--learn_type', default="mask", type=str)
parser.add_argument('--check_point_path', default="../check_points", type=str)
parser.add_argument('--dataset', default="Kins", type=str)
args = parser.parse_args()
args.path = os.path.join(args.check_point_path, args.path)
config_path = os.path.join(args.path, 'vqgan_{}.yml'.format(args.dataset))
# create checkpoints path if does't exist
if not os.path.exists(args.path):
os.makedirs(args.path)
# copy config template if does't exist
if not os.path.exists(config_path):
copyfile('configs/vqgan_{}.yml'.format(args.dataset), config_path)
# load config file
config = Config(config_path)
config.path = args.path
# cuda visble devices
local_rank = 0
log_file = 'log-{}.txt'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
if local_rank == 0:
|
def restore(ckpt_file, g_model, d_model, g_opt, d_opt):
torch_init_model(g_model, ckpt_file, "g_model")
torch_init_model(d_model, ckpt_file, "d_model")
saving = torch.load(ckpt_file, map_location='cpu')
# if 'optimizer_states' in saving:
# opt_state = saving['optimizer_states']
# # print(opt_state[0])
# g_opt.load_state_dict(opt_state[0])
# d_opt.load_state_dict(opt_state[1])
print(f"Restored from {ckpt_file}")
return g_opt, d_opt
def save(g_model, d_model, m_path, prefix=None, g_opt=None, d_opt=None):
if prefix is not None:
save_path = m_path + "_{}.pth".format(prefix)
else:
save_path = m_path + ".pth"
print('\nsaving {}...\n'.format(save_path))
all_saving = {'g_model': g_model.state_dict(),
'd_model': d_model.state_dict(),
'optimizer_states': [g_opt.state_dict(), d_opt.state_dict()]}
torch.save(all_saving, save_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--path', type=str, required=True, help='model checkpoints path')
parser.add_argument('--finetune_path', type=str, required=False, default=None)
parser.add_argument('--local_rank', default=-1, type=int)
parser.add_argument('--learn_type', default="mask", type=str)
parser.add_argument('--check_point_path', default="../check_points", type=str)
parser.add_argument('--dataset', default="Kins", type=str)
args = parser.parse_args()
args.path = os.path.join(args.check_point_path, args.path)
config_path = os.path.join(args.path, 'vqgan_{}.yml'.format(args.dataset))
# create checkpoints path if does't exist
if not os.path.exists(args.path):
os.makedirs(args.path)
# copy config template if does't exist
if not os.path.exists(config_path):
copyfile('configs/vqgan_{}.yml'.format(args.dataset), config_path)
# load config file
config = Config(config_path)
config.path = args.path
# cuda visble devices
local_rank = 0
log_file = 'log-{}.txt'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
if local_rank == 0: | logger = setup_logger(os.path.join(args.path, 'logs'), logfile_name=log_file) | 2 | 2023-12-21 04:25:47+00:00 | 8k |
alipay/PainlessInferenceAcceleration | pia/lookahead/common/pretrained_model.py | [
{
"identifier": "LookaheadCache",
"path": "pia/lookahead/common/lookahead_cache.py",
"snippet": "class LookaheadCache():\n def __init__(self, debug=False, eos=2, stop_words=None, max_node=512, max_output_node=256):\n self.debug = debug\n self.eos = eos\n self.max_node = max_node\... | import copy
import inspect
import time
import warnings
import numpy as np
import torch
import torch.distributed as dist
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
from torch import nn
from transformers import PreTrainedModel
from transformers.generation.beam_constraints import DisjunctiveConstraint, PhrasalConstraint
from transformers.generation.beam_search import BeamSearchScorer, ConstrainedBeamSearchScorer
from transformers.generation.logits_process import (
LogitsProcessorList,
MinLengthLogitsProcessor,
)
from transformers.generation.stopping_criteria import (
MaxLengthCriteria,
StoppingCriteriaList,
validate_stopping_criteria,
)
from transformers.generation.utils import (
GreedySearchEncoderDecoderOutput,
GreedySearchDecoderOnlyOutput)
from transformers.generation.utils import (
GreedySearchOutput,
GenerateOutput)
from transformers.utils import ModelOutput, logging
from transformers.generation.configuration_utils import GenerationConfig
from pia.lookahead.common.lookahead_cache import LookaheadCache
from pia.lookahead.common.lookahead_generation_utils import GenerationMode, LookaheadDecoderOnlyOutput | 6,565 | input_id_list = input_ids[0].tolist()
decoding_kwargs['input_id_list'] = [input_id_list]
branch_length = decoding_kwargs.get('branch_length', 12)
self.lookahead_cache.put(input_id_list[1:], branch_length=branch_length + 1, mode='input', idx=0)
ts = time.time()
this_peer_finished = False # used by synced_gpus only
while True:
if synced_gpus:
# Under synced_gpus the `forward` call must continue until all gpus complete their sequence.
# The following logic allows an early break if all peers finished generating their sequence
this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(input_ids.device)
# send 0.0 if we finished, 1.0 otherwise
dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM)
# did all peers finish? the reduced sum will be 0.0 then
if this_peer_finished_flag.item() == 0.0:
break
# prepare model inputs
model_inputs = self.lookahead_prepare_inputs_for_generation(input_ids, **model_kwargs)
decoding_kwargs = model_inputs.pop('decoding_kwargs', {})
# forward pass to get next token
outputs = self(
**model_inputs,
return_dict=True,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
if synced_gpus and this_peer_finished:
continue # don't waste resources running the code we don't need
model_kwargs['decoding_kwargs'] = decoding_kwargs
model_kwargs = self._lookahead_update_model_kwargs_for_generation(
outputs,
model_kwargs,
is_encoder_decoder=self.config.is_encoder_decoder,
input_ids=input_ids,
logits_processor=logits_processor
)
next_tokens = model_kwargs['next_tokens']
next_tokens_scores = model_kwargs['next_tokens_scores']
next_token_list = model_kwargs['next_token_list']
# finished sentences should have their next token be a padding token
if eos_token_id is not None:
if pad_token_id is None:
raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
# update generated ids, model inputs, and length for next step
input_ids = torch.cat([input_ids, next_tokens], dim=-1)
if streamer is not None:
streamer.put(next_token_list)
self.lookahead_cache.stream_put(next_token_list[0], branch_length=branch_length + 1, final=False,
mode='output', idx=0)
# Store scores, attentions and hidden_states when required
if return_dict_in_generate:
if output_scores:
scores += (next_tokens_scores,)
if output_attentions:
decoder_attentions += (
(outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
)
if self.config.is_encoder_decoder:
cross_attentions += (outputs.cross_attentions,)
if output_hidden_states:
decoder_hidden_states += (
(outputs.decoder_hidden_states,)
if self.config.is_encoder_decoder
else (outputs.hidden_states,)
)
# if eos_token was found in one sentence, set sentence to finished
if eos_token_id_tensor is not None:
# unfinished_sequences = unfinished_sequences.mul(
# next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
# )
unfinished_sequences = unfinished_sequences.mul(
next_tokens[:, :, None].ne(eos_token_id_tensor).prod(dim=2).prod(dim=1))
# stop when each sentence is finished
if unfinished_sequences.max() == 0:
this_peer_finished = True
# stop if we exceed the maximum length
if stopping_criteria(input_ids, scores):
this_peer_finished = True
te = time.time()
model_kwargs['decoding_kwargs']['fts'].append(te - ts)
ts = te
if this_peer_finished and not synced_gpus:
self.lookahead_cache.stream_put([], branch_length=branch_length + 1, final=True,
mode='output', idx=0)
break
if streamer is not None:
streamer.end()
if return_dict_in_generate:
if self.config.is_encoder_decoder:
return GreedySearchEncoderDecoderOutput(
sequences=input_ids,
scores=scores,
encoder_attentions=encoder_attentions,
encoder_hidden_states=encoder_hidden_states,
decoder_attentions=decoder_attentions,
cross_attentions=cross_attentions,
decoder_hidden_states=decoder_hidden_states,
)
else:
kwargs = {'dls': model_kwargs['decoding_kwargs']['dls'],
'edls': model_kwargs['decoding_kwargs']['edls'],
'fts': model_kwargs['decoding_kwargs']['fts']}
| # -*- coding: utf-8 -*-
"""
Copyright (c) Ant Financial Service Group and its affiliates.
"""
from __future__ import print_function
# from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
logger = logging.get_logger(__name__)
class LookaheadPreTrainedModel(PreTrainedModel):
_batch_generation = False
_stream_generation = False
def __init__(self, config):
super().__init__(config=config)
def _get_generation_mode(
self, generation_config: GenerationConfig, assistant_model: Optional["PreTrainedModel"]
) -> GenerationMode:
"""
Returns the generation mode triggered by a [`GenerationConfig`] instance.
"""
if generation_config.constraints is not None or generation_config.force_words_ids is not None:
generation_mode = GenerationMode.CONSTRAINED_BEAM_SEARCH
elif generation_config.num_beams == 1:
if generation_config.do_sample is False:
if (
generation_config.top_k is not None
and generation_config.top_k > 1
and generation_config.penalty_alpha is not None
and generation_config.penalty_alpha > 0
):
generation_mode = GenerationMode.CONTRASTIVE_SEARCH
elif generation_config.use_cache \
and hasattr(generation_config, 'decoding_kwargs') \
and generation_config.decoding_kwargs.get('use_lookahead', False) \
and generation_config.decoding_kwargs.get('decoding_length', 64) > 1 \
and generation_config.decoding_kwargs.get('branch_length', 12) > 0:
generation_mode = GenerationMode.LOOKAHEAD_GENERATION
else:
generation_mode = GenerationMode.GREEDY_SEARCH
else:
if generation_config.use_cache \
and hasattr(generation_config, 'decoding_kwargs') \
and generation_config.decoding_kwargs.get('use_lookahead', False) \
and generation_config.decoding_kwargs.get('decoding_length', 64) > 1 \
and generation_config.decoding_kwargs.get('branch_length', 12) > 0:
generation_mode = GenerationMode.LOOKAHEAD_GENERATION
else:
generation_mode = GenerationMode.SAMPLE
else:
if generation_config.num_beam_groups > 1:
generation_mode = GenerationMode.GROUP_BEAM_SEARCH
elif generation_config.do_sample is True:
generation_mode = GenerationMode.BEAM_SAMPLE
else:
generation_mode = GenerationMode.BEAM_SEARCH
# Assisted generation may extend some generation modes
if assistant_model is not None:
if generation_mode in ("greedy_search", "sample"):
generation_mode = GenerationMode.ASSISTED_GENERATION
else:
raise ValueError(
"You've set `assistant_model`, which triggers assisted generate. Currently, assisted generate "
"is only supported with Greedy Search and Sample."
)
return generation_mode
@torch.no_grad()
def generate(
self,
inputs: Optional[torch.Tensor] = None,
generation_config: Optional[GenerationConfig] = None,
logits_processor: Optional[LogitsProcessorList] = None,
stopping_criteria: Optional[StoppingCriteriaList] = None,
prefix_allowed_tokens_fn: Optional[Callable[[int, torch.Tensor], List[int]]] = None,
synced_gpus: Optional[bool] = None,
assistant_model: Optional["PreTrainedModel"] = None,
streamer: Optional["BaseStreamer"] = None,
**kwargs,
) -> Union[GenerateOutput, torch.LongTensor]:
r"""
Generates sequences of token ids for models with a language modeling head.
<Tip warning={true}>
Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the
model's default generation configuration. You can override any `generation_config` by passing the corresponding
parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`.
For an overview of generation strategies and code examples, check out the [following
guide](../generation_strategies).
</Tip>
Parameters:
inputs (`torch.Tensor` of varying shape depending on the modality, *optional*):
The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the
method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs`
should of in the format of `input_ids`. For encoder-decoder models *inputs* can represent any of
`input_ids`, `input_values`, `input_features`, or `pixel_values`.
generation_config (`~generation.GenerationConfig`, *optional*):
The generation configuration to be used as base parametrization for the generation call. `**kwargs`
passed to generate matching the attributes of `generation_config` will override them. If
`generation_config` is not provided, the default will be used, which had the following loading
priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model
configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s
default values, whose documentation should be checked to parameterize generation.
logits_processor (`LogitsProcessorList`, *optional*):
Custom logits processors that complement the default logits processors built from arguments and
generation config. If a logit processor is passed that is already created with the arguments or a
generation config an error is thrown. This feature is intended for advanced users.
stopping_criteria (`StoppingCriteriaList`, *optional*):
Custom stopping criteria that complement the default stopping criteria built from arguments and a
generation config. If a stopping criteria is passed that is already created with the arguments or a
generation config an error is thrown. This feature is intended for advanced users.
prefix_allowed_tokens_fn (`Callable[[int, torch.Tensor], List[int]]`, *optional*):
If provided, this function constraints the beam search to allowed tokens only at each step. If not
provided no constraint is applied. This function takes 2 arguments: the batch ID `batch_id` and
`input_ids`. It has to return a list with the allowed tokens for the next generation step conditioned
on the batch ID `batch_id` and the previously generated tokens `inputs_ids`. This argument is useful
for constrained generation conditioned on the prefix, as described in [Autoregressive Entity
Retrieval](https://arxiv.org/abs/2010.00904).
synced_gpus (`bool`, *optional*):
Whether to continue running the while loop until max_length. Unless overridden this flag will be set to
`True` under DeepSpeed ZeRO Stage 3 multiple GPUs environment to avoid hanging if one GPU finished
generating before other GPUs. Otherwise it'll be set to `False`.
assistant_model (`PreTrainedModel`, *optional*):
An assistant model that can be used to accelerate generation. The assistant model must have the exact
same tokenizer. The acceleration is achieved when forecasting candidate tokens with the assistent model
is much faster than running generation with the model you're calling generate from. As such, the
assistant model should be much smaller.
streamer (`BaseStreamer`, *optional*):
Streamer object that will be used to stream the generated sequences. Generated tokens are passed
through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
kwargs (`Dict[str, Any]`, *optional*):
Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be
forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder
specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*.
Return:
[`~utils.ModelOutput`] or `torch.LongTensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True`
or when `config.return_dict_in_generate=True`) or a `torch.FloatTensor`.
If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible
[`~utils.ModelOutput`] types are:
- [`~generation.GreedySearchDecoderOnlyOutput`],
- [`~generation.SampleDecoderOnlyOutput`],
- [`~generation.BeamSearchDecoderOnlyOutput`],
- [`~generation.BeamSampleDecoderOnlyOutput`]
If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible
[`~utils.ModelOutput`] types are:
- [`~generation.GreedySearchEncoderDecoderOutput`],
- [`~generation.SampleEncoderDecoderOutput`],
- [`~generation.BeamSearchEncoderDecoderOutput`],
- [`~generation.BeamSampleEncoderDecoderOutput`]
"""
if synced_gpus is None:
# if is_deepspeed_zero3_enabled() and dist.get_world_size() > 1:
# synced_gpus = True
# else:
# synced_gpus = False
synced_gpus = False
# 1. Handle `generation_config` and kwargs that might update it, and validate the `.generate()` call
self._validate_model_class()
# priority: `generation_config` argument > `model.generation_config` (the default generation config)
if generation_config is None:
# legacy: users may modify the model configuration to control generation -- update the generation config
# model attribute accordingly, if it was created from the model config
if self.generation_config._from_model_config:
new_generation_config = GenerationConfig.from_model_config(self.config)
if new_generation_config != self.generation_config:
# warnings.warn(
# "You have modified the pretrained model configuration to control generation. This is a"
# " deprecated strategy to control generation and will be removed soon, in a future version."
# " Please use a generation configuration file (see"
# " https://huggingface.co/docs/transformers/main_classes/text_generation )"
# )
self.generation_config = new_generation_config
generation_config = self.generation_config
generation_config = copy.deepcopy(generation_config)
model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs
generation_config.validate()
self._validate_model_kwargs(model_kwargs.copy())
if not hasattr(generation_config, 'decoding_kwargs'):
generation_config.decoding_kwargs = model_kwargs.get('decoding_kwargs', {})
# 2. Set generation parameters if not already defined
logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
if generation_config.pad_token_id is None and generation_config.eos_token_id is not None:
if model_kwargs.get("attention_mask", None) is None:
logger.warning(
"The attention mask and the pad token id were not set. As a consequence, you may observe "
"unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results."
)
eos_token_id = generation_config.eos_token_id
if isinstance(eos_token_id, list):
eos_token_id = eos_token_id[0]
logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{eos_token_id} for open-end generation.")
generation_config.pad_token_id = eos_token_id
# 3. Define model inputs
# inputs_tensor has to be defined
# model_input_name is defined if model-specific keyword input is passed
# otherwise model_input_name is None
# all model-specific keyword inputs are removed from `model_kwargs`
inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs(
inputs, generation_config.bos_token_id, model_kwargs
)
batch_size = inputs_tensor.shape[0]
# 4. Define other model kwargs
model_kwargs["output_attentions"] = generation_config.output_attentions
model_kwargs["output_hidden_states"] = generation_config.output_hidden_states
# decoder-only models with inputs_embeds forwarding must use caching (otherwise we can't detect whether we are
# generating the first new token or not, and we only want to use the embeddings for the first new token)
if not self.config.is_encoder_decoder and model_input_name == "inputs_embeds":
model_kwargs["use_cache"] = True
else:
model_kwargs["use_cache"] = generation_config.use_cache
accepts_attention_mask = "attention_mask" in set(inspect.signature(self.forward).parameters.keys())
requires_attention_mask = "encoder_outputs" not in model_kwargs
if model_kwargs.get("attention_mask", None) is None and requires_attention_mask and accepts_attention_mask:
model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation(
inputs_tensor, generation_config.pad_token_id, generation_config.eos_token_id
)
# decoder-only models should use left-padding for generation
if not self.config.is_encoder_decoder:
# If `input_ids` was given, check if the last id in any sequence is `pad_token_id`
# Note: If using, `inputs_embeds` this check does not work, because we want to be more hands-off.
if (
generation_config.pad_token_id is not None
and len(inputs_tensor.shape) == 2
and torch.sum(inputs_tensor[:, -1] == generation_config.pad_token_id) > 0
):
logger.warning(
"A decoder-only architecture is being used, but right-padding was detected! For correct "
"generation results, please set `padding_side='left'` when initializing the tokenizer."
)
if self.config.is_encoder_decoder and "encoder_outputs" not in model_kwargs:
# if model is encoder decoder encoder_outputs are created
# and added to `model_kwargs`
model_kwargs = self._prepare_encoder_decoder_kwargs_for_generation(
inputs_tensor, model_kwargs, model_input_name
)
# 5. Prepare `input_ids` which will be used for auto-regressive generation
if self.config.is_encoder_decoder:
input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation(
batch_size=batch_size,
model_input_name=model_input_name,
model_kwargs=model_kwargs,
decoder_start_token_id=generation_config.decoder_start_token_id,
bos_token_id=generation_config.bos_token_id,
device=inputs_tensor.device,
)
else:
input_ids = inputs_tensor if model_input_name == "input_ids" else model_kwargs.pop("input_ids")
if streamer is not None:
streamer.put(input_ids.cpu())
# 6. Prepare `max_length` depending on other stopping criteria.
input_ids_length = input_ids.shape[-1]
has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None
if generation_config.max_new_tokens is not None:
if not has_default_max_length:
logger.warning(
f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(="
f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. "
"Please refer to the documentation for more information. "
"(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)"
)
generation_config.max_length = generation_config.max_new_tokens + input_ids_length
# 7. determine generation mode
generation_mode = self._get_generation_mode(generation_config, assistant_model)
if streamer is not None and (generation_config.num_beams > 1):
raise ValueError(
"`streamer` cannot be used with beam search (yet!). Make sure that `num_beams` is set to 1."
)
if self.device.type != input_ids.device.type:
warnings.warn(
"You are calling .generate() with the `input_ids` being on a device type different"
f" than your model's device. `input_ids` is on {input_ids.device.type}, whereas the model"
f" is on {self.device.type}. You may experience unexpected behaviors or slower generation."
" Please make sure that you have put `input_ids` to the"
f" correct device by calling for example input_ids = input_ids.to('{self.device.type}') before"
" running `.generate()`.",
UserWarning,
)
# 8. prepare distribution pre_processing samplers
logits_processor = self._get_logits_processor(
generation_config=generation_config,
input_ids_seq_length=input_ids_length,
encoder_input_ids=inputs_tensor,
prefix_allowed_tokens_fn=prefix_allowed_tokens_fn,
logits_processor=logits_processor,
)
# 9. prepare stopping criteria
stopping_criteria = self._get_stopping_criteria(
generation_config=generation_config, stopping_criteria=stopping_criteria
)
decoding_kwargs = generation_config.decoding_kwargs if hasattr(generation_config, 'decoding_kwargs') else {}
decoding_kwargs['generation_mode'] = generation_mode
decoding_kwargs['do_sample'] = generation_config.do_sample
decoding_kwargs['inputs_embeds_position'] = generation_config.inputs_embeds_position if hasattr(generation_config, 'inputs_embeds_position') else 0
decoding_kwargs['max_length'] = generation_config.max_length
if generation_mode == GenerationMode.LOOKAHEAD_GENERATION:
decoding_length = decoding_kwargs.get('decoding_length', 64)
decoding_kwargs['decoding_max_length'] = generation_config.max_length + decoding_length + 1
else:
decoding_kwargs['decoding_max_length'] = generation_config.max_length
model_kwargs['decoding_kwargs'] = decoding_kwargs
# 10. go into different generation modes
if generation_mode == GenerationMode.ASSISTED_GENERATION:
if generation_config.num_return_sequences > 1:
raise ValueError(
"num_return_sequences has to be 1 when doing assisted generate, "
f"but is {generation_config.num_return_sequences}."
)
if batch_size > 1:
raise ValueError("assisted generate is only supported for batch_size = 1")
if not model_kwargs["use_cache"]:
raise ValueError("assisted generate requires `use_cache=True`")
# 11. If the assistant model is an encoder-decoder, prepare its encoder outputs
if assistant_model.config.is_encoder_decoder:
assistant_model_kwargs = copy.deepcopy(model_kwargs)
inputs_tensor, model_input_name, assistant_model_kwargs = assistant_model._prepare_model_inputs(
inputs_tensor, assistant_model.generation_config.bos_token_id, assistant_model_kwargs
)
assistant_model_kwargs = assistant_model._prepare_encoder_decoder_kwargs_for_generation(
inputs_tensor, assistant_model_kwargs, model_input_name
)
model_kwargs["assistant_encoder_outputs"] = assistant_model_kwargs["encoder_outputs"]
# 12. run assisted generate
return self.assisted_decoding(
input_ids,
assistant_model=assistant_model,
do_sample=generation_config.do_sample,
logits_processor=logits_processor,
logits_warper=self._get_logits_warper(generation_config) if generation_config.do_sample else None,
stopping_criteria=stopping_criteria,
pad_token_id=generation_config.pad_token_id,
eos_token_id=generation_config.eos_token_id,
output_scores=generation_config.output_scores,
return_dict_in_generate=generation_config.return_dict_in_generate,
synced_gpus=synced_gpus,
streamer=streamer,
**model_kwargs,
)
if generation_mode == GenerationMode.GREEDY_SEARCH:
# 11. run greedy search
return self.greedy_search(
input_ids,
logits_processor=logits_processor,
stopping_criteria=stopping_criteria,
pad_token_id=generation_config.pad_token_id,
eos_token_id=generation_config.eos_token_id,
output_scores=generation_config.output_scores,
return_dict_in_generate=generation_config.return_dict_in_generate,
synced_gpus=synced_gpus,
streamer=streamer,
**model_kwargs,
)
elif generation_mode == GenerationMode.LOOKAHEAD_GENERATION:
# 11. run greedy search
return self.lookahead_generation(
input_ids,
logits_processor=logits_processor,
stopping_criteria=stopping_criteria,
pad_token_id=generation_config.pad_token_id,
eos_token_id=generation_config.eos_token_id,
output_scores=generation_config.output_scores,
return_dict_in_generate=generation_config.return_dict_in_generate,
synced_gpus=synced_gpus,
streamer=streamer,
**model_kwargs,
)
elif generation_mode == GenerationMode.CONTRASTIVE_SEARCH:
if not model_kwargs["use_cache"]:
raise ValueError("Contrastive search requires `use_cache=True`")
return self.contrastive_search(
input_ids,
top_k=generation_config.top_k,
penalty_alpha=generation_config.penalty_alpha,
logits_processor=logits_processor,
stopping_criteria=stopping_criteria,
pad_token_id=generation_config.pad_token_id,
eos_token_id=generation_config.eos_token_id,
output_scores=generation_config.output_scores,
return_dict_in_generate=generation_config.return_dict_in_generate,
synced_gpus=synced_gpus,
streamer=streamer,
sequential=generation_config.low_memory,
**model_kwargs,
)
elif generation_mode == GenerationMode.SAMPLE:
# 11. prepare logits warper
logits_warper = self._get_logits_warper(generation_config)
# 12. expand input_ids with `num_return_sequences` additional sequences per batch
input_ids, model_kwargs = self._expand_inputs_for_generation(
input_ids=input_ids,
expand_size=generation_config.num_return_sequences,
is_encoder_decoder=self.config.is_encoder_decoder,
**model_kwargs,
)
# 13. run sample
return self.sample(
input_ids,
logits_processor=logits_processor,
logits_warper=logits_warper,
stopping_criteria=stopping_criteria,
pad_token_id=generation_config.pad_token_id,
eos_token_id=generation_config.eos_token_id,
output_scores=generation_config.output_scores,
return_dict_in_generate=generation_config.return_dict_in_generate,
synced_gpus=synced_gpus,
streamer=streamer,
**model_kwargs,
)
elif generation_mode == GenerationMode.BEAM_SEARCH:
# 11. prepare beam search scorer
beam_scorer = BeamSearchScorer(
batch_size=batch_size,
num_beams=generation_config.num_beams,
device=inputs_tensor.device,
length_penalty=generation_config.length_penalty,
do_early_stopping=generation_config.early_stopping,
num_beam_hyps_to_keep=generation_config.num_return_sequences,
max_length=generation_config.max_length,
)
# 12. interleave input_ids with `num_beams` additional sequences per batch
input_ids, model_kwargs = self._expand_inputs_for_generation(
input_ids=input_ids,
expand_size=generation_config.num_beams,
is_encoder_decoder=self.config.is_encoder_decoder,
**model_kwargs,
)
# 13. run beam search
return self.beam_search(
input_ids,
beam_scorer,
logits_processor=logits_processor,
stopping_criteria=stopping_criteria,
pad_token_id=generation_config.pad_token_id,
eos_token_id=generation_config.eos_token_id,
output_scores=generation_config.output_scores,
return_dict_in_generate=generation_config.return_dict_in_generate,
synced_gpus=synced_gpus,
**model_kwargs,
)
elif generation_mode == GenerationMode.BEAM_SAMPLE:
# 11. prepare logits warper
logits_warper = self._get_logits_warper(generation_config)
# 12. prepare beam search scorer
beam_scorer = BeamSearchScorer(
batch_size=batch_size,
num_beams=generation_config.num_beams,
device=inputs_tensor.device,
length_penalty=generation_config.length_penalty,
do_early_stopping=generation_config.early_stopping,
num_beam_hyps_to_keep=generation_config.num_return_sequences,
max_length=generation_config.max_length,
)
# 13. interleave input_ids with `num_beams` additional sequences per batch
input_ids, model_kwargs = self._expand_inputs_for_generation(
input_ids=input_ids,
expand_size=generation_config.num_beams,
is_encoder_decoder=self.config.is_encoder_decoder,
**model_kwargs,
)
# 14. run beam sample
return self.beam_sample(
input_ids,
beam_scorer,
logits_processor=logits_processor,
logits_warper=logits_warper,
stopping_criteria=stopping_criteria,
pad_token_id=generation_config.pad_token_id,
eos_token_id=generation_config.eos_token_id,
output_scores=generation_config.output_scores,
return_dict_in_generate=generation_config.return_dict_in_generate,
synced_gpus=synced_gpus,
**model_kwargs,
)
elif generation_mode == GenerationMode.GROUP_BEAM_SEARCH:
# 11. prepare beam search scorer
beam_scorer = BeamSearchScorer(
batch_size=batch_size,
num_beams=generation_config.num_beams,
device=inputs_tensor.device,
length_penalty=generation_config.length_penalty,
do_early_stopping=generation_config.early_stopping,
num_beam_hyps_to_keep=generation_config.num_return_sequences,
num_beam_groups=generation_config.num_beam_groups,
max_length=generation_config.max_length,
)
# 12. interleave input_ids with `num_beams` additional sequences per batch
input_ids, model_kwargs = self._expand_inputs_for_generation(
input_ids=input_ids,
expand_size=generation_config.num_beams,
is_encoder_decoder=self.config.is_encoder_decoder,
**model_kwargs,
)
# 13. run beam search
return self.group_beam_search(
input_ids,
beam_scorer,
logits_processor=logits_processor,
stopping_criteria=stopping_criteria,
pad_token_id=generation_config.pad_token_id,
eos_token_id=generation_config.eos_token_id,
output_scores=generation_config.output_scores,
return_dict_in_generate=generation_config.return_dict_in_generate,
synced_gpus=synced_gpus,
**model_kwargs,
)
elif generation_mode == GenerationMode.CONSTRAINED_BEAM_SEARCH:
final_constraints = []
if generation_config.constraints is not None:
final_constraints = generation_config.constraints
if generation_config.force_words_ids is not None:
def typeerror():
raise ValueError(
"`force_words_ids` has to either be a `List[List[List[int]]]` or `List[List[int]]`"
f"of positive integers, but is {generation_config.force_words_ids}."
)
if (
not isinstance(generation_config.force_words_ids, list)
or len(generation_config.force_words_ids) == 0
):
typeerror()
for word_ids in generation_config.force_words_ids:
if isinstance(word_ids[0], list):
if not isinstance(word_ids, list) or len(word_ids) == 0:
typeerror()
if any(not isinstance(token_ids, list) for token_ids in word_ids):
typeerror()
if any(
any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids)
for token_ids in word_ids
):
typeerror()
constraint = DisjunctiveConstraint(word_ids)
else:
if not isinstance(word_ids, list) or len(word_ids) == 0:
typeerror()
if any((not isinstance(token_id, int) or token_id < 0) for token_id in word_ids):
typeerror()
constraint = PhrasalConstraint(word_ids)
final_constraints.append(constraint)
# 11. prepare beam search scorer
constrained_beam_scorer = ConstrainedBeamSearchScorer(
constraints=final_constraints,
batch_size=batch_size,
num_beams=generation_config.num_beams,
device=inputs_tensor.device,
length_penalty=generation_config.length_penalty,
do_early_stopping=generation_config.early_stopping,
num_beam_hyps_to_keep=generation_config.num_return_sequences,
max_length=generation_config.max_length,
)
# 12. interleave input_ids with `num_beams` additional sequences per batch
input_ids, model_kwargs = self._expand_inputs_for_generation(
input_ids=input_ids,
expand_size=generation_config.num_beams,
is_encoder_decoder=self.config.is_encoder_decoder,
**model_kwargs,
)
# 13. run beam search
return self.constrained_beam_search(
input_ids,
constrained_beam_scorer=constrained_beam_scorer,
logits_processor=logits_processor,
stopping_criteria=stopping_criteria,
pad_token_id=generation_config.pad_token_id,
eos_token_id=generation_config.eos_token_id,
output_scores=generation_config.output_scores,
return_dict_in_generate=generation_config.return_dict_in_generate,
synced_gpus=synced_gpus,
**model_kwargs,
)
def lookahead_prepare_inputs_for_generation(self,
input_ids,
past_key_values=None,
attention_mask=None,
inputs_embeds=None,
**kwargs):
position_ids = kwargs.get("position_ids", None)
decoding_kwargs = kwargs.get('decoding_kwargs', {})
decoding_length = decoding_kwargs.get('decoding_length', 64)
branch_length = decoding_kwargs.get('branch_length', 12)
decoding_mode = decoding_kwargs.get('decoding_mode', 'hier')
max_length = decoding_kwargs.get('max_length', 2048)
update_branch_length = min(branch_length, max_length - input_ids.size(-1))
assert update_branch_length > 0, f'{branch_length=} {max_length=} {input_ids.size(-1)=} {update_branch_length=}'
if past_key_values is None:
if inputs_embeds is not None and input_ids is not None:
model_inputs = {"inputs_embeds": inputs_embeds, "input_ids": input_ids}
length = input_ids.size(1)
elif input_ids is not None:
model_inputs = {"input_ids": input_ids}
length = input_ids.size(1)
elif inputs_embeds is not None:
model_inputs = {"inputs_embeds": inputs_embeds}
length = input_ids.size(1)
else:
raise ValueError('either input_ids or inputs_embeds is not None')
update_attention_mask = attention_mask[:, :, :length, :length]
model_inputs.update(
{"past_key_values": past_key_values,
"use_cache": kwargs.get("use_cache"),
"attention_mask": update_attention_mask,
"decoding_kwargs": decoding_kwargs
})
if position_ids is not None:
model_inputs["position_ids"] = self._get_position_ids(position_ids, encoding=True, length=length)
else:
decoding_qids = input_ids[0, -2:].tolist()
# decoding_qids = decoding_kwargs['input_id_list'][0][-2:]
min_input_size = 0
min_output_size = max(decoding_length // 2, 1)
if decoding_mode in ('hier', 'par', 'one'):
decoding_mode = decoding_mode + '_mix'
fmt, mode = decoding_mode.split('_')
method_name = fmt + '_get'
decoding_ids, decoding_masks, sizes = getattr(self.lookahead_cache, method_name)(decoding_qids,
decoding_length=decoding_length,
branch_length=update_branch_length,
min_input_size=min_input_size,
min_output_size=min_output_size,
mode=mode,
idx=0)
decoding_input_ids = torch.tensor([decoding_ids], dtype=torch.long, device=input_ids.device)
prefix_length = input_ids.size(-1) - 1
fresh_length = len(decoding_ids)
ppl = prefix_length + fresh_length
assert ppl <= attention_mask.size(2), \
f'{max_length=} {update_branch_length=} {prefix_length=} {fresh_length=} {attention_mask.shape=}'
prefix_mask_tensor = attention_mask[:, :, prefix_length:ppl, :prefix_length]
decoding_mask_tensor = torch.from_numpy(decoding_masks[None, None]).to(
dtype=attention_mask.dtype, device=attention_mask.device)
decoding_attention_mask = torch.cat([prefix_mask_tensor, decoding_mask_tensor], dim=3)
decoding_kwargs.update({'decoding_qids': decoding_qids,
'decoding_ids': decoding_ids,
'decoding_masks': decoding_masks,
'sizes': sizes,
})
model_inputs = {'decoding_kwargs': decoding_kwargs}
model_inputs.update(
{
"input_ids": decoding_input_ids,
"past_key_values": past_key_values,
"use_cache": kwargs.get("use_cache"),
"attention_mask": decoding_attention_mask
}
)
if position_ids is not None:
indices = torch.sum(decoding_attention_mask, dim=3).squeeze(1)[0]
model_inputs["position_ids"] = self._get_position_ids(position_ids, indices=indices, encoding=False)
return model_inputs
def _get_position_ids(self, full_position_ids, indices=None, length=None, encoding=True):
if encoding:
return full_position_ids[..., :length]
else:
return full_position_ids[..., indices]
def _lookahead_update_model_kwargs_for_generation(
self,
outputs: ModelOutput,
model_kwargs: Dict[str, Any],
is_encoder_decoder: bool = False,
standardize_cache_format: bool = False,
logits_processor: Optional[LogitsProcessorList] = None,
input_ids: Optional[torch.Tensor] = None,
) -> Dict[str, Any]:
# update past_key_values
model_kwargs["past_key_values"] = self._extract_past_from_model_output(
outputs, standardize_cache_format=standardize_cache_format
)
decoding_kwargs = model_kwargs['decoding_kwargs']
decoding_ids = decoding_kwargs.get('decoding_ids', [])
if len(decoding_ids) <= 1:
next_token_logits = outputs.logits[:, -1:, :]
# pre-process distribution
# next_tokens_scores = logits_processor(input_ids, next_token_logits)
bs, nt, nv = next_token_logits.shape
next_tokens_scores = logits_processor(input_ids, next_token_logits.squeeze(1)).unsqueeze(1)
if decoding_kwargs.get('do_sample', False):
probs = nn.functional.softmax(next_tokens_scores, dim=-1)
next_tokens = torch.multinomial(probs.view(bs * nt, nv), num_samples=1).view(bs, nt)
else:
next_tokens = torch.argmax(next_tokens_scores, dim=-1, keepdim=False).long()
model_kwargs['next_tokens'] = next_tokens
model_kwargs['next_tokens_scores'] = next_tokens_scores
next_token_list = next_tokens.tolist()
model_kwargs['next_token_list'] = next_token_list
decoding_kwargs['input_id_list'][0].extend(next_token_list[0])
decoding_kwargs['dls'].append(1)
decoding_kwargs['edls'].append(1)
if decoding_kwargs.get('debug_lookahead', False):
decoding_qids = decoding_kwargs.get('decoding_qids', [])
print(f'size:0 query:{decoding_qids} next_token:{next_token_list[0]}')
else:
# TODO: accurate logit_processor
# next_tokens_scores = logits_processor(input_ids, outputs.logits)
bs, nt, nv = outputs.logits.shape
next_tokens_scores = logits_processor(input_ids.repeat(1, nt).view(bs * nt, -1),
outputs.logits.view(bs * nt, -1)).view(bs, nt, -1)
if decoding_kwargs.get('do_sample', False):
probs = nn.functional.softmax(next_tokens_scores, dim=-1)
bs, nt, nv = probs.shape
next_tokens = torch.multinomial(probs.view(bs * nt, nv), num_samples=1).view(bs, nt)
else:
next_tokens = torch.argmax(next_tokens_scores, dim=-1, keepdim=False).long()
next_token_list = next_tokens.tolist()[0]
decoding_ids = decoding_kwargs['decoding_ids'][1:]
decoding_mask = decoding_kwargs['decoding_masks']
sizes = decoding_kwargs['sizes']
max_match_index = 0
max_match_count = 0
max_decoding_ids_slice = None
max_next_token_slice = None
for i in range(len(decoding_ids)):
mask_indices = np.nonzero(decoding_mask[i + 1, 1:])[0]
decoding_ids_slice = [decoding_ids[j] for j in mask_indices]
next_token_slice = [next_token_list[0]] + [next_token_list[j + 1] for j in mask_indices]
c = len(decoding_ids_slice)
for j, p in enumerate(decoding_ids_slice):
if next_token_slice[j] != p:
c = j
break
if c > max_match_count:
max_match_count = c
max_match_index = i
if c >= max_match_count:
max_decoding_ids_slice = decoding_ids_slice
max_next_token_slice = next_token_slice
# if decoding_kwargs['eos'] in decoding_ids:
# max_match_count = 0
prefix_plus_count = input_ids.size(-1)
match_idx = np.nonzero(decoding_mask[max_match_index + 1, 1:])[0][:max_match_count]
if len(decoding_ids) != max_match_count:
past = model_kwargs["past_key_values"]
device = past[0][0].device
kv_idx = torch.tensor(match_idx + prefix_plus_count, dtype=torch.long, device=device)
model_kwargs["past_key_values"] = self._update_cache(past,
kv_idx,
prefix_and_next_count=prefix_plus_count,
max_match_count=max_match_count,
max_match_index=max_match_index)
next_token_list = [next_token_list[0:1] + [next_token_list[x + 1] for x in match_idx]]
next_tokens = torch.tensor(next_token_list, dtype=torch.long, device=input_ids.device)
model_kwargs['next_tokens'] = next_tokens
model_kwargs['next_token_list'] = next_token_list
decoding_kwargs['input_id_list'][0].extend(next_token_list[0])
decoding_kwargs['dls'].append(len(decoding_ids))
decoding_kwargs['edls'].append(max_match_count + 1)
if decoding_kwargs.get('debug_lookahead', False):
lengths = np.sum(decoding_mask, axis=1) - 1
l = np.concatenate([lengths[:-1][(lengths[1:] - lengths[:-1]) <= 0], lengths[-1:]], axis=0)
ls = ','.join(l.astype(np.str_))
decoding_qids = decoding_kwargs['decoding_qids']
size_str = ','.join([str(x) for x in sizes])
print(
f'decoding_length:{len(decoding_ids)+1} accept_length:{max_match_count+1} '
f'query:{decoding_qids} source:{size_str} lengths:{ls} index:{max_match_index} '
f'branch_token:{max_decoding_ids_slice} next_token:{max_next_token_slice}')
return model_kwargs
def _update_cache(self, past_key_values, kv_idx, prefix_and_next_count=None, max_match_count=None,
max_match_index=None):
update_past_key_values = []
for k, v in past_key_values:
if max_match_index + 1 == max_match_count:
k = k[:, :, :prefix_and_next_count + max_match_count]
v = v[:, :, :prefix_and_next_count + max_match_count]
else:
k = torch.concat([k[:, :, :prefix_and_next_count], k[:, :, kv_idx]], 2)
v = torch.concat([v[:, :, :prefix_and_next_count], v[:, :, kv_idx]], 2)
update_past_key_values.append((k, v))
return tuple(update_past_key_values)
def lookahead_generation(
self,
input_ids: torch.LongTensor,
logits_processor: Optional[LogitsProcessorList] = None,
stopping_criteria: Optional[StoppingCriteriaList] = None,
max_length: Optional[int] = None,
pad_token_id: Optional[int] = None,
eos_token_id: Optional[Union[int, List[int]]] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
output_scores: Optional[bool] = None,
return_dict_in_generate: Optional[bool] = None,
synced_gpus: bool = False,
streamer: Optional["BaseStreamer"] = None,
**model_kwargs,
) -> Union[GreedySearchOutput, torch.LongTensor]:
r"""
Generates sequences of token ids for models with a language modeling head using **greedy decoding** and can be
used for text-decoder, text-to-text, speech-to-text, and vision-to-text models.
<Tip warning={true}>
In most cases, you do not need to call [`~generation.GenerationMixin.greedy_search`] directly. Use generate()
instead. For an overview of generation strategies and code examples, check the [following
guide](../generation_strategies).
</Tip>
Parameters:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
The sequence used as a prompt for the generation.
logits_processor (`LogitsProcessorList`, *optional*):
An instance of [`LogitsProcessorList`]. List of instances of class derived from [`LogitsProcessor`]
used to modify the prediction scores of the language modeling head applied at each generation step.
stopping_criteria (`StoppingCriteriaList`, *optional*):
An instance of [`StoppingCriteriaList`]. List of instances of class derived from [`StoppingCriteria`]
used to tell if the generation loop should stop.
max_length (`int`, *optional*, defaults to 20):
**DEPRECATED**. Use `logits_processor` or `stopping_criteria` directly to cap the number of generated
tokens. The maximum length of the sequence to be generated.
pad_token_id (`int`, *optional*):
The id of the *padding* token.
eos_token_id (`Union[int, List[int]]`, *optional*):
The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
output_attentions (`bool`, *optional*, defaults to `False`):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more details.
output_hidden_states (`bool`, *optional*, defaults to `False`):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more details.
output_scores (`bool`, *optional*, defaults to `False`):
Whether or not to return the prediction scores. See `scores` under returned tensors for more details.
return_dict_in_generate (`bool`, *optional*, defaults to `False`):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
synced_gpus (`bool`, *optional*, defaults to `False`):
Whether to continue running the while loop until max_length (needed for ZeRO stage 3)
streamer (`BaseStreamer`, *optional*):
Streamer object that will be used to stream the generated sequences. Generated tokens are passed
through `streamer.put(token_ids)` and the streamer is responsible for any further processing.
model_kwargs:
Additional model specific keyword arguments will be forwarded to the `forward` function of the model.
If model is an encoder-decoder model the kwargs should include `encoder_outputs`.
Return:
[`~generation.GreedySearchDecoderOnlyOutput`], [`~generation.GreedySearchEncoderDecoderOutput`] or
`torch.LongTensor`: A `torch.LongTensor` containing the generated tokens (default behaviour) or a
[`~generation.GreedySearchDecoderOnlyOutput`] if `model.config.is_encoder_decoder=False` and
`return_dict_in_generate=True` or a [`~generation.GreedySearchEncoderDecoderOutput`] if
`model.config.is_encoder_decoder=True`.
Examples:
```python
>>> from transformers import (
... AutoTokenizer,
... AutoModelForCausalLM,
... LogitsProcessorList,
... MinLengthLogitsProcessor,
... StoppingCriteriaList,
... MaxLengthCriteria,
... )
>>> tokenizer = AutoTokenizer.from_pretrained("gpt2")
>>> model = AutoModelForCausalLM.from_pretrained("gpt2")
>>> # set pad_token_id to eos_token_id because GPT2 does not have a PAD token
>>> model.generation_config.pad_token_id = model.generation_config.eos_token_id
>>> input_prompt = "It might be possible to"
>>> input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids
>>> # instantiate logits processors
>>> logits_processor = LogitsProcessorList(
... [
... MinLengthLogitsProcessor(10, eos_token_id=model.generation_config.eos_token_id),
... ]
... )
>>> stopping_criteria = StoppingCriteriaList([MaxLengthCriteria(max_length=20)])
>>> outputs = model.greedy_search(
... input_ids, logits_processor=logits_processor, stopping_criteria=stopping_criteria
... )
>>> tokenizer.batch_decode(outputs, skip_special_tokens=True)
["It might be possible to get a better understanding of the nature of the problem, but it's not"]
```"""
# init values
if not hasattr(self, 'lookahead_cache'):
self.lookahead_cache = LookaheadCache()
logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList()
stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList()
if max_length is not None:
warnings.warn(
"`max_length` is deprecated in this function, use"
" `stopping_criteria=StoppingCriteriaList([MaxLengthCriteria(max_length=max_length)])` instead.",
UserWarning,
)
stopping_criteria = validate_stopping_criteria(stopping_criteria, max_length)
pad_token_id = pad_token_id if pad_token_id is not None else self.generation_config.pad_token_id
eos_token_id = eos_token_id if eos_token_id is not None else self.generation_config.eos_token_id
if isinstance(eos_token_id, int):
eos_token_id = [eos_token_id]
eos_token_id_tensor = torch.tensor(eos_token_id, device=input_ids.device) if eos_token_id is not None else None
output_scores = output_scores if output_scores is not None else self.generation_config.output_scores
output_attentions = (
output_attentions if output_attentions is not None else self.generation_config.output_attentions
)
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.generation_config.output_hidden_states
)
return_dict_in_generate = (
return_dict_in_generate
if return_dict_in_generate is not None
else self.generation_config.return_dict_in_generate
)
# init attention / hidden states / scores tuples
scores = () if (return_dict_in_generate and output_scores) else None
decoder_attentions = () if (return_dict_in_generate and output_attentions) else None
cross_attentions = () if (return_dict_in_generate and output_attentions) else None
decoder_hidden_states = () if (return_dict_in_generate and output_hidden_states) else None
# if model is an encoder-decoder, retrieve encoder attention weights and hidden states
if return_dict_in_generate and self.config.is_encoder_decoder:
encoder_attentions = model_kwargs["encoder_outputs"].get("attentions") if output_attentions else None
encoder_hidden_states = (
model_kwargs["encoder_outputs"].get("hidden_states") if output_hidden_states else None
)
decoding_kwargs = model_kwargs['decoding_kwargs']
decoding_kwargs.update({
'eos': eos_token_id[0] if eos_token_id is not None else 2,
'edls': [],
'dls': [],
'fts': []
})
decoding_length = decoding_kwargs.get('decoding_length', 64)
stop_max_length = stopping_criteria.max_length
decoding_max_length = stop_max_length + decoding_length + 1
attention_mask = model_kwargs.get('attention_mask', None)
input_device = input_ids.device
if attention_mask is None:
bs = input_ids.size(0)
full_attention_mask = torch.tril(
torch.ones((bs, 1, decoding_max_length, decoding_max_length), dtype=torch.long, device=input_device),
0)
elif len(attention_mask.shape) == 2:
# from [bs, src_len] to [bs,1,max_len,max_len]
bs, src_len = attention_mask.shape
pad_len = decoding_max_length - src_len
attention_mask = attention_mask.long()
if pad_len > 0:
pad_mask = torch.ones((bs, pad_len), dtype=torch.long, device=attention_mask.device)
attention_mask = torch.cat([attention_mask, pad_mask], 1)
full_attention_mask = torch.tril(attention_mask[:, None, None].expand(-1, -1, decoding_max_length, -1), 0)
elif len(attention_mask.shape) == 4:
bs, _, src_len, tgt_len = attention_mask.shape
attention_mask = attention_mask.long()
if src_len < decoding_max_length or tgt_len < decoding_max_length:
full_attention_mask = torch.tril(
torch.ones((bs, 1, decoding_max_length, decoding_max_length), dtype=torch.long,
device=input_device),
0)
full_attention_mask[:, :, :src_len, :tgt_len] = attention_mask
else:
full_attention_mask = attention_mask
else:
raise ValueError(f'unsupport attention_mask.shape:{attention_mask.shape}')
model_kwargs['attention_mask'] = full_attention_mask
decoding_kwargs['max_length'] = stop_max_length
decoding_kwargs['decoding_max_length'] = decoding_max_length
# keep track of which sequences are already finished
unfinished_sequences = torch.ones(input_ids.shape[0], dtype=torch.long, device=input_ids.device)
assert input_ids.size(0) == 1
input_id_list = input_ids[0].tolist()
decoding_kwargs['input_id_list'] = [input_id_list]
branch_length = decoding_kwargs.get('branch_length', 12)
self.lookahead_cache.put(input_id_list[1:], branch_length=branch_length + 1, mode='input', idx=0)
ts = time.time()
this_peer_finished = False # used by synced_gpus only
while True:
if synced_gpus:
# Under synced_gpus the `forward` call must continue until all gpus complete their sequence.
# The following logic allows an early break if all peers finished generating their sequence
this_peer_finished_flag = torch.tensor(0.0 if this_peer_finished else 1.0).to(input_ids.device)
# send 0.0 if we finished, 1.0 otherwise
dist.all_reduce(this_peer_finished_flag, op=dist.ReduceOp.SUM)
# did all peers finish? the reduced sum will be 0.0 then
if this_peer_finished_flag.item() == 0.0:
break
# prepare model inputs
model_inputs = self.lookahead_prepare_inputs_for_generation(input_ids, **model_kwargs)
decoding_kwargs = model_inputs.pop('decoding_kwargs', {})
# forward pass to get next token
outputs = self(
**model_inputs,
return_dict=True,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
)
if synced_gpus and this_peer_finished:
continue # don't waste resources running the code we don't need
model_kwargs['decoding_kwargs'] = decoding_kwargs
model_kwargs = self._lookahead_update_model_kwargs_for_generation(
outputs,
model_kwargs,
is_encoder_decoder=self.config.is_encoder_decoder,
input_ids=input_ids,
logits_processor=logits_processor
)
next_tokens = model_kwargs['next_tokens']
next_tokens_scores = model_kwargs['next_tokens_scores']
next_token_list = model_kwargs['next_token_list']
# finished sentences should have their next token be a padding token
if eos_token_id is not None:
if pad_token_id is None:
raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.")
next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences)
# update generated ids, model inputs, and length for next step
input_ids = torch.cat([input_ids, next_tokens], dim=-1)
if streamer is not None:
streamer.put(next_token_list)
self.lookahead_cache.stream_put(next_token_list[0], branch_length=branch_length + 1, final=False,
mode='output', idx=0)
# Store scores, attentions and hidden_states when required
if return_dict_in_generate:
if output_scores:
scores += (next_tokens_scores,)
if output_attentions:
decoder_attentions += (
(outputs.decoder_attentions,) if self.config.is_encoder_decoder else (outputs.attentions,)
)
if self.config.is_encoder_decoder:
cross_attentions += (outputs.cross_attentions,)
if output_hidden_states:
decoder_hidden_states += (
(outputs.decoder_hidden_states,)
if self.config.is_encoder_decoder
else (outputs.hidden_states,)
)
# if eos_token was found in one sentence, set sentence to finished
if eos_token_id_tensor is not None:
# unfinished_sequences = unfinished_sequences.mul(
# next_tokens.tile(eos_token_id_tensor.shape[0], 1).ne(eos_token_id_tensor.unsqueeze(1)).prod(dim=0)
# )
unfinished_sequences = unfinished_sequences.mul(
next_tokens[:, :, None].ne(eos_token_id_tensor).prod(dim=2).prod(dim=1))
# stop when each sentence is finished
if unfinished_sequences.max() == 0:
this_peer_finished = True
# stop if we exceed the maximum length
if stopping_criteria(input_ids, scores):
this_peer_finished = True
te = time.time()
model_kwargs['decoding_kwargs']['fts'].append(te - ts)
ts = te
if this_peer_finished and not synced_gpus:
self.lookahead_cache.stream_put([], branch_length=branch_length + 1, final=True,
mode='output', idx=0)
break
if streamer is not None:
streamer.end()
if return_dict_in_generate:
if self.config.is_encoder_decoder:
return GreedySearchEncoderDecoderOutput(
sequences=input_ids,
scores=scores,
encoder_attentions=encoder_attentions,
encoder_hidden_states=encoder_hidden_states,
decoder_attentions=decoder_attentions,
cross_attentions=cross_attentions,
decoder_hidden_states=decoder_hidden_states,
)
else:
kwargs = {'dls': model_kwargs['decoding_kwargs']['dls'],
'edls': model_kwargs['decoding_kwargs']['edls'],
'fts': model_kwargs['decoding_kwargs']['fts']} | return LookaheadDecoderOnlyOutput( | 2 | 2023-12-19 13:11:38+00:00 | 8k |
Its-Haze/league-rpc-linux | league_rpc_linux/__main__.py | [
{
"identifier": "gather_ingame_information",
"path": "league_rpc_linux/champion.py",
"snippet": "def gather_ingame_information() -> tuple[str, str, int, str, int, int]:\n \"\"\"\n Get the current playing champion name.\n \"\"\"\n all_game_data_url = ALL_GAME_DATA_URL\n your_summoner_name ... | import argparse
import sys
import threading
import time
import nest_asyncio
import pypresence
from league_rpc_linux.champion import gather_ingame_information, get_skin_asset
from league_rpc_linux.colors import Colors
from league_rpc_linux.const import (
ALL_GAME_DATA_URL,
CHAMPION_NAME_CONVERT_MAP,
DEFAULT_CLIENT_ID,
DISCORD_PROCESS_NAMES,
LEAGUE_OF_LEGENDS_LOGO,
SMALL_TEXT,
)
from league_rpc_linux.gametime import get_current_ingame_time
from league_rpc_linux.kda import get_creepscore, get_gold, get_kda, get_level
from league_rpc_linux.lcu_api.lcu_connector import start_connector
from league_rpc_linux.polling import wait_until_exists
from league_rpc_linux.processes.process import (
check_discord_process,
check_league_client_process,
player_state,
)
from league_rpc_linux.reconnect import discord_reconnect_attempt | 5,930 | target=start_connector,
args=(
rpc,
cli_args,
),
daemon=True,
)
lcu_process.start()
print(f"\n{Colors.green}Successfully connected to Discord RPC!{Colors.reset}")
############################################################
start_time = int(time.time())
while True:
try:
match player_state():
case "InGame":
print(
f"\n{Colors.dblue}Detected game! Will soon gather data and update discord RPC{Colors.reset}"
)
# Poll the local league api until 200 response.
wait_until_exists(
url=ALL_GAME_DATA_URL,
custom_message="Failed to reach the local league api",
startup=True,
)
(
champ_name,
skin_name,
skin_id,
gamemode,
_,
_,
) = gather_ingame_information()
if gamemode == "TFT":
# TFT RPC
while player_state() == "InGame":
rpc.update( # type:ignore
large_image="https://wallpapercave.com/wp/wp7413493.jpg",
large_text="Playing TFT",
details="Teamfight Tactics",
state=f"In Game · lvl: {get_level()}",
small_image=LEAGUE_OF_LEGENDS_LOGO,
small_text=SMALL_TEXT,
start=int(time.time())
- get_current_ingame_time(default_time=start_time),
)
time.sleep(10)
elif gamemode == "Arena":
# ARENA RPC
skin_asset = get_skin_asset(
champion_name=champ_name,
skin_id=skin_id,
)
print(
f"{Colors.green}Successfully gathered all data.{Colors.yellow}\nUpdating Discord Presence now!{Colors.reset}"
)
while player_state() == "InGame":
rpc.update( # type:ignore
large_image=skin_asset,
large_text=skin_name
if skin_name
else CHAMPION_NAME_CONVERT_MAP.get(
champ_name, champ_name
),
details=gamemode,
state=f"In Game {f'· {get_kda()} · lvl: {get_level()} · gold: {get_gold()}' if not cli_args.no_stats else ''}",
small_image=LEAGUE_OF_LEGENDS_LOGO,
small_text=SMALL_TEXT,
start=int(time.time())
- get_current_ingame_time(default_time=start_time),
)
time.sleep(10)
else:
# LEAGUE RPC
skin_asset = get_skin_asset(
champion_name=champ_name,
skin_id=skin_id,
)
print(
f"{Colors.green}Successfully gathered all data.{Colors.yellow}\nUpdating Discord Presence now!{Colors.reset}"
)
while player_state() == "InGame":
if not champ_name or not gamemode:
break
rpc.update( # type:ignore
large_image=skin_asset,
large_text=skin_name
if skin_name
else CHAMPION_NAME_CONVERT_MAP.get(
champ_name, champ_name
),
details=gamemode,
state=f"In Game {f'· {get_kda()} · {get_creepscore()}' if not cli_args.no_stats else ''}",
small_image=LEAGUE_OF_LEGENDS_LOGO,
small_text=SMALL_TEXT,
start=int(time.time())
- get_current_ingame_time(default_time=start_time),
)
time.sleep(10)
case "InLobby":
# Handled by lcu_process thread
# It will subscribe to websockets and update discord on events.
time.sleep(10)
case _:
print(
f"{Colors.red}LeagueOfLegends.exe was terminated. rpc shuting down..{Colors.reset}."
)
rpc.close()
sys.exit()
except pypresence.exceptions.PipeClosed:
# If the program crashes because pypresence failed to connect to a pipe. (Typically if Discord is closed.)
# The script will automatically try to reconnect..
# if it fails it will keep going until you either reconnect or after a long enough period of time has passed
print(
f"{Colors.red}Discord seems to be closed, will attempt to reconnect!{Colors.reset}"
)
|
# Discord Application: League of Linux
def main(cli_args: argparse.Namespace):
"""
This is the program that gets executed.
"""
############################################################
## Check Discord, RiotClient & LeagueClient processes ##
check_league_client_process(wait_for_league=cli_args.wait_for_league)
rpc = check_discord_process(
process_names=DISCORD_PROCESS_NAMES + cli_args.add_process,
client_id=cli_args.client_id,
wait_for_discord=cli_args.wait_for_discord,
)
# Start LCU_Thread
# This process will connect to the LCU API and updates the rpc based on data subscribed from the LCU API.
# In this case passing the rpc object to the process is easier than trying to return updated data from the process.
# Every In-Client update will be handled by the LCU_Thread process and will update the rpc accordingly.
lcu_process = threading.Thread(
target=start_connector,
args=(
rpc,
cli_args,
),
daemon=True,
)
lcu_process.start()
print(f"\n{Colors.green}Successfully connected to Discord RPC!{Colors.reset}")
############################################################
start_time = int(time.time())
while True:
try:
match player_state():
case "InGame":
print(
f"\n{Colors.dblue}Detected game! Will soon gather data and update discord RPC{Colors.reset}"
)
# Poll the local league api until 200 response.
wait_until_exists(
url=ALL_GAME_DATA_URL,
custom_message="Failed to reach the local league api",
startup=True,
)
(
champ_name,
skin_name,
skin_id,
gamemode,
_,
_,
) = gather_ingame_information()
if gamemode == "TFT":
# TFT RPC
while player_state() == "InGame":
rpc.update( # type:ignore
large_image="https://wallpapercave.com/wp/wp7413493.jpg",
large_text="Playing TFT",
details="Teamfight Tactics",
state=f"In Game · lvl: {get_level()}",
small_image=LEAGUE_OF_LEGENDS_LOGO,
small_text=SMALL_TEXT,
start=int(time.time())
- get_current_ingame_time(default_time=start_time),
)
time.sleep(10)
elif gamemode == "Arena":
# ARENA RPC
skin_asset = get_skin_asset(
champion_name=champ_name,
skin_id=skin_id,
)
print(
f"{Colors.green}Successfully gathered all data.{Colors.yellow}\nUpdating Discord Presence now!{Colors.reset}"
)
while player_state() == "InGame":
rpc.update( # type:ignore
large_image=skin_asset,
large_text=skin_name
if skin_name
else CHAMPION_NAME_CONVERT_MAP.get(
champ_name, champ_name
),
details=gamemode,
state=f"In Game {f'· {get_kda()} · lvl: {get_level()} · gold: {get_gold()}' if not cli_args.no_stats else ''}",
small_image=LEAGUE_OF_LEGENDS_LOGO,
small_text=SMALL_TEXT,
start=int(time.time())
- get_current_ingame_time(default_time=start_time),
)
time.sleep(10)
else:
# LEAGUE RPC
skin_asset = get_skin_asset(
champion_name=champ_name,
skin_id=skin_id,
)
print(
f"{Colors.green}Successfully gathered all data.{Colors.yellow}\nUpdating Discord Presence now!{Colors.reset}"
)
while player_state() == "InGame":
if not champ_name or not gamemode:
break
rpc.update( # type:ignore
large_image=skin_asset,
large_text=skin_name
if skin_name
else CHAMPION_NAME_CONVERT_MAP.get(
champ_name, champ_name
),
details=gamemode,
state=f"In Game {f'· {get_kda()} · {get_creepscore()}' if not cli_args.no_stats else ''}",
small_image=LEAGUE_OF_LEGENDS_LOGO,
small_text=SMALL_TEXT,
start=int(time.time())
- get_current_ingame_time(default_time=start_time),
)
time.sleep(10)
case "InLobby":
# Handled by lcu_process thread
# It will subscribe to websockets and update discord on events.
time.sleep(10)
case _:
print(
f"{Colors.red}LeagueOfLegends.exe was terminated. rpc shuting down..{Colors.reset}."
)
rpc.close()
sys.exit()
except pypresence.exceptions.PipeClosed:
# If the program crashes because pypresence failed to connect to a pipe. (Typically if Discord is closed.)
# The script will automatically try to reconnect..
# if it fails it will keep going until you either reconnect or after a long enough period of time has passed
print(
f"{Colors.red}Discord seems to be closed, will attempt to reconnect!{Colors.reset}"
) | discord_reconnect_attempt(rpc, amount_of_tries=12, amount_of_waiting=5) | 19 | 2023-12-15 22:21:53+00:00 | 8k |
huahuahuage/Bert-VITS2-Speech | api/tts.py | [
{
"identifier": "log_instance",
"path": "log.py",
"snippet": "DISABLED_LOGGER = [\"gradio.processing_utils\", \"gradio\", \"httpx\"]\r"
},
{
"identifier": "config_instance",
"path": "config.py",
"snippet": "CONFIG_PATH = \"config.json\"\r\ndef read_config(config_path:str) -> dict:\r\n ... | import os
import numpy as np
from uuid import uuid4
from log import log_instance
from config import config_instance
from scipy.io import wavfile
from typing import Callable, List
from dataclasses import dataclass
from onnx_infer.onnx_infer import infor_onnx_instance
from .split import split_text, text_split_to_sentence
from .utils import rebuild_temp_dir
| 3,747 | log_instance.info(
f"正在推理({str(index+1)}/{str(list_length)}):{speaker_name} -> {text}"
)
# 判断是否需要自动多语言切分
if language.lower() == "auto":
try:
del params_dict["language"]
except KeyError:
pass
audio = __generate_multilang_audio(**params_dict)
else:
params_dict["language"] = language
audio = __generate_single_audio(**params_dict)
# 将所有语音句子数据存入列表中
within_audio_list.append(audio)
# 插入静音数据
slient_audio = __generate_slient_audio(interval_time=within_interval)
within_audio_list.append(slient_audio)
# 删除最后一个静音数据
within_audio_list.pop()
# 将列表中的语音数据合成
audio_concat = np.concatenate(within_audio_list, axis=2)
return audio_concat
def __generate_multi_sentence(
text_list: List[str],
speaker_name: str,
language: str = "ZH",
sdp_ratio: float = SDP_RATIO,
noise_scale: float = NOISE,
noise_scale_w: float = NOISEW,
length_scale: float = LENGTH,
emotion: float = EMOTION,
seed: int = 114514,
within_interval: float = 0.5,
sentence_interval: float = 1.0,
) -> np.float32:
"""
根据多个句子生成语音
"""
# 获取局部变量
params_dict: dict = locals()
del params_dict["text_list"]
del params_dict["sentence_interval"]
sentence_audio_list = []
for whithin_text_list in text_list:
# 句子列表数据合成一个段落音频数据
params_dict["text_list"] = whithin_text_list
sentence_audio = __generate_multi_within(**params_dict)
sentence_audio_list.append(sentence_audio)
# 插入静音数据
slient_audio = __generate_slient_audio(interval_time=sentence_interval)
sentence_audio_list.append(slient_audio)
# 删除最后一个静音数据
sentence_audio_list.pop()
audio_concat = np.concatenate(sentence_audio_list, axis=2)
return audio_concat
def generate_tts_auto(
text: str,
speaker_name: str,
language: str = "ZH",
sdp_ratio: float = 0.2,
noise_scale: float = 0.6,
noise_scale_w: float = 0.8,
length_scale: float = 1.0,
emotion: int = 7,
seed: int = 114514,
within_interval: float = 0.5,
sentence_interval: float = 1.0,
paragraph_interval: float = 2.0,
) -> np.float32:
"""
自动切分,生成语音
"""
# 获取局部变量
params_dict: dict = locals()
del params_dict["text"]
del params_dict["paragraph_interval"]
# 根据文本进行按句子切分成三级列表
paragraph_sentences_text_list = text_split_to_sentence(text=text)
log_instance.debug(f"自动切分结果 {str(paragraph_sentences_text_list)}")
# 检测文本是否为空,为空直接返回空音频
if len(paragraph_sentences_text_list) == 0:
log_instance.warning("文本转语音推理失败:{speaker_name} -> {text} 文本内容不可为空。")
return __generate_empty_float32()
# 获取每一个段落所有句子的语音数据
paragraph_audio_list = []
for sentences_text_list in paragraph_sentences_text_list:
# 句子列表数据合成一个段落音频数据
params_dict["text_list"] = sentences_text_list
paragraph_audio = __generate_multi_sentence(**params_dict)
paragraph_audio_list.append(paragraph_audio)
# 插入静音数据
slient_audio = __generate_slient_audio(interval_time=paragraph_interval)
paragraph_audio_list.append(slient_audio)
# 删除最后一个静音数据
paragraph_audio_list.pop()
audio_concat = np.concatenate(paragraph_audio_list, axis=2)
return audio_concat
@dataclass
class InferHander:
single: Callable = None
auto: Callable = None
class GenerateTTS:
def __init__(self) -> None:
# 重建语音缓存文件夹
|
EMOTION = 7
SDP_RATIO = 0.2
NOISE = 0.6
NOISEW = 0.8
LENGTH = 0.8
LANGUAGE = "ZH"
AUDIO_RATE = 44100
TEMP_PATH = os.path.abspath("./temp")
def change_to_wav(
file_path: str, data: np.float32, sample_rate: int = AUDIO_RATE
) -> str:
"""
将返回的numpy数据转换成音频
"""
scaled_data = np.int16(data * 32767)
wavfile.write(file_path, sample_rate, scaled_data)
return file_path
def __generate_empty_float32(sample_rate: int = AUDIO_RATE) -> tuple:
"""
生成空音频的numpy数据
"""
return tuple(
sample_rate,
np.concatenate([np.zeros(sample_rate // 2)]),
)
def __generate_slient_audio(
interval_time: float = 1.5, sample_rate: int = AUDIO_RATE
) -> np.float32:
"""
生成指定秒数的空音频数据
"""
return np.zeros((int)(sample_rate * interval_time), dtype=np.float32).reshape(
1, 1, int(sample_rate * interval_time)
)
def __generate_single_audio(
text: str,
speaker_name: str,
language: str = "ZH",
sdp_ratio: float = SDP_RATIO,
noise_scale: float = NOISE,
noise_scale_w: float = NOISEW,
length_scale: float = LENGTH,
emotion: float = EMOTION,
seed: int = 114514,
) -> np.float32:
"""
根据text生成单语言音频
"""
audio = infor_onnx_instance.infer(
text=text,
speaker_name=speaker_name,
language=language,
sdp_ratio=sdp_ratio,
noise_scale=noise_scale,
noise_scale_w=noise_scale_w,
length_scale=length_scale,
emotion=emotion,
seed=seed,
)
return audio
def __generate_multilang_audio(
text: str,
speaker_name: str,
sdp_ratio: float = SDP_RATIO,
noise_scale: float = NOISE,
noise_scale_w: float = NOISEW,
length_scale: float = LENGTH,
emotion: float = EMOTION,
seed: int = 114514,
) -> np.float32:
"""
根据text自动切分,生成多语言混合音频
"""
text_list, language_list = split_text(text)
if not language_list:
log_instance.warning("文本转语音推理失败:{speaker_name} -> {text} 文本内容不可为空。")
return __generate_empty_float32()
elif len(language_list) == 1:
audio = infor_onnx_instance.infer(
text=text_list[0],
speaker_name=speaker_name,
language=language_list[0],
sdp_ratio=sdp_ratio,
noise_scale=noise_scale,
noise_scale_w=noise_scale_w,
length_scale=length_scale,
emotion=emotion,
seed=seed,
)
else:
audio = infor_onnx_instance.infer_multilang(
text_list=text_list,
speaker_name=speaker_name,
language_list=language_list,
sdp_ratio=sdp_ratio,
noise_scale=noise_scale,
noise_scale_w=noise_scale_w,
length_scale=length_scale,
emotion=emotion,
seed=seed,
)
return audio
def __generate_multi_within(
text_list: List[str],
speaker_name: str,
language: str = "ZH",
sdp_ratio: float = SDP_RATIO,
noise_scale: float = NOISE,
noise_scale_w: float = NOISEW,
length_scale: float = LENGTH,
emotion: float = EMOTION,
seed: int = 114514,
within_interval: float = 0.5,
) -> np.float32:
"""
根据多个句内文字段生成语音
"""
# 获取局部变量
params_dict: dict = locals()
del params_dict["text_list"]
del params_dict["within_interval"]
within_audio_list = []
list_length = len(text_list)
for index, text in enumerate(text_list):
params_dict["text"] = text
log_instance.info(
f"正在推理({str(index+1)}/{str(list_length)}):{speaker_name} -> {text}"
)
# 判断是否需要自动多语言切分
if language.lower() == "auto":
try:
del params_dict["language"]
except KeyError:
pass
audio = __generate_multilang_audio(**params_dict)
else:
params_dict["language"] = language
audio = __generate_single_audio(**params_dict)
# 将所有语音句子数据存入列表中
within_audio_list.append(audio)
# 插入静音数据
slient_audio = __generate_slient_audio(interval_time=within_interval)
within_audio_list.append(slient_audio)
# 删除最后一个静音数据
within_audio_list.pop()
# 将列表中的语音数据合成
audio_concat = np.concatenate(within_audio_list, axis=2)
return audio_concat
def __generate_multi_sentence(
text_list: List[str],
speaker_name: str,
language: str = "ZH",
sdp_ratio: float = SDP_RATIO,
noise_scale: float = NOISE,
noise_scale_w: float = NOISEW,
length_scale: float = LENGTH,
emotion: float = EMOTION,
seed: int = 114514,
within_interval: float = 0.5,
sentence_interval: float = 1.0,
) -> np.float32:
"""
根据多个句子生成语音
"""
# 获取局部变量
params_dict: dict = locals()
del params_dict["text_list"]
del params_dict["sentence_interval"]
sentence_audio_list = []
for whithin_text_list in text_list:
# 句子列表数据合成一个段落音频数据
params_dict["text_list"] = whithin_text_list
sentence_audio = __generate_multi_within(**params_dict)
sentence_audio_list.append(sentence_audio)
# 插入静音数据
slient_audio = __generate_slient_audio(interval_time=sentence_interval)
sentence_audio_list.append(slient_audio)
# 删除最后一个静音数据
sentence_audio_list.pop()
audio_concat = np.concatenate(sentence_audio_list, axis=2)
return audio_concat
def generate_tts_auto(
text: str,
speaker_name: str,
language: str = "ZH",
sdp_ratio: float = 0.2,
noise_scale: float = 0.6,
noise_scale_w: float = 0.8,
length_scale: float = 1.0,
emotion: int = 7,
seed: int = 114514,
within_interval: float = 0.5,
sentence_interval: float = 1.0,
paragraph_interval: float = 2.0,
) -> np.float32:
"""
自动切分,生成语音
"""
# 获取局部变量
params_dict: dict = locals()
del params_dict["text"]
del params_dict["paragraph_interval"]
# 根据文本进行按句子切分成三级列表
paragraph_sentences_text_list = text_split_to_sentence(text=text)
log_instance.debug(f"自动切分结果 {str(paragraph_sentences_text_list)}")
# 检测文本是否为空,为空直接返回空音频
if len(paragraph_sentences_text_list) == 0:
log_instance.warning("文本转语音推理失败:{speaker_name} -> {text} 文本内容不可为空。")
return __generate_empty_float32()
# 获取每一个段落所有句子的语音数据
paragraph_audio_list = []
for sentences_text_list in paragraph_sentences_text_list:
# 句子列表数据合成一个段落音频数据
params_dict["text_list"] = sentences_text_list
paragraph_audio = __generate_multi_sentence(**params_dict)
paragraph_audio_list.append(paragraph_audio)
# 插入静音数据
slient_audio = __generate_slient_audio(interval_time=paragraph_interval)
paragraph_audio_list.append(slient_audio)
# 删除最后一个静音数据
paragraph_audio_list.pop()
audio_concat = np.concatenate(paragraph_audio_list, axis=2)
return audio_concat
@dataclass
class InferHander:
single: Callable = None
auto: Callable = None
class GenerateTTS:
def __init__(self) -> None:
# 重建语音缓存文件夹
| rebuild_temp_dir(TEMP_PATH)
| 5 | 2023-12-21 13:50:50+00:00 | 8k |
haseeb-heaven/Gemini-Vision-Pro | script.py | [
{
"identifier": "Logger",
"path": "libs/logger.py",
"snippet": "class Logger:\n _logger = None\n\n @staticmethod\n def get_logger(file_name):\n if Logger._logger is None:\n Logger._logger = Logger._setup_logger(file_name)\n return Logger._logger\n\n @staticmethod\n ... | import streamlit as st
import cv2
import io
import traceback
import traceback
from streamlit_webrtc import webrtc_streamer, WebRtcMode, RTCConfiguration
from PIL import Image
from io import BytesIO
from pathlib import Path
from libs.logger import Logger
from libs.gemini_vision import GeminiVision
from libs.speech import SpeechToText
from libs.voice import TextToSpeech
from libs.image_cv2 import ImageCV2 | 4,022 | try:
return func(*args, **kwargs)
except Exception as exception:
st.session_state.logger.error(f"An error occurred in {func.__name__}: {exception}")
st.error(f"An error occurred: {exception}")
st.session_state.logger.error(traceback.format_exc())
st.stop()
return wrapper
@exception_handler
def validate_image(image_path):
if not image_path.exists():
st.session_state.logger.error(f"Could not find image: {image_path}")
raise FileNotFoundError(f"Could not find image: {image_path}")
@exception_handler
def process_image():
image_contents = [st.session_state['prompt'], st.session_state['captured_image']]
st.session_state.logger.info(f"Image data is: {st.session_state['captured_image']}")
response = st.session_state.gemini_vision.generate_content(image_contents)
if 'error' in response:
raise ValueError(f"An error occurred: {response}")
else:
if response.text:
st.session_state.tts.speak(response.text)
st.session_state.logger.info(f"Response: {response.text}")
st.session_state.response = response.text
@exception_handler
def get_prompt_from_mic():
prompt = st.session_state.stt.listen_and_convert()
return prompt
@exception_handler
def log_webrtc_context_states(webrtc_ctx):
if webrtc_ctx is not None:
# Log the state of the WebRTC context
st.session_state.logger.info(f"WebRTC context: {webrtc_ctx}")
st.session_state.logger.info(f"Is WebRTC playing: {webrtc_ctx.state.playing}")
st.session_state.logger.info(f"Is audio receiver ready: {webrtc_ctx.audio_receiver}")
st.session_state.logger.info(f"Is video receiver ready: {webrtc_ctx.video_receiver}")
else:
st.error("WebRTC context is None.")
@exception_handler
def capture_image():
st.session_state.logger.info("Attempting to capture image from webcam with ImageCV2...")
# Capture the image from the webcam
web_image = None
web_cam = ImageCV2()
web_image_file = "web_image.png"
web_image = web_cam.capture_image_from_webcam(web_image_file)
if web_image is None:
raise ValueError("Could not capture image from webcam")
# convert web_image from RGB to RGBA
web_image = web_image.convert("RGBA")
# Validate that an image is present
image_path = Path(web_image_file)
validate_image(image_path)
# Open the image
st.session_state.logger.info(f"Trying to open image: {web_image_file}")
web_image = Image.open(web_image_file)
return web_image
def display_support():
st.markdown("<div style='text-align: center;'>Share and Support</div>", unsafe_allow_html=True)
st.write("""
<div style="display: flex; flex-direction: column; align-items: center; justify-content: center;">
<ul style="list-style-type: none; margin: 0; padding: 0; display: flex;">
<li style="margin-right: 10px;"><a href="https://twitter.com/haseeb_heaven" target="_blank"><img src="https://img.icons8.com/color/32/000000/twitter--v1.png"/></a></li>
<li style="margin-right: 10px;"><a href="https://www.buymeacoffee.com/haseebheaven" target="_blank"><img src="https://img.icons8.com/color/32/000000/coffee-to-go--v1.png"/></a></li>
<li style="margin-right: 10px;"><a href="https://www.youtube.com/@HaseebHeaven/videos" target="_blank"><img src="https://img.icons8.com/color/32/000000/youtube-play.png"/></a></li>
<li><a href="https://github.com/haseeb-heaven/LangChain-Coder" target="_blank"><img src="https://img.icons8.com/color/32/000000/github--v1.png"/></a></li>
</ul>
</div>
""", unsafe_allow_html=True)
# Streamlit App
def streamlit_app():
# Google Logo and Title
st.write('<div style="display: flex; flex-direction: row; align-items: center; justify-content: center;"><a style="margin-right: 10px;" href="https://www.google.com" target="_blank"><img src="https://img.icons8.com/color/32/000000/google-logo.png"/></a><h1 style="margin-left: 10px;">Google - Gemini Vision</h1></div>', unsafe_allow_html=True)
# Display support
display_support()
# Initialize logger
if st.session_state.logger is None:
st.session_state.logger = Logger.get_logger('gemini_vision_pro.log')
# Display the Gemini Sidebar settings
with st.sidebar.title("Gemini Settings"):
st.session_state.api_key = st.sidebar.text_input("API Key", type="password")
st.session_state.temperature = st.sidebar.slider("Temperature", 0.0, 1.0, 0.3)
st.session_state.top_k = st.sidebar.number_input("Top K", value=32)
st.session_state.top_p = st.sidebar.slider("Top P", 0.0, 1.0, 1.0)
st.session_state.gemini_vision = GeminiVision(st.session_state.api_key, st.session_state.temperature, st.session_state.top_p, st.session_state.top_k)
if (st.session_state.api_key is not None and st.session_state.api_key != '') \
and (st.session_state.temperature is not None and st.session_state.temperature != '') \
and (st.session_state.top_k is not None and st.session_state.top_k != '') \
and (st.session_state.top_p is not None and st.session_state.top_p != ''):
st.toast("Settings updated successfully!", icon="👍")
else:
st.toast("Please enter all the settings.\nAPI Key is required", icon="❌")
raise ValueError("Please enter all values the settings.\nAPI Key is required")
# Initialize services once
if st.session_state.tts is None:
st.session_state.tts = TextToSpeech()
if st.session_state.stt is None:
| """
Description: This is the amazing Google Gemini Vision Pro.
This scans the image and using Gemini AI pro vision API it generates the descrption of the image.
It also uses the speech to text and text to speech to speak the prompt and display the description of the image.
It also uses the webcam to capture the image and display it.
Features:
1. Webcam detection using WebRTC, OpenCV and PIL
2. Speech to text using Google Cloud Speech to Text API
3. Text to speech using Google Cloud Text to Speech API
4. Image processing using Gemini AI Pro Vision API
5. Logging using Python logging module
6. Error handling using Python exception handling
Modules used:
1. Streamlit - Is is the Web App framework used to build the app
2. Streamlit Webrtc - It is used to capture the image from the webcam
3. OpenCV - It is used to capture the image from the webcam
4. PIL - It is image processing library used to convert the image.
5. gTTS - It is used to convert the text to speech
6. SpeechRecognition - It is used to convert the speech to text
7. google.cloud.speech - It is used to convert the speech to text
Author: HeavenHM
Date: 17-12-2023
Version: 1.0
"""
# Initialize session state
def init_session_state():
if 'api_key' not in st.session_state:
st.session_state['api_key'] = ''
if 'temperature' not in st.session_state:
st.session_state['temperature'] = 0.1
if 'top_k' not in st.session_state:
st.session_state['top_k'] = 32
if 'top_p' not in st.session_state:
st.session_state['top_p'] = 1.0
if 'captured_image' not in st.session_state:
st.session_state['captured_image'] = None
if 'prompt' not in st.session_state:
st.session_state['prompt'] = ''
if 'api_key' not in st.session_state:
st.session_state['api_key'] = ''
if 'captured_image' not in st.session_state:
st.session_state['captured_image'] = None
if 'prompt' not in st.session_state:
st.session_state['prompt'] = ''
if "logger" not in st.session_state:
st.session_state["logger"] = None
if "tts" not in st.session_state:
st.session_state["tts"] = None
if "stt" not in st.session_state:
st.session_state["stt"] = None
if "gemini_vision" not in st.session_state:
st.session_state["gemini_vision"] = None
if "webrtc_ctx" not in st.session_state:
st.session_state["webrtc_ctx"] = None
if "response" not in st.session_state:
st.session_state["response"] = None
# Exception handling decorator
def exception_handler(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exception:
st.session_state.logger.error(f"An error occurred in {func.__name__}: {exception}")
st.error(f"An error occurred: {exception}")
st.session_state.logger.error(traceback.format_exc())
st.stop()
return wrapper
@exception_handler
def validate_image(image_path):
if not image_path.exists():
st.session_state.logger.error(f"Could not find image: {image_path}")
raise FileNotFoundError(f"Could not find image: {image_path}")
@exception_handler
def process_image():
image_contents = [st.session_state['prompt'], st.session_state['captured_image']]
st.session_state.logger.info(f"Image data is: {st.session_state['captured_image']}")
response = st.session_state.gemini_vision.generate_content(image_contents)
if 'error' in response:
raise ValueError(f"An error occurred: {response}")
else:
if response.text:
st.session_state.tts.speak(response.text)
st.session_state.logger.info(f"Response: {response.text}")
st.session_state.response = response.text
@exception_handler
def get_prompt_from_mic():
prompt = st.session_state.stt.listen_and_convert()
return prompt
@exception_handler
def log_webrtc_context_states(webrtc_ctx):
if webrtc_ctx is not None:
# Log the state of the WebRTC context
st.session_state.logger.info(f"WebRTC context: {webrtc_ctx}")
st.session_state.logger.info(f"Is WebRTC playing: {webrtc_ctx.state.playing}")
st.session_state.logger.info(f"Is audio receiver ready: {webrtc_ctx.audio_receiver}")
st.session_state.logger.info(f"Is video receiver ready: {webrtc_ctx.video_receiver}")
else:
st.error("WebRTC context is None.")
@exception_handler
def capture_image():
st.session_state.logger.info("Attempting to capture image from webcam with ImageCV2...")
# Capture the image from the webcam
web_image = None
web_cam = ImageCV2()
web_image_file = "web_image.png"
web_image = web_cam.capture_image_from_webcam(web_image_file)
if web_image is None:
raise ValueError("Could not capture image from webcam")
# convert web_image from RGB to RGBA
web_image = web_image.convert("RGBA")
# Validate that an image is present
image_path = Path(web_image_file)
validate_image(image_path)
# Open the image
st.session_state.logger.info(f"Trying to open image: {web_image_file}")
web_image = Image.open(web_image_file)
return web_image
def display_support():
st.markdown("<div style='text-align: center;'>Share and Support</div>", unsafe_allow_html=True)
st.write("""
<div style="display: flex; flex-direction: column; align-items: center; justify-content: center;">
<ul style="list-style-type: none; margin: 0; padding: 0; display: flex;">
<li style="margin-right: 10px;"><a href="https://twitter.com/haseeb_heaven" target="_blank"><img src="https://img.icons8.com/color/32/000000/twitter--v1.png"/></a></li>
<li style="margin-right: 10px;"><a href="https://www.buymeacoffee.com/haseebheaven" target="_blank"><img src="https://img.icons8.com/color/32/000000/coffee-to-go--v1.png"/></a></li>
<li style="margin-right: 10px;"><a href="https://www.youtube.com/@HaseebHeaven/videos" target="_blank"><img src="https://img.icons8.com/color/32/000000/youtube-play.png"/></a></li>
<li><a href="https://github.com/haseeb-heaven/LangChain-Coder" target="_blank"><img src="https://img.icons8.com/color/32/000000/github--v1.png"/></a></li>
</ul>
</div>
""", unsafe_allow_html=True)
# Streamlit App
def streamlit_app():
# Google Logo and Title
st.write('<div style="display: flex; flex-direction: row; align-items: center; justify-content: center;"><a style="margin-right: 10px;" href="https://www.google.com" target="_blank"><img src="https://img.icons8.com/color/32/000000/google-logo.png"/></a><h1 style="margin-left: 10px;">Google - Gemini Vision</h1></div>', unsafe_allow_html=True)
# Display support
display_support()
# Initialize logger
if st.session_state.logger is None:
st.session_state.logger = Logger.get_logger('gemini_vision_pro.log')
# Display the Gemini Sidebar settings
with st.sidebar.title("Gemini Settings"):
st.session_state.api_key = st.sidebar.text_input("API Key", type="password")
st.session_state.temperature = st.sidebar.slider("Temperature", 0.0, 1.0, 0.3)
st.session_state.top_k = st.sidebar.number_input("Top K", value=32)
st.session_state.top_p = st.sidebar.slider("Top P", 0.0, 1.0, 1.0)
st.session_state.gemini_vision = GeminiVision(st.session_state.api_key, st.session_state.temperature, st.session_state.top_p, st.session_state.top_k)
if (st.session_state.api_key is not None and st.session_state.api_key != '') \
and (st.session_state.temperature is not None and st.session_state.temperature != '') \
and (st.session_state.top_k is not None and st.session_state.top_k != '') \
and (st.session_state.top_p is not None and st.session_state.top_p != ''):
st.toast("Settings updated successfully!", icon="👍")
else:
st.toast("Please enter all the settings.\nAPI Key is required", icon="❌")
raise ValueError("Please enter all values the settings.\nAPI Key is required")
# Initialize services once
if st.session_state.tts is None:
st.session_state.tts = TextToSpeech()
if st.session_state.stt is None: | st.session_state.stt = SpeechToText() | 2 | 2023-12-16 23:24:46+00:00 | 8k |
lipku/metahuman-stream | nerf_triplane/provider.py | [
{
"identifier": "get_audio_features",
"path": "nerf_triplane/utils.py",
"snippet": "def get_audio_features(features, att_mode, index):\n if att_mode == 0:\n return features[[index]]\n elif att_mode == 1:\n left = index - 8\n pad_left = 0\n if left < 0:\n pad_... | import os
import cv2
import glob
import json
import tqdm
import numpy as np
import matplotlib.pyplot as plt
import trimesh
import torch
import torch.nn.functional as F
import pandas as pd
from scipy.spatial.transform import Slerp, Rotation
from torch.utils.data import DataLoader
from .utils import get_audio_features, get_rays, get_bg_coords, convert_poses | 4,224 | aud_features = aud_features.long()
print(f'[INFO] load {self.opt.aud} aud_features: {aud_features.shape}')
self.poses = []
self.auds = []
self.eye_area = []
for f in tqdm.tqdm(frames, desc=f'Loading data'):
pose = np.array(f['transform_matrix'], dtype=np.float32) # [4, 4]
pose = nerf_matrix_to_ngp(pose, scale=self.scale, offset=self.offset)
self.poses.append(pose)
# find the corresponding audio to the image frame
if not self.opt.asr and self.opt.aud == '':
aud = aud_features[min(f['aud_id'], aud_features.shape[0] - 1)] # careful for the last frame...
self.auds.append(aud)
if self.opt.exp_eye:
if 'eye_ratio' in f:
area = f['eye_ratio']
else:
area = 0.25 # default value for opened eye
self.eye_area.append(area)
# load pre-extracted background image (should be the same size as training image...)
if self.opt.bg_img == 'white': # special
bg_img = np.ones((self.H, self.W, 3), dtype=np.float32)
elif self.opt.bg_img == 'black': # special
bg_img = np.zeros((self.H, self.W, 3), dtype=np.float32)
else: # load from file
bg_img = cv2.imread(self.opt.bg_img, cv2.IMREAD_UNCHANGED) # [H, W, 3]
if bg_img.shape[0] != self.H or bg_img.shape[1] != self.W:
bg_img = cv2.resize(bg_img, (self.W, self.H), interpolation=cv2.INTER_AREA)
bg_img = cv2.cvtColor(bg_img, cv2.COLOR_BGR2RGB)
bg_img = bg_img.astype(np.float32) / 255 # [H, W, 3/4]
self.bg_img = bg_img
self.poses = np.stack(self.poses, axis=0)
# smooth camera path...
if self.opt.smooth_path:
self.poses = smooth_camera_path(self.poses, self.opt.smooth_path_window)
self.poses = torch.from_numpy(self.poses) # [N, 4, 4]
if self.opt.asr:
# live streaming, no pre-calculated auds
self.auds = None
else:
# auds corresponding to images
if self.opt.aud == '':
self.auds = torch.stack(self.auds, dim=0) # [N, 32, 16]
# auds is novel, may have a different length with images
else:
self.auds = aud_features
self.bg_img = torch.from_numpy(self.bg_img)
if self.opt.exp_eye:
self.eye_area = np.array(self.eye_area, dtype=np.float32) # [N]
print(f'[INFO] eye_area: {self.eye_area.min()} - {self.eye_area.max()}')
if self.opt.smooth_eye:
# naive 5 window average
ori_eye = self.eye_area.copy()
for i in range(ori_eye.shape[0]):
start = max(0, i - 1)
end = min(ori_eye.shape[0], i + 2)
self.eye_area[i] = ori_eye[start:end].mean()
self.eye_area = torch.from_numpy(self.eye_area).view(-1, 1) # [N, 1]
# always preload
self.poses = self.poses.to(self.device)
if self.auds is not None:
self.auds = self.auds.to(self.device)
self.bg_img = self.bg_img.to(torch.half).to(self.device)
if self.opt.exp_eye:
self.eye_area = self.eye_area.to(self.device)
# load intrinsics
fl_x = fl_y = transform['focal_len']
cx = (transform['cx'] / downscale)
cy = (transform['cy'] / downscale)
self.intrinsics = np.array([fl_x, fl_y, cx, cy])
# directly build the coordinate meshgrid in [-1, 1]^2
self.bg_coords = get_bg_coords(self.H, self.W, self.device) # [1, H*W, 2] in [-1, 1]
def mirror_index(self, index):
size = self.poses.shape[0]
turn = index // size
res = index % size
if turn % 2 == 0:
return res
else:
return size - res - 1
def collate(self, index):
B = len(index) # a list of length 1
# assert B == 1
results = {}
# audio use the original index
if self.auds is not None:
|
# ref: https://github.com/NVlabs/instant-ngp/blob/b76004c8cf478880227401ae763be4c02f80b62f/include/neural-graphics-primitives/nerf_loader.h#L50
def nerf_matrix_to_ngp(pose, scale=0.33, offset=[0, 0, 0]):
new_pose = np.array([
[pose[1, 0], -pose[1, 1], -pose[1, 2], pose[1, 3] * scale + offset[0]],
[pose[2, 0], -pose[2, 1], -pose[2, 2], pose[2, 3] * scale + offset[1]],
[pose[0, 0], -pose[0, 1], -pose[0, 2], pose[0, 3] * scale + offset[2]],
[0, 0, 0, 1],
], dtype=np.float32)
return new_pose
def smooth_camera_path(poses, kernel_size=5):
# smooth the camera trajectory...
# poses: [N, 4, 4], numpy array
N = poses.shape[0]
K = kernel_size // 2
trans = poses[:, :3, 3].copy() # [N, 3]
rots = poses[:, :3, :3].copy() # [N, 3, 3]
for i in range(N):
start = max(0, i - K)
end = min(N, i + K + 1)
poses[i, :3, 3] = trans[start:end].mean(0)
poses[i, :3, :3] = Rotation.from_matrix(rots[start:end]).mean().as_matrix()
return poses
def polygon_area(x, y):
x_ = x - x.mean()
y_ = y - y.mean()
correction = x_[-1] * y_[0] - y_[-1]* x_[0]
main_area = np.dot(x_[:-1], y_[1:]) - np.dot(y_[:-1], x_[1:])
return 0.5 * np.abs(main_area + correction)
def visualize_poses(poses, size=0.1):
# poses: [B, 4, 4]
print(f'[INFO] visualize poses: {poses.shape}')
axes = trimesh.creation.axis(axis_length=4)
box = trimesh.primitives.Box(extents=(2, 2, 2)).as_outline()
box.colors = np.array([[128, 128, 128]] * len(box.entities))
objects = [axes, box]
for pose in poses:
# a camera is visualized with 8 line segments.
pos = pose[:3, 3]
a = pos + size * pose[:3, 0] + size * pose[:3, 1] + size * pose[:3, 2]
b = pos - size * pose[:3, 0] + size * pose[:3, 1] + size * pose[:3, 2]
c = pos - size * pose[:3, 0] - size * pose[:3, 1] + size * pose[:3, 2]
d = pos + size * pose[:3, 0] - size * pose[:3, 1] + size * pose[:3, 2]
dir = (a + b + c + d) / 4 - pos
dir = dir / (np.linalg.norm(dir) + 1e-8)
o = pos + dir * 3
segs = np.array([[pos, a], [pos, b], [pos, c], [pos, d], [a, b], [b, c], [c, d], [d, a], [pos, o]])
segs = trimesh.load_path(segs)
objects.append(segs)
trimesh.Scene(objects).show()
class NeRFDataset_Test:
def __init__(self, opt, device, downscale=1):
super().__init__()
self.opt = opt
self.device = device
self.downscale = downscale
self.scale = opt.scale # camera radius scale to make sure camera are inside the bounding box.
self.offset = opt.offset # camera offset
self.bound = opt.bound # bounding box half length, also used as the radius to random sample poses.
self.fp16 = opt.fp16
self.start_index = opt.data_range[0]
self.end_index = opt.data_range[1]
self.training = False
self.num_rays = -1
# load nerf-compatible format data.
with open(opt.pose, 'r') as f:
transform = json.load(f)
# load image size
self.H = int(transform['cy']) * 2 // downscale
self.W = int(transform['cx']) * 2 // downscale
# read images
frames = transform["frames"]
# use a slice of the dataset
if self.end_index == -1: # abuse...
self.end_index = len(frames)
frames = frames[self.start_index:self.end_index]
print(f'[INFO] load {len(frames)} frames.')
# only load pre-calculated aud features when not live-streaming
if not self.opt.asr:
aud_features = np.load(self.opt.aud)
aud_features = torch.from_numpy(aud_features)
# support both [N, 16] labels and [N, 16, K] logits
if len(aud_features.shape) == 3:
aud_features = aud_features.float().permute(0, 2, 1) # [N, 16, 29] --> [N, 29, 16]
if self.opt.emb:
print(f'[INFO] argmax to aud features {aud_features.shape} for --emb mode')
aud_features = aud_features.argmax(1) # [N, 16]
else:
assert self.opt.emb, "aud only provide labels, must use --emb"
aud_features = aud_features.long()
print(f'[INFO] load {self.opt.aud} aud_features: {aud_features.shape}')
self.poses = []
self.auds = []
self.eye_area = []
for f in tqdm.tqdm(frames, desc=f'Loading data'):
pose = np.array(f['transform_matrix'], dtype=np.float32) # [4, 4]
pose = nerf_matrix_to_ngp(pose, scale=self.scale, offset=self.offset)
self.poses.append(pose)
# find the corresponding audio to the image frame
if not self.opt.asr and self.opt.aud == '':
aud = aud_features[min(f['aud_id'], aud_features.shape[0] - 1)] # careful for the last frame...
self.auds.append(aud)
if self.opt.exp_eye:
if 'eye_ratio' in f:
area = f['eye_ratio']
else:
area = 0.25 # default value for opened eye
self.eye_area.append(area)
# load pre-extracted background image (should be the same size as training image...)
if self.opt.bg_img == 'white': # special
bg_img = np.ones((self.H, self.W, 3), dtype=np.float32)
elif self.opt.bg_img == 'black': # special
bg_img = np.zeros((self.H, self.W, 3), dtype=np.float32)
else: # load from file
bg_img = cv2.imread(self.opt.bg_img, cv2.IMREAD_UNCHANGED) # [H, W, 3]
if bg_img.shape[0] != self.H or bg_img.shape[1] != self.W:
bg_img = cv2.resize(bg_img, (self.W, self.H), interpolation=cv2.INTER_AREA)
bg_img = cv2.cvtColor(bg_img, cv2.COLOR_BGR2RGB)
bg_img = bg_img.astype(np.float32) / 255 # [H, W, 3/4]
self.bg_img = bg_img
self.poses = np.stack(self.poses, axis=0)
# smooth camera path...
if self.opt.smooth_path:
self.poses = smooth_camera_path(self.poses, self.opt.smooth_path_window)
self.poses = torch.from_numpy(self.poses) # [N, 4, 4]
if self.opt.asr:
# live streaming, no pre-calculated auds
self.auds = None
else:
# auds corresponding to images
if self.opt.aud == '':
self.auds = torch.stack(self.auds, dim=0) # [N, 32, 16]
# auds is novel, may have a different length with images
else:
self.auds = aud_features
self.bg_img = torch.from_numpy(self.bg_img)
if self.opt.exp_eye:
self.eye_area = np.array(self.eye_area, dtype=np.float32) # [N]
print(f'[INFO] eye_area: {self.eye_area.min()} - {self.eye_area.max()}')
if self.opt.smooth_eye:
# naive 5 window average
ori_eye = self.eye_area.copy()
for i in range(ori_eye.shape[0]):
start = max(0, i - 1)
end = min(ori_eye.shape[0], i + 2)
self.eye_area[i] = ori_eye[start:end].mean()
self.eye_area = torch.from_numpy(self.eye_area).view(-1, 1) # [N, 1]
# always preload
self.poses = self.poses.to(self.device)
if self.auds is not None:
self.auds = self.auds.to(self.device)
self.bg_img = self.bg_img.to(torch.half).to(self.device)
if self.opt.exp_eye:
self.eye_area = self.eye_area.to(self.device)
# load intrinsics
fl_x = fl_y = transform['focal_len']
cx = (transform['cx'] / downscale)
cy = (transform['cy'] / downscale)
self.intrinsics = np.array([fl_x, fl_y, cx, cy])
# directly build the coordinate meshgrid in [-1, 1]^2
self.bg_coords = get_bg_coords(self.H, self.W, self.device) # [1, H*W, 2] in [-1, 1]
def mirror_index(self, index):
size = self.poses.shape[0]
turn = index // size
res = index % size
if turn % 2 == 0:
return res
else:
return size - res - 1
def collate(self, index):
B = len(index) # a list of length 1
# assert B == 1
results = {}
# audio use the original index
if self.auds is not None: | auds = get_audio_features(self.auds, self.opt.att, index[0]).to(self.device) | 0 | 2023-12-19 01:32:46+00:00 | 8k |
MingtaoGuo/AnimateAnyone_unofficial | 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 ldm.modules.diffusionmodules.util import (
checkpoint,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
)
from ldm.modules.attention import SpatialSelfAttention, SpatialTransformer
from ldm.util import exists
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,750 | 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),
|
# 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, ResBlockNoTime):
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( | 4 | 2023-12-16 03:31:33+00:00 | 8k |
yasserben/CLOUDS | demo.py | [
{
"identifier": "add_maskformer2_config",
"path": "clouds/config.py",
"snippet": "def add_maskformer2_config(cfg):\n \"\"\"\n Add config for MASK_FORMER.\n \"\"\"\n # NOTE: configs from original maskformer\n # data config\n # select the dataset mapper\n cfg.INPUT.DATASET_MAPPER_NAME... | import argparse
import glob
import multiprocessing as mp
import os
import sys
import tempfile
import time
import warnings
import cv2
import numpy as np
import tqdm
from detectron2.config import get_cfg
from detectron2.data.detection_utils import read_image
from detectron2.projects.deeplab import add_deeplab_config
from detectron2.utils.logger import setup_logger
from clouds import add_maskformer2_config, add_clouds_config
from predictor import VisualizationDemo | 3,771 | """
Copyright 2023 Telecom Paris, Yasser BENIGMIM. All rights reserved.
Licensed under the Apache License, Version 2.0
Reference: https://github.com/facebookresearch/Mask2Former/blob/main/demo/demo.py
"""
# fmt: off
sys.path.insert(1, os.path.join(sys.path[0], '..'))
# fmt: on
# constants
WINDOW_NAME = "clouds demo"
def setup_cfg(args):
# load config from file and command-line arguments
cfg = get_cfg()
add_deeplab_config(cfg)
add_maskformer2_config(cfg)
add_clouds_config(cfg)
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
return cfg
def get_parser():
parser = argparse.ArgumentParser(description="clouds demo for builtin configs")
parser.add_argument(
"--config-file",
default="../configs/coco/segmentation/clouds/clouds_convnext_large_eval_cityscapes.yaml",
metavar="FILE",
help="path to config file",
)
parser.add_argument(
"--webcam", action="store_true", help="Take inputs from webcam."
)
parser.add_argument("--video-input", help="Path to video file.")
parser.add_argument(
"--input",
nargs="+",
help="A list of space separated input images; "
"or a single glob pattern such as 'directory/*.jpg'",
)
parser.add_argument(
"--output",
help="A file or directory to save output visualizations. "
"If not given, will show output in an OpenCV window.",
)
parser.add_argument(
"--confidence-threshold",
type=float,
default=0.5,
help="Minimum score for instance predictions to be shown",
)
parser.add_argument(
"--opts",
help="Modify config options using the command-line 'KEY VALUE' pairs",
default=[],
nargs=argparse.REMAINDER,
)
return parser
def test_opencv_video_format(codec, file_ext):
with tempfile.TemporaryDirectory(prefix="video_format_test") as dir:
filename = os.path.join(dir, "test_file" + file_ext)
writer = cv2.VideoWriter(
filename=filename,
fourcc=cv2.VideoWriter_fourcc(*codec),
fps=float(30),
frameSize=(10, 10),
isColor=True,
)
[writer.write(np.zeros((10, 10, 3), np.uint8)) for _ in range(30)]
writer.release()
if os.path.isfile(filename):
return True
return False
if __name__ == "__main__":
mp.set_start_method("spawn", force=True)
args = get_parser().parse_args()
setup_logger(name="fvcore")
logger = setup_logger()
logger.info("Arguments: " + str(args))
cfg = setup_cfg(args)
| """
Copyright 2023 Telecom Paris, Yasser BENIGMIM. All rights reserved.
Licensed under the Apache License, Version 2.0
Reference: https://github.com/facebookresearch/Mask2Former/blob/main/demo/demo.py
"""
# fmt: off
sys.path.insert(1, os.path.join(sys.path[0], '..'))
# fmt: on
# constants
WINDOW_NAME = "clouds demo"
def setup_cfg(args):
# load config from file and command-line arguments
cfg = get_cfg()
add_deeplab_config(cfg)
add_maskformer2_config(cfg)
add_clouds_config(cfg)
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
return cfg
def get_parser():
parser = argparse.ArgumentParser(description="clouds demo for builtin configs")
parser.add_argument(
"--config-file",
default="../configs/coco/segmentation/clouds/clouds_convnext_large_eval_cityscapes.yaml",
metavar="FILE",
help="path to config file",
)
parser.add_argument(
"--webcam", action="store_true", help="Take inputs from webcam."
)
parser.add_argument("--video-input", help="Path to video file.")
parser.add_argument(
"--input",
nargs="+",
help="A list of space separated input images; "
"or a single glob pattern such as 'directory/*.jpg'",
)
parser.add_argument(
"--output",
help="A file or directory to save output visualizations. "
"If not given, will show output in an OpenCV window.",
)
parser.add_argument(
"--confidence-threshold",
type=float,
default=0.5,
help="Minimum score for instance predictions to be shown",
)
parser.add_argument(
"--opts",
help="Modify config options using the command-line 'KEY VALUE' pairs",
default=[],
nargs=argparse.REMAINDER,
)
return parser
def test_opencv_video_format(codec, file_ext):
with tempfile.TemporaryDirectory(prefix="video_format_test") as dir:
filename = os.path.join(dir, "test_file" + file_ext)
writer = cv2.VideoWriter(
filename=filename,
fourcc=cv2.VideoWriter_fourcc(*codec),
fps=float(30),
frameSize=(10, 10),
isColor=True,
)
[writer.write(np.zeros((10, 10, 3), np.uint8)) for _ in range(30)]
writer.release()
if os.path.isfile(filename):
return True
return False
if __name__ == "__main__":
mp.set_start_method("spawn", force=True)
args = get_parser().parse_args()
setup_logger(name="fvcore")
logger = setup_logger()
logger.info("Arguments: " + str(args))
cfg = setup_cfg(args)
| demo = VisualizationDemo(cfg) | 2 | 2023-12-15 15:40:58+00:00 | 8k |
mattcar15/bambu-connect | bambu_connect/BambuClient.py | [
{
"identifier": "CameraClient",
"path": "bambu_connect/CameraClient.py",
"snippet": "class CameraClient:\n def __init__(self, hostname, access_code, port=6000):\n self.hostname = hostname\n self.port = port\n self.username = \"bblp\"\n self.auth_packet = self.__create_auth... | from .CameraClient import CameraClient
from .WatchClient import WatchClient
from .ExecuteClient import ExecuteClient
from .FileClient import FileClient
from .utils.models import PrinterStatus
from typing import Callable, Dict, Optional, Any | 3,916 |
class BambuClient:
def __init__(self, hostname: str, access_code: str, serial: str):
self.cameraClient = CameraClient(hostname, access_code)
self.watchClient = WatchClient(hostname, access_code, serial)
self.executeClient = ExecuteClient(hostname, access_code, serial)
|
class BambuClient:
def __init__(self, hostname: str, access_code: str, serial: str):
self.cameraClient = CameraClient(hostname, access_code)
self.watchClient = WatchClient(hostname, access_code, serial)
self.executeClient = ExecuteClient(hostname, access_code, serial) | self.fileClient = FileClient(hostname, access_code, serial) | 3 | 2023-12-16 05:31:56+00:00 | 8k |
linyq2117/TagCLIP | classify.py | [
{
"identifier": "scoremap2bbox",
"path": "utils.py",
"snippet": "def scoremap2bbox(scoremap, threshold, multi_contour_eval=False):\n height, width = scoremap.shape\n scoremap_image = np.expand_dims((scoremap * 255).astype(np.uint8), 2)\n _, thr_gray_heatmap = cv2.threshold(\n src=scorema... | import clip
import torch
import cv2
import numpy as np
import pickle
import os
import math
import torch.nn.functional as F
import os
import argparse
import warnings
from PIL import Image
from tqdm import tqdm
from lxml import etree
from utils import scoremap2bbox, parse_xml_to_dict, _convert_image_to_rgb, compute_AP, compute_F1, _transform_resize
from clip_text import class_names_voc, BACKGROUND_CATEGORY_VOC, class_names_coco, BACKGROUND_CATEGORY_COCO, class_names_coco_stuff182_dict, coco_stuff_182_to_27 | 4,339 | if len(array_img.shape) == 2:
array_img = np.stack([array_img, array_img, array_img], axis=2)
pil_img = Image.fromarray(np.uint8(array_img))
if model_type == 'clip':
patch_size = 16
preprocess = _transform_resize(int(np.ceil(int(ori_height) / patch_size) * patch_size), int(np.ceil(int(ori_width) / patch_size) * patch_size))
image = preprocess(pil_img).unsqueeze(0).to(device)
with torch.no_grad():
# Extract image features
h, w = image.shape[-2], image.shape[-1]
image_features, attn_weight_list = model.encode_image_tagclip(image, h, w, attn_mask=1)
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
attn_weight = [aw[:, 1:, 1:] for aw in attn_weight_list]
attn_vote = torch.stack(attn_weight, dim=0).squeeze()
thres0 = attn_vote.reshape(attn_vote.shape[0], -1)
thres0 = torch.mean(thres0, dim=-1).reshape(attn_vote.shape[0], 1, 1)
thres0 = thres0.repeat(1, attn_vote.shape[1], attn_vote.shape[2])
if args.dataset == 'cocostuff':
attn_weight = torch.stack(attn_weight, dim=0)[:-1]
else:
attn_weight = torch.stack(attn_weight, dim=0)[8:-1]
attn_cnt = attn_vote > thres0
attn_cnt = attn_cnt.float()
attn_cnt = torch.sum(attn_cnt, dim=0)
attn_cnt = attn_cnt >= 4
attn_weight = torch.mean(attn_weight, dim=0)[0]
attn_weight = attn_weight * attn_cnt.float()
logit_scale = model.logit_scale.exp()
logits = logit_scale * image_features @ text_features.t()#torch.Size([1, 197, 81])
logits = logits[:, 1:, :]
logits = logits.softmax(dim=-1)
logits_coarse = logits.squeeze()
logits = torch.matmul(attn_weight, logits)
logits = logits.squeeze()
logits = mask_attn(logits_coarse, logits, h, w, attn_weight)
logits_max = torch.max(logits, dim=0)[0]
logits_max = logits_max[:NUM_CLASSES]
logits_max = cwr(logits, logits_max, h, w, image, text_features)
logits_max = logits_max.cpu().numpy()
pred_label_id.append(logits_max)
else:
raise NotImplementedError()
gt_one_hot = np.zeros((len(gt_label_id), NUM_CLASSES))
for i in range(len(gt_label_id)):
gt_ids = gt_label_id[i]
for gt_id in gt_ids:
gt_one_hot[i][gt_id] = 1
predictions = torch.tensor(pred_label_id)
labels = torch.tensor(gt_one_hot)
# compute AP
ap = compute_AP(predictions, labels)
print('================================================')
print('mAP: %.6f' % torch.mean(ap))
# compute F1, P, R with specific relative threshold
ma = predictions.max(dim=1)[0]
mi = predictions.min(dim=1)[0]
step = ma - mi
if args.dataset == 'cocostuff':
thres_abs = 0.1
else:
thres_abs = 0.5
F1, P, R = compute_F1(predictions.clone(), labels.clone(), 'overall', thres_abs, use_relative=True)
print('F1: %.6f, Precision: %.6f, Recall: %.6f' % (torch.mean(F1), torch.mean(P), torch.mean(R)))
print('================================================\n')
#save class labels
if args.save_file:
save_path = './output/{}_val_tagclip.txt'.format(args.dataset)
print('>>>writing to {}'.format(save_path))
thres_rel = mi + thres_abs * step
with open(save_path, 'w') as f:
for im_idx, im in enumerate(image_list):
line = im.replace('.jpg','')
for index, value in enumerate(pred_label_id[im_idx]):
if value > thres_rel[im_idx]:
line += " {}".format(index)
if line == im.replace('.jpg',''):
line += " {}".format(np.argmax(pred_label_id[im_idx]))
line += "\n"
f.writelines(line)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='')
parser.add_argument('--dataset', type=str, default='voc2007', choices=['voc2007', 'voc2012', 'coco2014', 'coco2017', 'cocostuff'])
parser.add_argument('--img_root', type=str, default='./datasets/VOC2007/JPEGImages')
parser.add_argument('--split_file', type=str, default='./datasets/VOC2007/ImageSets/Main/test.txt')
parser.add_argument('--model_path', type=str, default='ViT-B/16')
parser.add_argument('--save_file', action="store_true")
args = parser.parse_args()
if args.dataset in ['voc2007', 'voc2012']:
class_names = class_names_voc + BACKGROUND_CATEGORY_VOC
NUM_CLASSES = len(class_names_voc)
elif args.dataset in ['coco2014', 'coco2017']:
class_names = class_names_coco + BACKGROUND_CATEGORY_COCO
NUM_CLASSES = len(class_names_coco)
else:
coco_stuff_182_to_171 = {}
cnt = 0
|
warnings.filterwarnings("ignore")
def mask_attn(logits_coarse, logits, h, w, attn_weight):
patch_size = 16
candidate_cls_list = []
logits_refined = logits.clone()
logits_max = torch.max(logits, dim=0)[0]
for tempid,tempv in enumerate(logits_max):
if tempv > 0:
candidate_cls_list.append(tempid)
for ccls in candidate_cls_list:
temp_logits = logits[:,ccls]
temp_logits = temp_logits - temp_logits.min()
temp_logits = temp_logits / temp_logits.max()
mask = temp_logits
mask = mask.reshape(h // patch_size, w // patch_size)
box, cnt = scoremap2bbox(mask.detach().cpu().numpy(), threshold=temp_logits.mean(), multi_contour_eval=True)
aff_mask = torch.zeros((mask.shape[0],mask.shape[1])).to(device)
for i_ in range(cnt):
x0_, y0_, x1_, y1_ = box[i_]
aff_mask[y0_:y1_, x0_:x1_] = 1
aff_mask = aff_mask.view(1,mask.shape[0] * mask.shape[1])
trans_mat = attn_weight * aff_mask
logits_refined_ccls = torch.matmul(trans_mat, logits_coarse[:,ccls:ccls+1])
logits_refined[:, ccls] = logits_refined_ccls.squeeze()
return logits_refined
def cwr(logits, logits_max, h, w, image, text_features):
patch_size = 16
input_size = 224
stride = input_size // patch_size
candidate_cls_list = []
ma = logits.max()
mi = logits.min()
step = ma - mi
if args.dataset == 'cocostuff':
thres_abs = 0.1
else:
thres_abs = 0.5
thres = mi + thres_abs*step
for tempid,tempv in enumerate(logits_max):
if tempv > thres:
candidate_cls_list.append(tempid)
for ccls in candidate_cls_list:
temp_logits = logits[:,ccls]
temp_logits = temp_logits - temp_logits.min()
temp_logits = temp_logits / temp_logits.max()
mask = temp_logits > 0.5
mask = mask.reshape(h // patch_size, w // patch_size)
horizontal_indicies = np.where(np.any(mask.cpu().numpy(), axis=0))[0]
vertical_indicies = np.where(np.any(mask.cpu().numpy(), axis=1))[0]
if horizontal_indicies.shape[0]:
x1, x2 = horizontal_indicies[[0, -1]]
y1, y2 = vertical_indicies[[0, -1]]
x2 += 1
y2 += 1
else:
x1, x2, y1, y2 = 0, 0, 0, 0
y1 = max(y1, 0)
x1 = max(x1, 0)
y2 = min(y2, mask.shape[-2] - 1)
x2 = min(x2, mask.shape[-1] - 1)
if x1 == x2 or y1 == y2:
return logits_max
mask = mask[y1:y2, x1:x2]
mask = mask.float()
mask = mask[None, None, :, :]
mask = F.interpolate(mask, size=(stride, stride), mode="nearest")
mask = mask.squeeze()
mask = mask.reshape(-1).bool()
image_cut = image[:, :, int(y1*patch_size):int(y2*patch_size), int(x1*patch_size):int(x2*patch_size)]
image_cut = F.interpolate(image_cut, size=(input_size, input_size), mode="bilinear", align_corners=False)
cls_attn = 1 - torch.ones((stride*stride+1, stride*stride+1))
for j in range(1, cls_attn.shape[1]):
if not mask[j - 1]:
cls_attn[0, j] = -1000
image_features = model.encode_image_tagclip(image_cut, input_size, input_size, attn_mask=cls_attn)[0]
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
logit_scale = model.logit_scale.exp()
cur_logits = logit_scale * image_features @ text_features.t()
cur_logits = cur_logits[:, 0, :]
cur_logits = cur_logits.softmax(dim=-1).squeeze()
cur_logits_norm = cur_logits[ccls]
logits_max[ccls] = 0.5 * logits_max[ccls] + (1 - 0.5) * cur_logits_norm
return logits_max
def classify():
pred_label_id = []
gt_label_id = []
with torch.no_grad():
text_features = clip.encode_text_with_prompt_ensemble(model, class_names, device)
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
for im_idx, im in enumerate(tqdm(image_list)):
image_path = os.path.join(args.img_root, im)
label_id_list = all_label_list[im_idx]
label_id_list = [int(lid) for lid in label_id_list]
if args.dataset == 'cocostuff':
label_id_list = [coco_stuff_182_to_171[int(lid)] for lid in label_id_list]
gt_label_id.append(label_id_list)
pil_img = Image.open(image_path)
array_img = np.array(pil_img)
ori_height, ori_width = array_img.shape[:2]
if len(array_img.shape) == 2:
array_img = np.stack([array_img, array_img, array_img], axis=2)
pil_img = Image.fromarray(np.uint8(array_img))
if model_type == 'clip':
patch_size = 16
preprocess = _transform_resize(int(np.ceil(int(ori_height) / patch_size) * patch_size), int(np.ceil(int(ori_width) / patch_size) * patch_size))
image = preprocess(pil_img).unsqueeze(0).to(device)
with torch.no_grad():
# Extract image features
h, w = image.shape[-2], image.shape[-1]
image_features, attn_weight_list = model.encode_image_tagclip(image, h, w, attn_mask=1)
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
attn_weight = [aw[:, 1:, 1:] for aw in attn_weight_list]
attn_vote = torch.stack(attn_weight, dim=0).squeeze()
thres0 = attn_vote.reshape(attn_vote.shape[0], -1)
thres0 = torch.mean(thres0, dim=-1).reshape(attn_vote.shape[0], 1, 1)
thres0 = thres0.repeat(1, attn_vote.shape[1], attn_vote.shape[2])
if args.dataset == 'cocostuff':
attn_weight = torch.stack(attn_weight, dim=0)[:-1]
else:
attn_weight = torch.stack(attn_weight, dim=0)[8:-1]
attn_cnt = attn_vote > thres0
attn_cnt = attn_cnt.float()
attn_cnt = torch.sum(attn_cnt, dim=0)
attn_cnt = attn_cnt >= 4
attn_weight = torch.mean(attn_weight, dim=0)[0]
attn_weight = attn_weight * attn_cnt.float()
logit_scale = model.logit_scale.exp()
logits = logit_scale * image_features @ text_features.t()#torch.Size([1, 197, 81])
logits = logits[:, 1:, :]
logits = logits.softmax(dim=-1)
logits_coarse = logits.squeeze()
logits = torch.matmul(attn_weight, logits)
logits = logits.squeeze()
logits = mask_attn(logits_coarse, logits, h, w, attn_weight)
logits_max = torch.max(logits, dim=0)[0]
logits_max = logits_max[:NUM_CLASSES]
logits_max = cwr(logits, logits_max, h, w, image, text_features)
logits_max = logits_max.cpu().numpy()
pred_label_id.append(logits_max)
else:
raise NotImplementedError()
gt_one_hot = np.zeros((len(gt_label_id), NUM_CLASSES))
for i in range(len(gt_label_id)):
gt_ids = gt_label_id[i]
for gt_id in gt_ids:
gt_one_hot[i][gt_id] = 1
predictions = torch.tensor(pred_label_id)
labels = torch.tensor(gt_one_hot)
# compute AP
ap = compute_AP(predictions, labels)
print('================================================')
print('mAP: %.6f' % torch.mean(ap))
# compute F1, P, R with specific relative threshold
ma = predictions.max(dim=1)[0]
mi = predictions.min(dim=1)[0]
step = ma - mi
if args.dataset == 'cocostuff':
thres_abs = 0.1
else:
thres_abs = 0.5
F1, P, R = compute_F1(predictions.clone(), labels.clone(), 'overall', thres_abs, use_relative=True)
print('F1: %.6f, Precision: %.6f, Recall: %.6f' % (torch.mean(F1), torch.mean(P), torch.mean(R)))
print('================================================\n')
#save class labels
if args.save_file:
save_path = './output/{}_val_tagclip.txt'.format(args.dataset)
print('>>>writing to {}'.format(save_path))
thres_rel = mi + thres_abs * step
with open(save_path, 'w') as f:
for im_idx, im in enumerate(image_list):
line = im.replace('.jpg','')
for index, value in enumerate(pred_label_id[im_idx]):
if value > thres_rel[im_idx]:
line += " {}".format(index)
if line == im.replace('.jpg',''):
line += " {}".format(np.argmax(pred_label_id[im_idx]))
line += "\n"
f.writelines(line)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='')
parser.add_argument('--dataset', type=str, default='voc2007', choices=['voc2007', 'voc2012', 'coco2014', 'coco2017', 'cocostuff'])
parser.add_argument('--img_root', type=str, default='./datasets/VOC2007/JPEGImages')
parser.add_argument('--split_file', type=str, default='./datasets/VOC2007/ImageSets/Main/test.txt')
parser.add_argument('--model_path', type=str, default='ViT-B/16')
parser.add_argument('--save_file', action="store_true")
args = parser.parse_args()
if args.dataset in ['voc2007', 'voc2012']:
class_names = class_names_voc + BACKGROUND_CATEGORY_VOC
NUM_CLASSES = len(class_names_voc)
elif args.dataset in ['coco2014', 'coco2017']:
class_names = class_names_coco + BACKGROUND_CATEGORY_COCO
NUM_CLASSES = len(class_names_coco)
else:
coco_stuff_182_to_171 = {}
cnt = 0 | for label_id in coco_stuff_182_to_27: | 6 | 2023-12-21 03:20:47+00:00 | 8k |
video-db/videodb-python | videodb/client.py | [
{
"identifier": "ApiPath",
"path": "videodb/_constants.py",
"snippet": "class ApiPath:\n collection = \"collection\"\n upload = \"upload\"\n video = \"video\"\n stream = \"stream\"\n thumbnail = \"thumbnail\"\n upload_url = \"upload_url\"\n transcription = \"transcription\"\n ind... | import logging
from typing import (
Optional,
)
from videodb._constants import (
ApiPath,
)
from videodb.collection import Collection
from videodb._utils._http_client import HttpClient
from videodb.video import Video
from videodb._upload import (
upload,
) | 4,129 |
logger = logging.getLogger(__name__)
class Connection(HttpClient):
def __init__(self, api_key: str, base_url: str) -> None:
self.api_key = api_key
self.base_url = base_url
self.collection_id = "default"
super().__init__(api_key, base_url)
def get_collection(self, collection_id: Optional[str] = "default") -> Collection:
|
logger = logging.getLogger(__name__)
class Connection(HttpClient):
def __init__(self, api_key: str, base_url: str) -> None:
self.api_key = api_key
self.base_url = base_url
self.collection_id = "default"
super().__init__(api_key, base_url)
def get_collection(self, collection_id: Optional[str] = "default") -> Collection: | collection_data = self.get(path=f"{ApiPath.collection}/{collection_id}") | 0 | 2023-12-18 15:20:04+00:00 | 8k |
IDEA-CCNL/Real-Gemini | real_gemini/agent.py | [
{
"identifier": "GPT4VTool",
"path": "real_gemini/tools/gpt4v_tool.py",
"snippet": "class GPT4VTool(object):\n _name_ = \"GPT-4-Vision\"\n _description_ = \"这个工具是GPT for vision的调用接口。用于图像到文本的理解。本工具的输入是一段文本指令和一张或者多张图片,请注意,工具的输入由一个JSON字符串组成,json包括两个key,question和image_input。question表示文本指令,image_input表... | import os
import re
import json
from langchain.chat_models import ChatOpenAI
from langchain.agents.tools import Tool
from langchain.agents import initialize_agent, load_tools, AgentType
from langchain.prompts import PromptTemplate
from langchain.memory import ConversationBufferMemory
from .tools.gpt4v_tool import GPT4VTool
from .tools.image_generation_tool import TaiyiGeneralTool
from .tools.music_tool import Text2MusicTool
from .tools.controlnet_tool import Image2PoseTool
from .tools.sam_tool import SegmentingTool
from .tools.dino_tool import Text2BoxTool
from .tools.imageediting_tool import ImageRemoveTool, ImageReplaceTool
from .tools.weather_tool import WeatherTool
from .utils.output_parser import ConvoOutputParser
from .utils.agent_prompt import PREFIX, FORMAT_INSTRUCTIONS, SUFFIX | 5,879 | #encoding=utf8
REGISTERED_TOOL_CLASSES = [
GPT4VTool,
TaiyiGeneralTool,
Text2MusicTool,
| #encoding=utf8
REGISTERED_TOOL_CLASSES = [
GPT4VTool,
TaiyiGeneralTool,
Text2MusicTool, | SegmentingTool, | 4 | 2023-12-15 04:09:37+00:00 | 8k |
aiim-research/GRETEL | src/evaluation/evaluator_manager_do.py | [
{
"identifier": "DatasetFactory",
"path": "src/dataset/dataset_factory.py",
"snippet": "class DatasetFactory(Factory):\n\n def get_dataset(self, dataset_snippet):\n return self._get_object(dataset_snippet)\n \n def get_datasets(self, config_list):\n return [self.get_datase... | import random
from src.dataset.dataset_factory import DatasetFactory
from src.evaluation.evaluation_metric_factory import EvaluationMetricFactory
from src.evaluation.evaluator_base import Evaluator
from src.explainer.explainer_factory import ExplainerFactory
from src.oracle.embedder_factory import EmbedderFactory
from src.oracle.oracle_factory import OracleFactory
from src.utils.context import Context | 5,879 |
class EvaluatorManager:
def __init__(self, context: Context) -> None:
self.context = context
self._output_store_path = self.context.output_store_path
self._evaluators = []
#NOTE: Move the Factories creation outside?
self.context.factories['datasets'] = DatasetFactory(context)
self.context.factories['embedders'] = EmbedderFactory(context)
|
class EvaluatorManager:
def __init__(self, context: Context) -> None:
self.context = context
self._output_store_path = self.context.output_store_path
self._evaluators = []
#NOTE: Move the Factories creation outside?
self.context.factories['datasets'] = DatasetFactory(context)
self.context.factories['embedders'] = EmbedderFactory(context) | self.context.factories['oracles'] = OracleFactory(context) | 5 | 2023-12-15 16:34:16+00:00 | 8k |
modelscope/scepter | scepter/modules/annotator/openpose.py | [
{
"identifier": "BaseAnnotator",
"path": "scepter/modules/annotator/base_annotator.py",
"snippet": "class BaseAnnotator(BaseModel, metaclass=ABCMeta):\n para_dict = {}\n\n def __init__(self, cfg, logger=None):\n super().__init__(cfg, logger=logger)\n\n @torch.no_grad()\n @torch.infere... | import math
import os
import cv2
import matplotlib
import numpy as np
import torch
import torch.nn as nn
from abc import ABCMeta
from collections import OrderedDict
from PIL import Image
from scipy.ndimage.filters import gaussian_filter
from skimage.measure import label
from scepter.modules.annotator.base_annotator import BaseAnnotator
from scepter.modules.annotator.registry import ANNOTATORS
from scepter.modules.utils.config import dict_to_yaml
from scepter.modules.utils.file_system import FS | 5,088 | startend = list(
zip(
np.linspace(candA[i][0],
candB[j][0],
num=mid_num),
np.linspace(candA[i][1],
candB[j][1],
num=mid_num)))
vec_x = np.array([
score_mid[int(round(startend[ii][1])),
int(round(startend[ii][0])), 0]
for ii in range(len(startend))
])
vec_y = np.array([
score_mid[int(round(startend[ii][1])),
int(round(startend[ii][0])), 1]
for ii in range(len(startend))
])
score_midpts = np.multiply(
vec_x, vec[0]) + np.multiply(vec_y, vec[1])
score_with_dist_prior = sum(score_midpts) / len(
score_midpts) + min(
0.5 * oriImg.shape[0] / norm - 1, 0)
criterion1 = len(np.nonzero(
score_midpts > thre2)[0]) > 0.8 * len(score_midpts)
criterion2 = score_with_dist_prior > 0
if criterion1 and criterion2:
connection_candidate.append([
i, j, score_with_dist_prior,
score_with_dist_prior + candA[i][2] +
candB[j][2]
])
connection_candidate = sorted(connection_candidate,
key=lambda x: x[2],
reverse=True)
connection = np.zeros((0, 5))
for c in range(len(connection_candidate)):
i, j, s = connection_candidate[c][0:3]
if (i not in connection[:, 3]
and j not in connection[:, 4]):
connection = np.vstack(
[connection, [candA[i][3], candB[j][3], s, i, j]])
if (len(connection) >= min(nA, nB)):
break
connection_all.append(connection)
else:
special_k.append(k)
connection_all.append([])
# last number in each row is the total parts number of that person
# the second last number in each row is the score of the overall configuration
subset = -1 * np.ones((0, 20))
candidate = np.array(
[item for sublist in all_peaks for item in sublist])
for k in range(len(mapIdx)):
if k not in special_k:
partAs = connection_all[k][:, 0]
partBs = connection_all[k][:, 1]
indexA, indexB = np.array(limbSeq[k]) - 1
for i in range(len(connection_all[k])): # = 1:size(temp,1)
found = 0
subset_idx = [-1, -1]
for j in range(len(subset)): # 1:size(subset,1):
if subset[j][indexA] == partAs[i] or subset[j][
indexB] == partBs[i]:
subset_idx[found] = j
found += 1
if found == 1:
j = subset_idx[0]
if subset[j][indexB] != partBs[i]:
subset[j][indexB] = partBs[i]
subset[j][-1] += 1
subset[j][-2] += candidate[
partBs[i].astype(int),
2] + connection_all[k][i][2]
elif found == 2: # if found 2 and disjoint, merge them
j1, j2 = subset_idx
membership = ((subset[j1] >= 0).astype(int) +
(subset[j2] >= 0).astype(int))[:-2]
if len(np.nonzero(membership == 2)[0]) == 0: # merge
subset[j1][:-2] += (subset[j2][:-2] + 1)
subset[j1][-2:] += subset[j2][-2:]
subset[j1][-2] += connection_all[k][i][2]
subset = np.delete(subset, j2, 0)
else: # as like found == 1
subset[j1][indexB] = partBs[i]
subset[j1][-1] += 1
subset[j1][-2] += candidate[
partBs[i].astype(int),
2] + connection_all[k][i][2]
# if find no partA in the subset, create a new subset
elif not found and k < 17:
row = -1 * np.ones(20)
row[indexA] = partAs[i]
row[indexB] = partBs[i]
row[-1] = 2
row[-2] = sum(
candidate[connection_all[k][i, :2].astype(int),
2]) + connection_all[k][i][2]
subset = np.vstack([subset, row])
# delete some rows of subset which has few parts occur
deleteIdx = []
for i in range(len(subset)):
if subset[i][-1] < 4 or subset[i][-2] / subset[i][-1] < 0.4:
deleteIdx.append(i)
subset = np.delete(subset, deleteIdx, axis=0)
# subset: n*20 array, 0-17 is the index in candidate, 18 is the total score, 19 is the total parts
# candidate: x, y, score, id
return candidate, subset
| # -*- coding: utf-8 -*-
# Openpose
# Original from CMU https://github.com/CMU-Perceptual-Computing-Lab/openpose
# 2nd Edited by https://github.com/Hzzone/pytorch-openpose
# The implementation is modified from 3rd Edited Version by ControlNet
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
def padRightDownCorner(img, stride, padValue):
h = img.shape[0]
w = img.shape[1]
pad = 4 * [None]
pad[0] = 0 # up
pad[1] = 0 # left
pad[2] = 0 if (h % stride == 0) else stride - (h % stride) # down
pad[3] = 0 if (w % stride == 0) else stride - (w % stride) # right
img_padded = img
pad_up = np.tile(img_padded[0:1, :, :] * 0 + padValue, (pad[0], 1, 1))
img_padded = np.concatenate((pad_up, img_padded), axis=0)
pad_left = np.tile(img_padded[:, 0:1, :] * 0 + padValue, (1, pad[1], 1))
img_padded = np.concatenate((pad_left, img_padded), axis=1)
pad_down = np.tile(img_padded[-2:-1, :, :] * 0 + padValue, (pad[2], 1, 1))
img_padded = np.concatenate((img_padded, pad_down), axis=0)
pad_right = np.tile(img_padded[:, -2:-1, :] * 0 + padValue, (1, pad[3], 1))
img_padded = np.concatenate((img_padded, pad_right), axis=1)
return img_padded, pad
# transfer caffe model to pytorch which will match the layer name
def transfer(model, model_weights):
transfered_model_weights = {}
for weights_name in model.state_dict().keys():
transfered_model_weights[weights_name] = model_weights['.'.join(
weights_name.split('.')[1:])]
return transfered_model_weights
# draw the body keypoint and lims
def draw_bodypose(canvas, candidate, subset):
stickwidth = 4
limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10],
[10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15],
[15, 17], [1, 16], [16, 18], [3, 17], [6, 18]]
colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0],
[170, 255, 0], [85, 255, 0], [0, 255, 0], [0, 255, 85],
[0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255],
[0, 0, 255], [85, 0, 255], [170, 0, 255], [255, 0, 255],
[255, 0, 170], [255, 0, 85]]
for i in range(18):
for n in range(len(subset)):
index = int(subset[n][i])
if index == -1:
continue
x, y = candidate[index][0:2]
cv2.circle(canvas, (int(x), int(y)), 4, colors[i], thickness=-1)
for i in range(17):
for n in range(len(subset)):
index = subset[n][np.array(limbSeq[i]) - 1]
if -1 in index:
continue
cur_canvas = canvas.copy()
Y = candidate[index.astype(int), 0]
X = candidate[index.astype(int), 1]
mX = np.mean(X)
mY = np.mean(Y)
length = ((X[0] - X[1])**2 + (Y[0] - Y[1])**2)**0.5
angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
polygon = cv2.ellipse2Poly(
(int(mY), int(mX)), (int(length / 2), stickwidth), int(angle),
0, 360, 1)
cv2.fillConvexPoly(cur_canvas, polygon, colors[i])
canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)
# plt.imsave("preview.jpg", canvas[:, :, [2, 1, 0]])
# plt.imshow(canvas[:, :, [2, 1, 0]])
return canvas
# image drawed by opencv is not good.
def draw_handpose(canvas, all_hand_peaks, show_number=False):
edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8],
[0, 9], [9, 10], [10, 11], [11, 12], [0, 13], [13, 14], [14, 15],
[15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]
for peaks in all_hand_peaks:
for ie, e in enumerate(edges):
if np.sum(np.all(peaks[e], axis=1) == 0) == 0:
x1, y1 = peaks[e[0]]
x2, y2 = peaks[e[1]]
cv2.line(canvas, (x1, y1), (x2, y2),
matplotlib.colors.hsv_to_rgb(
[ie / float(len(edges)), 1.0, 1.0]) * 255,
thickness=2)
for i, keyponit in enumerate(peaks):
x, y = keyponit
cv2.circle(canvas, (x, y), 4, (0, 0, 255), thickness=-1)
if show_number:
cv2.putText(canvas,
str(i), (x, y),
cv2.FONT_HERSHEY_SIMPLEX,
0.3, (0, 0, 0),
lineType=cv2.LINE_AA)
return canvas
# detect hand according to body pose keypoints
# please refer to https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/
# master/src/openpose/hand/handDetector.cpp
def handDetect(candidate, subset, oriImg):
# right hand: wrist 4, elbow 3, shoulder 2
# left hand: wrist 7, elbow 6, shoulder 5
ratioWristElbow = 0.33
detect_result = []
image_height, image_width = oriImg.shape[0:2]
for person in subset.astype(int):
# if any of three not detected
has_left = np.sum(person[[5, 6, 7]] == -1) == 0
has_right = np.sum(person[[2, 3, 4]] == -1) == 0
if not (has_left or has_right):
continue
hands = []
# left hand
if has_left:
left_shoulder_index, left_elbow_index, left_wrist_index = person[[
5, 6, 7
]]
x1, y1 = candidate[left_shoulder_index][:2]
x2, y2 = candidate[left_elbow_index][:2]
x3, y3 = candidate[left_wrist_index][:2]
hands.append([x1, y1, x2, y2, x3, y3, True])
# right hand
if has_right:
right_shoulder_index, right_elbow_index, right_wrist_index = person[
[2, 3, 4]]
x1, y1 = candidate[right_shoulder_index][:2]
x2, y2 = candidate[right_elbow_index][:2]
x3, y3 = candidate[right_wrist_index][:2]
hands.append([x1, y1, x2, y2, x3, y3, False])
for x1, y1, x2, y2, x3, y3, is_left in hands:
# pos_hand = pos_wrist + ratio * (pos_wrist - pos_elbox) = (1 + ratio) * pos_wrist - ratio * pos_elbox
# handRectangle.x = posePtr[wrist*3] + ratioWristElbow * (posePtr[wrist*3] - posePtr[elbow*3]);
# handRectangle.y = posePtr[wrist*3+1] + ratioWristElbow * (posePtr[wrist*3+1] - posePtr[elbow*3+1]);
# const auto distanceWristElbow = getDistance(poseKeypoints, person, wrist, elbow);
# const auto distanceElbowShoulder = getDistance(poseKeypoints, person, elbow, shoulder);
# handRectangle.width = 1.5f * fastMax(distanceWristElbow, 0.9f * distanceElbowShoulder);
x = x3 + ratioWristElbow * (x3 - x2)
y = y3 + ratioWristElbow * (y3 - y2)
distanceWristElbow = math.sqrt((x3 - x2)**2 + (y3 - y2)**2)
distanceElbowShoulder = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
width = 1.5 * max(distanceWristElbow, 0.9 * distanceElbowShoulder)
# x-y refers to the center --> offset to topLeft point
# handRectangle.x -= handRectangle.width / 2.f;
# handRectangle.y -= handRectangle.height / 2.f;
x -= width / 2
y -= width / 2 # width = height
# overflow the image
if x < 0:
x = 0
if y < 0:
y = 0
width1 = width
width2 = width
if x + width > image_width:
width1 = image_width - x
if y + width > image_height:
width2 = image_height - y
width = min(width1, width2)
# the max hand box value is 20 pixels
if width >= 20:
detect_result.append([int(x), int(y), int(width), is_left])
'''
return value: [[x, y, w, True if left hand else False]].
width=height since the network require squared input.
x, y is the coordinate of top left
'''
return detect_result
# get max index of 2d array
def npmax(array):
arrayindex = array.argmax(1)
arrayvalue = array.max(1)
i = arrayvalue.argmax()
j = arrayindex[i]
return i, j
def make_layers(block, no_relu_layers):
layers = []
for layer_name, v in block.items():
if 'pool' in layer_name:
layer = nn.MaxPool2d(kernel_size=v[0], stride=v[1], padding=v[2])
layers.append((layer_name, layer))
else:
conv2d = nn.Conv2d(in_channels=v[0],
out_channels=v[1],
kernel_size=v[2],
stride=v[3],
padding=v[4])
layers.append((layer_name, conv2d))
if layer_name not in no_relu_layers:
layers.append(('relu_' + layer_name, nn.ReLU(inplace=True)))
return nn.Sequential(OrderedDict(layers))
class bodypose_model(nn.Module):
def __init__(self):
super(bodypose_model, self).__init__()
# these layers have no relu layer
no_relu_layers = [
'conv5_5_CPM_L1', 'conv5_5_CPM_L2', 'Mconv7_stage2_L1',
'Mconv7_stage2_L2', 'Mconv7_stage3_L1', 'Mconv7_stage3_L2',
'Mconv7_stage4_L1', 'Mconv7_stage4_L2', 'Mconv7_stage5_L1',
'Mconv7_stage5_L2', 'Mconv7_stage6_L1', 'Mconv7_stage6_L1'
]
blocks = {}
block0 = OrderedDict([('conv1_1', [3, 64, 3, 1, 1]),
('conv1_2', [64, 64, 3, 1, 1]),
('pool1_stage1', [2, 2, 0]),
('conv2_1', [64, 128, 3, 1, 1]),
('conv2_2', [128, 128, 3, 1, 1]),
('pool2_stage1', [2, 2, 0]),
('conv3_1', [128, 256, 3, 1, 1]),
('conv3_2', [256, 256, 3, 1, 1]),
('conv3_3', [256, 256, 3, 1, 1]),
('conv3_4', [256, 256, 3, 1, 1]),
('pool3_stage1', [2, 2, 0]),
('conv4_1', [256, 512, 3, 1, 1]),
('conv4_2', [512, 512, 3, 1, 1]),
('conv4_3_CPM', [512, 256, 3, 1, 1]),
('conv4_4_CPM', [256, 128, 3, 1, 1])])
# Stage 1
block1_1 = OrderedDict([('conv5_1_CPM_L1', [128, 128, 3, 1, 1]),
('conv5_2_CPM_L1', [128, 128, 3, 1, 1]),
('conv5_3_CPM_L1', [128, 128, 3, 1, 1]),
('conv5_4_CPM_L1', [128, 512, 1, 1, 0]),
('conv5_5_CPM_L1', [512, 38, 1, 1, 0])])
block1_2 = OrderedDict([('conv5_1_CPM_L2', [128, 128, 3, 1, 1]),
('conv5_2_CPM_L2', [128, 128, 3, 1, 1]),
('conv5_3_CPM_L2', [128, 128, 3, 1, 1]),
('conv5_4_CPM_L2', [128, 512, 1, 1, 0]),
('conv5_5_CPM_L2', [512, 19, 1, 1, 0])])
blocks['block1_1'] = block1_1
blocks['block1_2'] = block1_2
self.model0 = make_layers(block0, no_relu_layers)
# Stages 2 - 6
for i in range(2, 7):
blocks['block%d_1' % i] = OrderedDict([
('Mconv1_stage%d_L1' % i, [185, 128, 7, 1, 3]),
('Mconv2_stage%d_L1' % i, [128, 128, 7, 1, 3]),
('Mconv3_stage%d_L1' % i, [128, 128, 7, 1, 3]),
('Mconv4_stage%d_L1' % i, [128, 128, 7, 1, 3]),
('Mconv5_stage%d_L1' % i, [128, 128, 7, 1, 3]),
('Mconv6_stage%d_L1' % i, [128, 128, 1, 1, 0]),
('Mconv7_stage%d_L1' % i, [128, 38, 1, 1, 0])
])
blocks['block%d_2' % i] = OrderedDict([
('Mconv1_stage%d_L2' % i, [185, 128, 7, 1, 3]),
('Mconv2_stage%d_L2' % i, [128, 128, 7, 1, 3]),
('Mconv3_stage%d_L2' % i, [128, 128, 7, 1, 3]),
('Mconv4_stage%d_L2' % i, [128, 128, 7, 1, 3]),
('Mconv5_stage%d_L2' % i, [128, 128, 7, 1, 3]),
('Mconv6_stage%d_L2' % i, [128, 128, 1, 1, 0]),
('Mconv7_stage%d_L2' % i, [128, 19, 1, 1, 0])
])
for k in blocks.keys():
blocks[k] = make_layers(blocks[k], no_relu_layers)
self.model1_1 = blocks['block1_1']
self.model2_1 = blocks['block2_1']
self.model3_1 = blocks['block3_1']
self.model4_1 = blocks['block4_1']
self.model5_1 = blocks['block5_1']
self.model6_1 = blocks['block6_1']
self.model1_2 = blocks['block1_2']
self.model2_2 = blocks['block2_2']
self.model3_2 = blocks['block3_2']
self.model4_2 = blocks['block4_2']
self.model5_2 = blocks['block5_2']
self.model6_2 = blocks['block6_2']
def forward(self, x):
out1 = self.model0(x)
out1_1 = self.model1_1(out1)
out1_2 = self.model1_2(out1)
out2 = torch.cat([out1_1, out1_2, out1], 1)
out2_1 = self.model2_1(out2)
out2_2 = self.model2_2(out2)
out3 = torch.cat([out2_1, out2_2, out1], 1)
out3_1 = self.model3_1(out3)
out3_2 = self.model3_2(out3)
out4 = torch.cat([out3_1, out3_2, out1], 1)
out4_1 = self.model4_1(out4)
out4_2 = self.model4_2(out4)
out5 = torch.cat([out4_1, out4_2, out1], 1)
out5_1 = self.model5_1(out5)
out5_2 = self.model5_2(out5)
out6 = torch.cat([out5_1, out5_2, out1], 1)
out6_1 = self.model6_1(out6)
out6_2 = self.model6_2(out6)
return out6_1, out6_2
class handpose_model(nn.Module):
def __init__(self):
super(handpose_model, self).__init__()
# these layers have no relu layer
no_relu_layers = [
'conv6_2_CPM', 'Mconv7_stage2', 'Mconv7_stage3', 'Mconv7_stage4',
'Mconv7_stage5', 'Mconv7_stage6'
]
# stage 1
block1_0 = OrderedDict([('conv1_1', [3, 64, 3, 1, 1]),
('conv1_2', [64, 64, 3, 1, 1]),
('pool1_stage1', [2, 2, 0]),
('conv2_1', [64, 128, 3, 1, 1]),
('conv2_2', [128, 128, 3, 1, 1]),
('pool2_stage1', [2, 2, 0]),
('conv3_1', [128, 256, 3, 1, 1]),
('conv3_2', [256, 256, 3, 1, 1]),
('conv3_3', [256, 256, 3, 1, 1]),
('conv3_4', [256, 256, 3, 1, 1]),
('pool3_stage1', [2, 2, 0]),
('conv4_1', [256, 512, 3, 1, 1]),
('conv4_2', [512, 512, 3, 1, 1]),
('conv4_3', [512, 512, 3, 1, 1]),
('conv4_4', [512, 512, 3, 1, 1]),
('conv5_1', [512, 512, 3, 1, 1]),
('conv5_2', [512, 512, 3, 1, 1]),
('conv5_3_CPM', [512, 128, 3, 1, 1])])
block1_1 = OrderedDict([('conv6_1_CPM', [128, 512, 1, 1, 0]),
('conv6_2_CPM', [512, 22, 1, 1, 0])])
blocks = {}
blocks['block1_0'] = block1_0
blocks['block1_1'] = block1_1
# stage 2-6
for i in range(2, 7):
blocks['block%d' % i] = OrderedDict([
('Mconv1_stage%d' % i, [150, 128, 7, 1, 3]),
('Mconv2_stage%d' % i, [128, 128, 7, 1, 3]),
('Mconv3_stage%d' % i, [128, 128, 7, 1, 3]),
('Mconv4_stage%d' % i, [128, 128, 7, 1, 3]),
('Mconv5_stage%d' % i, [128, 128, 7, 1, 3]),
('Mconv6_stage%d' % i, [128, 128, 1, 1, 0]),
('Mconv7_stage%d' % i, [128, 22, 1, 1, 0])
])
for k in blocks.keys():
blocks[k] = make_layers(blocks[k], no_relu_layers)
self.model1_0 = blocks['block1_0']
self.model1_1 = blocks['block1_1']
self.model2 = blocks['block2']
self.model3 = blocks['block3']
self.model4 = blocks['block4']
self.model5 = blocks['block5']
self.model6 = blocks['block6']
def forward(self, x):
out1_0 = self.model1_0(x)
out1_1 = self.model1_1(out1_0)
concat_stage2 = torch.cat([out1_1, out1_0], 1)
out_stage2 = self.model2(concat_stage2)
concat_stage3 = torch.cat([out_stage2, out1_0], 1)
out_stage3 = self.model3(concat_stage3)
concat_stage4 = torch.cat([out_stage3, out1_0], 1)
out_stage4 = self.model4(concat_stage4)
concat_stage5 = torch.cat([out_stage4, out1_0], 1)
out_stage5 = self.model5(concat_stage5)
concat_stage6 = torch.cat([out_stage5, out1_0], 1)
out_stage6 = self.model6(concat_stage6)
return out_stage6
class Hand(object):
def __init__(self, model_path, device='cuda'):
self.model = handpose_model()
if torch.cuda.is_available():
self.model = self.model.to(device)
model_dict = transfer(self.model, torch.load(model_path))
self.model.load_state_dict(model_dict)
self.model.eval()
self.device = device
def __call__(self, oriImg):
scale_search = [0.5, 1.0, 1.5, 2.0]
# scale_search = [0.5]
boxsize = 368
stride = 8
padValue = 128
thre = 0.05
multiplier = [x * boxsize / oriImg.shape[0] for x in scale_search]
heatmap_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 22))
# paf_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 38))
for m in range(len(multiplier)):
scale = multiplier[m]
imageToTest = cv2.resize(oriImg, (0, 0),
fx=scale,
fy=scale,
interpolation=cv2.INTER_CUBIC)
imageToTest_padded, pad = padRightDownCorner(
imageToTest, stride, padValue)
im = np.transpose(
np.float32(imageToTest_padded[:, :, :, np.newaxis]),
(3, 2, 0, 1)) / 256 - 0.5
im = np.ascontiguousarray(im)
data = torch.from_numpy(im).float()
if torch.cuda.is_available():
data = data.to(self.device)
# data = data.permute([2, 0, 1]).unsqueeze(0).float()
with torch.no_grad():
output = self.model(data).cpu().numpy()
# output = self.model(data).numpy()q
# extract outputs, resize, and remove padding
heatmap = np.transpose(np.squeeze(output),
(1, 2, 0)) # output 1 is heatmaps
heatmap = cv2.resize(heatmap, (0, 0),
fx=stride,
fy=stride,
interpolation=cv2.INTER_CUBIC)
heatmap = heatmap[:imageToTest_padded.shape[0] -
pad[2], :imageToTest_padded.shape[1] - pad[3], :]
heatmap = cv2.resize(heatmap, (oriImg.shape[1], oriImg.shape[0]),
interpolation=cv2.INTER_CUBIC)
heatmap_avg += heatmap / len(multiplier)
all_peaks = []
for part in range(21):
map_ori = heatmap_avg[:, :, part]
one_heatmap = gaussian_filter(map_ori, sigma=3)
binary = np.ascontiguousarray(one_heatmap > thre, dtype=np.uint8)
# 全部小于阈值
if np.sum(binary) == 0:
all_peaks.append([0, 0])
continue
label_img, label_numbers = label(binary,
return_num=True,
connectivity=binary.ndim)
max_index = np.argmax([
np.sum(map_ori[label_img == i])
for i in range(1, label_numbers + 1)
]) + 1
label_img[label_img != max_index] = 0
map_ori[label_img == 0] = 0
y, x = npmax(map_ori)
all_peaks.append([x, y])
return np.array(all_peaks)
class Body(object):
def __init__(self, model_path, device='cuda'):
self.model = bodypose_model()
if torch.cuda.is_available():
self.model = self.model.to(device)
model_dict = transfer(self.model, torch.load(model_path))
self.model.load_state_dict(model_dict)
self.model.eval()
self.device = device
def __call__(self, oriImg):
# scale_search = [0.5, 1.0, 1.5, 2.0]
scale_search = [0.5]
boxsize = 368
stride = 8
padValue = 128
thre1 = 0.1
thre2 = 0.05
multiplier = [x * boxsize / oriImg.shape[0] for x in scale_search]
heatmap_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 19))
paf_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 38))
for m in range(len(multiplier)):
scale = multiplier[m]
imageToTest = cv2.resize(oriImg, (0, 0),
fx=scale,
fy=scale,
interpolation=cv2.INTER_CUBIC)
imageToTest_padded, pad = padRightDownCorner(
imageToTest, stride, padValue)
im = np.transpose(
np.float32(imageToTest_padded[:, :, :, np.newaxis]),
(3, 2, 0, 1)) / 256 - 0.5
im = np.ascontiguousarray(im)
data = torch.from_numpy(im).float()
if torch.cuda.is_available():
data = data.to(self.device)
# data = data.permute([2, 0, 1]).unsqueeze(0).float()
with torch.no_grad():
Mconv7_stage6_L1, Mconv7_stage6_L2 = self.model(data)
Mconv7_stage6_L1 = Mconv7_stage6_L1.cpu().numpy()
Mconv7_stage6_L2 = Mconv7_stage6_L2.cpu().numpy()
# extract outputs, resize, and remove padding
# heatmap = np.transpose(np.squeeze(net.blobs[output_blobs.keys()[1]].data), (1, 2, 0))
# output 1 is heatmaps
heatmap = np.transpose(np.squeeze(Mconv7_stage6_L2),
(1, 2, 0)) # output 1 is heatmaps
heatmap = cv2.resize(heatmap, (0, 0),
fx=stride,
fy=stride,
interpolation=cv2.INTER_CUBIC)
heatmap = heatmap[:imageToTest_padded.shape[0] -
pad[2], :imageToTest_padded.shape[1] - pad[3], :]
heatmap = cv2.resize(heatmap, (oriImg.shape[1], oriImg.shape[0]),
interpolation=cv2.INTER_CUBIC)
# paf = np.transpose(np.squeeze(net.blobs[output_blobs.keys()[0]].data), (1, 2, 0)) # output 0 is PAFs
paf = np.transpose(np.squeeze(Mconv7_stage6_L1),
(1, 2, 0)) # output 0 is PAFs
paf = cv2.resize(paf, (0, 0),
fx=stride,
fy=stride,
interpolation=cv2.INTER_CUBIC)
paf = paf[:imageToTest_padded.shape[0] -
pad[2], :imageToTest_padded.shape[1] - pad[3], :]
paf = cv2.resize(paf, (oriImg.shape[1], oriImg.shape[0]),
interpolation=cv2.INTER_CUBIC)
heatmap_avg += heatmap_avg + heatmap / len(multiplier)
paf_avg += +paf / len(multiplier)
all_peaks = []
peak_counter = 0
for part in range(18):
map_ori = heatmap_avg[:, :, part]
one_heatmap = gaussian_filter(map_ori, sigma=3)
map_left = np.zeros(one_heatmap.shape)
map_left[1:, :] = one_heatmap[:-1, :]
map_right = np.zeros(one_heatmap.shape)
map_right[:-1, :] = one_heatmap[1:, :]
map_up = np.zeros(one_heatmap.shape)
map_up[:, 1:] = one_heatmap[:, :-1]
map_down = np.zeros(one_heatmap.shape)
map_down[:, :-1] = one_heatmap[:, 1:]
peaks_binary = np.logical_and.reduce(
(one_heatmap >= map_left, one_heatmap >= map_right,
one_heatmap >= map_up, one_heatmap >= map_down,
one_heatmap > thre1))
peaks = list(
zip(np.nonzero(peaks_binary)[1],
np.nonzero(peaks_binary)[0])) # note reverse
peaks_with_score = [x + (map_ori[x[1], x[0]], ) for x in peaks]
peak_id = range(peak_counter, peak_counter + len(peaks))
peaks_with_score_and_id = [
peaks_with_score[i] + (peak_id[i], )
for i in range(len(peak_id))
]
all_peaks.append(peaks_with_score_and_id)
peak_counter += len(peaks)
# find connection in the specified sequence, center 29 is in the position 15
limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9],
[9, 10], [10, 11], [2, 12], [12, 13], [13, 14], [2, 1],
[1, 15], [15, 17], [1, 16], [16, 18], [3, 17], [6, 18]]
# the middle joints heatmap correpondence
mapIdx = [[31, 32], [39, 40], [33, 34], [35, 36], [41, 42], [43, 44],
[19, 20], [21, 22], [23, 24], [25, 26], [27, 28], [29, 30],
[47, 48], [49, 50], [53, 54], [51, 52], [55, 56], [37, 38],
[45, 46]]
connection_all = []
special_k = []
mid_num = 10
for k in range(len(mapIdx)):
score_mid = paf_avg[:, :, [x - 19 for x in mapIdx[k]]]
candA = all_peaks[limbSeq[k][0] - 1]
candB = all_peaks[limbSeq[k][1] - 1]
nA = len(candA)
nB = len(candB)
indexA, indexB = limbSeq[k]
if (nA != 0 and nB != 0):
connection_candidate = []
for i in range(nA):
for j in range(nB):
vec = np.subtract(candB[j][:2], candA[i][:2])
norm = math.sqrt(vec[0] * vec[0] + vec[1] * vec[1])
norm = max(0.001, norm)
vec = np.divide(vec, norm)
startend = list(
zip(
np.linspace(candA[i][0],
candB[j][0],
num=mid_num),
np.linspace(candA[i][1],
candB[j][1],
num=mid_num)))
vec_x = np.array([
score_mid[int(round(startend[ii][1])),
int(round(startend[ii][0])), 0]
for ii in range(len(startend))
])
vec_y = np.array([
score_mid[int(round(startend[ii][1])),
int(round(startend[ii][0])), 1]
for ii in range(len(startend))
])
score_midpts = np.multiply(
vec_x, vec[0]) + np.multiply(vec_y, vec[1])
score_with_dist_prior = sum(score_midpts) / len(
score_midpts) + min(
0.5 * oriImg.shape[0] / norm - 1, 0)
criterion1 = len(np.nonzero(
score_midpts > thre2)[0]) > 0.8 * len(score_midpts)
criterion2 = score_with_dist_prior > 0
if criterion1 and criterion2:
connection_candidate.append([
i, j, score_with_dist_prior,
score_with_dist_prior + candA[i][2] +
candB[j][2]
])
connection_candidate = sorted(connection_candidate,
key=lambda x: x[2],
reverse=True)
connection = np.zeros((0, 5))
for c in range(len(connection_candidate)):
i, j, s = connection_candidate[c][0:3]
if (i not in connection[:, 3]
and j not in connection[:, 4]):
connection = np.vstack(
[connection, [candA[i][3], candB[j][3], s, i, j]])
if (len(connection) >= min(nA, nB)):
break
connection_all.append(connection)
else:
special_k.append(k)
connection_all.append([])
# last number in each row is the total parts number of that person
# the second last number in each row is the score of the overall configuration
subset = -1 * np.ones((0, 20))
candidate = np.array(
[item for sublist in all_peaks for item in sublist])
for k in range(len(mapIdx)):
if k not in special_k:
partAs = connection_all[k][:, 0]
partBs = connection_all[k][:, 1]
indexA, indexB = np.array(limbSeq[k]) - 1
for i in range(len(connection_all[k])): # = 1:size(temp,1)
found = 0
subset_idx = [-1, -1]
for j in range(len(subset)): # 1:size(subset,1):
if subset[j][indexA] == partAs[i] or subset[j][
indexB] == partBs[i]:
subset_idx[found] = j
found += 1
if found == 1:
j = subset_idx[0]
if subset[j][indexB] != partBs[i]:
subset[j][indexB] = partBs[i]
subset[j][-1] += 1
subset[j][-2] += candidate[
partBs[i].astype(int),
2] + connection_all[k][i][2]
elif found == 2: # if found 2 and disjoint, merge them
j1, j2 = subset_idx
membership = ((subset[j1] >= 0).astype(int) +
(subset[j2] >= 0).astype(int))[:-2]
if len(np.nonzero(membership == 2)[0]) == 0: # merge
subset[j1][:-2] += (subset[j2][:-2] + 1)
subset[j1][-2:] += subset[j2][-2:]
subset[j1][-2] += connection_all[k][i][2]
subset = np.delete(subset, j2, 0)
else: # as like found == 1
subset[j1][indexB] = partBs[i]
subset[j1][-1] += 1
subset[j1][-2] += candidate[
partBs[i].astype(int),
2] + connection_all[k][i][2]
# if find no partA in the subset, create a new subset
elif not found and k < 17:
row = -1 * np.ones(20)
row[indexA] = partAs[i]
row[indexB] = partBs[i]
row[-1] = 2
row[-2] = sum(
candidate[connection_all[k][i, :2].astype(int),
2]) + connection_all[k][i][2]
subset = np.vstack([subset, row])
# delete some rows of subset which has few parts occur
deleteIdx = []
for i in range(len(subset)):
if subset[i][-1] < 4 or subset[i][-2] / subset[i][-1] < 0.4:
deleteIdx.append(i)
subset = np.delete(subset, deleteIdx, axis=0)
# subset: n*20 array, 0-17 is the index in candidate, 18 is the total score, 19 is the total parts
# candidate: x, y, score, id
return candidate, subset
| @ANNOTATORS.register_class() | 1 | 2023-12-21 02:01:48+00:00 | 8k |
YyzHarry/shortcut-ood-fairness | learning/algorithms.py | [
{
"identifier": "networks",
"path": "models/networks.py",
"snippet": "class Identity(nn.Module):\nclass MLP(nn.Module):\nclass PretrainedImageModel(torch.nn.Module):\nclass ResNet(PretrainedImageModel):\nclass TimmModel(PretrainedImageModel):\nclass HubModel(PretrainedImageModel):\nclass ImportedModel(P... | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as autograd
import copy
import numpy as np
from transformers import get_scheduler
from models import networks
from learning import joint_dro
from learning.optimizers import get_optimizers
from utils.misc import mixup_data | 3,906 | loss_value = objective + (self.hparams['mmd_gamma'] * penalty)
return loss_value
class MMD(AbstractMMD):
"""MMD using Gaussian kernel"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(MMD, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes, gaussian=True)
class CORAL(AbstractMMD):
"""MMD using mean and covariance difference"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(CORAL, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes, gaussian=False)
class AbstractDANN(Algorithm):
"""Domain-Adversarial Neural Networks (abstract class)"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams,
grp_sizes=None, attr_sizes=None, conditional=False, class_balance=False):
super(AbstractDANN, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
self.register_buffer('update_count', torch.tensor([0]))
self.conditional = conditional
self.class_balance = class_balance
self.featurizer = networks.Featurizer(data_type, input_shape, self.hparams)
self.classifier = networks.Classifier(
self.featurizer.n_outputs,
num_classes,
self.hparams['nonlinear_classifier']
)
self.discriminator = networks.MLP(self.featurizer.n_outputs, num_attributes, self.hparams)
self.class_embeddings = nn.Embedding(num_classes, self.featurizer.n_outputs)
# optimizers
self.disc_opt = torch.optim.SGD(
(list(self.discriminator.parameters()) + list(self.class_embeddings.parameters())),
lr=self.hparams["lr_d"],
weight_decay=self.hparams['weight_decay_d'],
momentum=0.9)
self.gen_opt = torch.optim.SGD(
(list(self.featurizer.parameters()) + list(self.classifier.parameters())),
lr=self.hparams["lr_g"],
weight_decay=self.hparams['weight_decay_g'],
momentum=0.9)
def update(self, minibatch, step):
all_i, all_x, all_y, all_a = minibatch
self.update_count += 1
all_z = self.featurizer(all_x)
if self.conditional:
disc_input = all_z + self.class_embeddings(all_y)
else:
disc_input = all_z
disc_out = self.discriminator(disc_input)
if self.class_balance:
y_counts = F.one_hot(all_y).sum(dim=0)
weights = 1. / (y_counts[all_y] * y_counts.shape[0]).float()
disc_loss = F.cross_entropy(disc_out, all_a, reduction='none')
disc_loss = (weights * disc_loss).sum()
else:
disc_loss = F.cross_entropy(disc_out, all_a)
disc_softmax = F.softmax(disc_out, dim=1)
input_grad = autograd.grad(disc_softmax[:, all_a].sum(),
[disc_input], create_graph=True)[0]
grad_penalty = (input_grad ** 2).sum(dim=1).mean(dim=0)
disc_loss += self.hparams['grad_penalty'] * grad_penalty
d_steps_per_g = self.hparams['d_steps_per_g_step']
if self.update_count.item() % (1 + d_steps_per_g) < d_steps_per_g:
self.disc_opt.zero_grad()
disc_loss.backward()
self.disc_opt.step()
return {'disc_loss': disc_loss.item()}
else:
all_preds = self.classifier(all_z)
classifier_loss = F.cross_entropy(all_preds, all_y)
gen_loss = classifier_loss + (self.hparams['lambda'] * -disc_loss)
self.disc_opt.zero_grad()
self.gen_opt.zero_grad()
gen_loss.backward()
self.gen_opt.step()
return {'gen_loss': gen_loss.item()}
def return_feats(self, x):
return self.featurizer(x)
def predict(self, x):
return self.classifier(self.featurizer(x))
class DANN(AbstractDANN):
"""Unconditional DANN"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(DANN, self).__init__(data_type, input_shape, num_classes, num_attributes, num_examples, hparams,
grp_sizes, attr_sizes, conditional=False, class_balance=False)
class CDANN(AbstractDANN):
"""Conditional DANN"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(CDANN, self).__init__(data_type, input_shape, num_classes, num_attributes, num_examples, hparams,
grp_sizes, attr_sizes, conditional=True, class_balance=True)
class CVaRDRO(ERM):
"""
DRO with CVaR uncertainty set
https://arxiv.org/pdf/2010.05893.pdf
"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(CVaRDRO, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
|
ALGORITHMS = [
'ERM',
'StratifiedERM',
# subgroup methods
'GroupDRO',
'IRM',
'CVaRDRO',
'JTT',
'LISA',
'DFR',
# data augmentation
'Mixup',
# domain generalization methods
'MMD',
'CORAL',
'DANN',
'CDANN',
# imbalanced learning methods
'ReSample',
'ReWeight',
'SqrtReWeight',
'CBLoss',
'Focal',
'LDAM',
'BSoftmax',
'CRT',
'ReWeightCRT',
'VanillaCRT',
# flat minima optimizer
'MA',
'SAM',
# attribute balancing
'GroupDROAttr',
'ReSampleAttr',
'ReWeightAttr',
]
def get_algorithm_class(algorithm_name):
"""Return the algorithm class with the given name."""
if algorithm_name not in globals():
raise NotImplementedError("Algorithm not found: {}".format(algorithm_name))
return globals()[algorithm_name]
class Algorithm(torch.nn.Module):
"""
A subclass of Algorithm implements a subgroup robustness algorithm.
Subclasses should implement the following:
- _init_model()
- _compute_loss()
- update()
- return_feats()
- predict()
"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(Algorithm, self).__init__()
self.hparams = hparams
self.data_type = data_type
self.num_classes = num_classes
self.num_attributes = num_attributes
self.num_examples = num_examples
def _init_model(self):
raise NotImplementedError
def _compute_loss(self, i, x, y, a, step):
raise NotImplementedError
def update(self, minibatch, step):
"""Perform one update step."""
raise NotImplementedError
def return_feats(self, x):
raise NotImplementedError
def predict(self, x):
raise NotImplementedError
def return_groups(self, y, a):
"""Given a list of (y, a) tuples, return indexes of samples belonging to each subgroup"""
idx_g, idx_samples = [], []
all_g = y * self.num_attributes + a
for g in all_g.unique():
idx_g.append(g)
idx_samples.append(all_g == g)
return zip(idx_g, idx_samples)
@staticmethod
def return_attributes(all_a):
"""Given a list of attributes, return indexes of samples belonging to each attribute"""
idx_a, idx_samples = [], []
for a in all_a.unique():
idx_a.append(a)
idx_samples.append(all_a == a)
return zip(idx_a, idx_samples)
class ERM(Algorithm):
"""Empirical Risk Minimization (ERM)"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(ERM, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
self.featurizer = networks.Featurizer(data_type, input_shape, self.hparams)
self.classifier = networks.Classifier(
self.featurizer.n_outputs,
num_classes,
self.hparams['nonlinear_classifier']
)
self.network = nn.Sequential(self.featurizer, self.classifier)
self._init_model()
def _init_model(self):
self.clip_grad = (self.data_type == "text" and self.hparams["optimizer"] == "adamw")
if self.data_type in ["images", "tabular"]:
self.optimizer = get_optimizers[self.hparams['optimizer']](
self.network,
self.hparams['lr'],
self.hparams['weight_decay']
)
self.lr_scheduler = None
self.loss = torch.nn.CrossEntropyLoss(reduction="none")
elif self.data_type == "text":
self.network.zero_grad()
self.optimizer = get_optimizers[self.hparams["optimizer"]](
self.network,
self.hparams['lr'],
self.hparams['weight_decay']
)
self.lr_scheduler = get_scheduler(
"linear",
optimizer=self.optimizer,
num_warmup_steps=0,
num_training_steps=self.hparams["steps"]
)
self.loss = torch.nn.CrossEntropyLoss(reduction="none")
else:
raise NotImplementedError(f"{self.data_type} not supported.")
def _compute_loss(self, i, x, y, a, step):
return self.loss(self.predict(x), y).mean()
def update(self, minibatch, step):
all_i, all_x, all_y, all_a = minibatch
loss = self._compute_loss(all_i, all_x, all_y, all_a, step)
self.optimizer.zero_grad()
loss.backward()
if self.clip_grad:
torch.nn.utils.clip_grad_norm_(self.network.parameters(), 1.0)
self.optimizer.step()
if self.lr_scheduler is not None:
self.lr_scheduler.step()
if self.data_type == "text":
self.network.zero_grad()
return {'loss': loss.item()}
def return_feats(self, x):
return self.featurizer(x)
def predict(self, x):
return self.network(x)
class GroupDRO(ERM):
"""
Group DRO minimizes the error at the worst group [https://arxiv.org/pdf/1911.08731.pdf]
"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(GroupDRO, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
self.register_buffer(
"q", torch.ones(self.num_classes * self.num_attributes).cuda())
def _compute_loss(self, i, x, y, a, step):
losses = self.loss(self.predict(x), y)
for idx_g, idx_samples in self.return_groups(y, a):
self.q[idx_g] *= (self.hparams["groupdro_eta"] * losses[idx_samples].mean()).exp().item()
self.q /= self.q.sum()
loss_value = 0
for idx_g, idx_samples in self.return_groups(y, a):
loss_value += self.q[idx_g] * losses[idx_samples].mean()
return loss_value
class GroupDROAttr(ERM):
"""
GroupDROAttr minimizes the error at the worst attribute [https://arxiv.org/pdf/1911.08731.pdf]
"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(GroupDROAttr, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
self.register_buffer(
"q", torch.ones(self.num_attributes).cuda())
def _compute_loss(self, i, x, y, a, step):
losses = self.loss(self.predict(x), y)
for idx_a in range(self.num_attributes):
mask = (a == idx_a)
if mask.sum() > 0:
self.q[idx_a] *= (self.hparams["groupdro_eta"] * losses[mask].mean()).exp().item()
self.q /= self.q.sum()
loss_value = 0
for idx_a in range(self.num_attributes):
mask = (a == idx_a)
if mask.sum() > 0:
loss_value += self.q[idx_a] * losses[mask].mean()
return loss_value
class StratifiedERM(ERM):
"""No changes to ERM, but flags subsetting dataset"""
class ReSample(ERM):
"""Naive resample, with no changes to ERM, but enable balanced sampling in hparams"""
class ReSampleAttr(ERM):
"""Naive resample, with no changes to ERM, but enable balanced sampling in hparams"""
class ReWeightBase(ERM):
"""Naive inverse re-weighting"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None, group_def='group'):
super(ReWeightBase, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
self.group_def = group_def
if group_def == 'group':
assert len(grp_sizes) == num_classes * num_attributes
grp_sizes = [x if x else np.inf for x in grp_sizes]
elif group_def == 'attr':
assert len(attr_sizes) == num_attributes
grp_sizes = [x if x else np.inf for x in attr_sizes]
per_grp_weights = 1 / np.array(grp_sizes)
per_grp_weights = per_grp_weights / np.sum(per_grp_weights) * len(grp_sizes)
self.weights_per_grp = torch.FloatTensor(per_grp_weights)
def _compute_loss(self, i, x, y, a, step):
losses = self.loss(self.predict(x), y)
if self.group_def == 'group':
all_g = y * self.num_attributes + a
elif self.group_def == 'attr':
all_g = a
loss_value = (self.weights_per_grp.type_as(losses)[all_g] * losses).mean()
return loss_value
class ReWeight(ReWeightBase):
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(ReWeight, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes, 'group')
class ReWeightAttr(ReWeightBase):
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(ReWeightAttr, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes, 'attr')
class SqrtReWeight(ReWeight):
"""Square-root inverse re-weighting"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(SqrtReWeight, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
assert len(grp_sizes) == num_classes * num_attributes
grp_sizes = [x if x else np.inf for x in grp_sizes]
per_grp_weights = 1 / np.sqrt(np.array(grp_sizes))
per_grp_weights = per_grp_weights / np.sum(per_grp_weights) * len(grp_sizes)
self.weights_per_grp = torch.FloatTensor(per_grp_weights)
class CBLoss(ReWeight):
"""Class-balanced loss, https://arxiv.org/pdf/1901.05555.pdf"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(CBLoss, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
assert len(grp_sizes) == num_classes * num_attributes
grp_sizes = [x if x else np.inf for x in grp_sizes]
effective_num = 1. - np.power(self.hparams["beta"], grp_sizes)
effective_num = np.array(effective_num)
effective_num[effective_num == 1] = np.inf
per_grp_weights = (1. - self.hparams["beta"]) / effective_num
per_grp_weights = per_grp_weights / np.sum(per_grp_weights) * len(grp_sizes)
self.weights_per_grp = torch.FloatTensor(per_grp_weights)
class Focal(ERM):
"""Focal loss, https://arxiv.org/abs/1708.02002"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(Focal, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
@staticmethod
def focal_loss(input_values, gamma):
p = torch.exp(-input_values)
loss = (1 - p) ** gamma * input_values
return loss.mean()
def _compute_loss(self, i, x, y, a, step):
return self.focal_loss(self.loss(self.predict(x), y), self.hparams["gamma"])
class LDAM(ERM):
"""LDAM loss, https://arxiv.org/abs/1906.07413"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(LDAM, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
assert len(grp_sizes) == num_classes * num_attributes
# attribute-agnostic as modifying class-dependent margins
class_sizes = [np.sum(grp_sizes[i * num_attributes:(i+1) * num_attributes]) for i in range(num_classes)]
class_sizes = [x if x else np.inf for x in class_sizes]
m_list = 1. / np.sqrt(np.sqrt(np.array(class_sizes)))
m_list = m_list * (self.hparams["max_m"] / np.max(m_list))
self.m_list = torch.FloatTensor(m_list)
def _compute_loss(self, i, x, y, a, step):
x = self.predict(x)
index = torch.zeros_like(x, dtype=torch.uint8)
index.scatter_(1, y.data.view(-1, 1), 1)
index_float = index.type(torch.FloatTensor)
batch_m = torch.matmul(self.m_list[None, :].type_as(x), index_float.transpose(0, 1).type_as(x))
batch_m = batch_m.view((-1, 1))
x_m = x - batch_m
output = torch.where(index, x_m, x)
loss_value = F.cross_entropy(self.hparams["scale"] * output, y)
return loss_value
class BSoftmax(ERM):
"""Balanced softmax, https://arxiv.org/abs/2007.10740"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(BSoftmax, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
assert len(grp_sizes) == num_classes * num_attributes
# attribute-agnostic as modifying class-dependent margins
class_sizes = [np.sum(grp_sizes[i * num_attributes:(i+1) * num_attributes]) for i in range(num_classes)]
self.n_samples_per_cls = torch.FloatTensor(class_sizes)
def _compute_loss(self, i, x, y, a, step):
x = self.predict(x)
spc = self.n_samples_per_cls.type_as(x)
spc = spc.unsqueeze(0).expand(x.shape[0], -1)
x = x + spc.log()
loss_value = F.cross_entropy(input=x, target=y)
return loss_value
class CRT(ERM):
"""Classifier re-training with balanced sampling during the second earning stage"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(CRT, self).__init__(data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
# fix stage 1 trained featurizer
for name, param in self.featurizer.named_parameters():
param.requires_grad = False
# only optimize the classifier
if self.data_type in ["images", "tabular"]:
self.optimizer = get_optimizers[self.hparams["optimizer"]](
self.classifier,
self.hparams['lr'],
self.hparams['weight_decay']
)
self.lr_scheduler = None
elif self.data_type == "text":
self.network.zero_grad()
self.optimizer = get_optimizers[self.hparams["optimizer"]](
self.classifier,
self.hparams['lr'],
self.hparams['weight_decay']
)
self.lr_scheduler = get_scheduler(
"linear",
optimizer=self.optimizer,
num_warmup_steps=0,
num_training_steps=self.hparams["steps"]
)
else:
raise NotImplementedError(f"{self.data_type} not supported.")
class ReWeightCRT(ReWeight):
"""Classifier re-training with balanced re-weighting during the second earning stage"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(ReWeightCRT, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
# fix stage 1 trained featurizer
for name, param in self.featurizer.named_parameters():
param.requires_grad = False
# only optimize the classifier
if self.data_type in ["images", "tabular"]:
self.optimizer = get_optimizers[self.hparams["optimizer"]](
self.classifier,
self.hparams['lr'],
self.hparams['weight_decay']
)
self.lr_scheduler = None
elif self.data_type == "text":
self.network.zero_grad()
self.optimizer = get_optimizers[self.hparams["optimizer"]](
self.classifier,
self.hparams['lr'],
self.hparams['weight_decay']
)
self.lr_scheduler = get_scheduler(
"linear",
optimizer=self.optimizer,
num_warmup_steps=0,
num_training_steps=self.hparams["steps"]
)
else:
raise NotImplementedError(f"{self.data_type} not supported.")
class VanillaCRT(ERM):
"""Classifier re-training with normal (instance-balanced) sampling"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(VanillaCRT, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
# fix stage 1 trained featurizer
for name, param in self.featurizer.named_parameters():
param.requires_grad = False
# only optimize the classifier
if self.data_type in ["images", "tabular"]:
self.optimizer = get_optimizers[self.hparams["optimizer"]](
self.classifier,
self.hparams['lr'],
self.hparams['weight_decay']
)
self.lr_scheduler = None
elif self.data_type == "text":
self.network.zero_grad()
self.optimizer = get_optimizers[self.hparams["optimizer"]](
self.classifier,
self.hparams['lr'],
self.hparams['weight_decay']
)
self.lr_scheduler = get_scheduler(
"linear",
optimizer=self.optimizer,
num_warmup_steps=0,
num_training_steps=self.hparams["steps"]
)
else:
raise NotImplementedError(f"{self.data_type} not supported.")
class DFR(ERM):
"""
Classifier re-training with sub-sampled, group-balanced, held-out(validation) data and l1 regularization.
Note that when attribute is unavailable in validation data, group-balanced reduces to class-balanced.
https://openreview.net/pdf?id=Zb6c8A-Fghk
"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(DFR, self).__init__(data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
# fix stage 1 trained featurizer
for name, param in self.featurizer.named_parameters():
param.requires_grad = False
# only optimize the classifier
if self.data_type in ["images", "tabular"]:
self.optimizer = get_optimizers[self.hparams["optimizer"]](
self.classifier,
self.hparams['lr'],
0.
)
self.lr_scheduler = None
elif self.data_type == "text":
self.network.zero_grad()
self.optimizer = get_optimizers[self.hparams["optimizer"]](
self.classifier,
self.hparams['lr'],
0.
)
self.lr_scheduler = get_scheduler(
"linear",
optimizer=self.optimizer,
num_warmup_steps=0,
num_training_steps=self.hparams["steps"]
)
else:
raise NotImplementedError(f"{self.data_type} not supported.")
def _compute_loss(self, i, x, y, a, step):
return self.loss(self.predict(x), y).mean() + self.hparams['dfr_reg'] * torch.norm(self.classifier.weight, 1)
class IRM(ERM):
"""Invariant Risk Minimization"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(IRM, self).__init__(data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
self.register_buffer('update_count', torch.tensor([0]))
@staticmethod
def _irm_penalty(logits, y):
device = "cuda" if logits[0][0].is_cuda else "cpu"
scale = torch.tensor(1.).to(device).requires_grad_()
loss_1 = F.cross_entropy(logits[::2] * scale, y[::2])
loss_2 = F.cross_entropy(logits[1::2] * scale, y[1::2])
grad_1 = autograd.grad(loss_1, [scale], create_graph=True)[0]
grad_2 = autograd.grad(loss_2, [scale], create_graph=True)[0]
result = torch.sum(grad_1 * grad_2)
return result
def _compute_loss(self, i, x, y, a, step):
penalty_weight = self.hparams['irm_lambda'] \
if self.update_count >= self.hparams['irm_penalty_anneal_iters'] else 1.0
nll = 0.
penalty = 0.
logits = self.network(x)
for idx_a, idx_samples in self.return_attributes(a):
nll += F.cross_entropy(logits[idx_samples], y[idx_samples])
penalty += self._irm_penalty(logits[idx_samples], y[idx_samples])
nll /= len(a.unique())
penalty /= len(a.unique())
loss_value = nll + (penalty_weight * penalty)
self.update_count += 1
return loss_value
class Mixup(ERM):
"""Mixup of minibatch data"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(Mixup, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
def _compute_loss(self, i, x, y, a, step):
if self.data_type == "text":
feats = self.featurizer(x)
feats, yi, yj, lam = mixup_data(feats, y, self.hparams["mixup_alpha"], device="cuda")
predictions = self.classifier(feats)
else:
x, yi, yj, lam = mixup_data(x, y, self.hparams["mixup_alpha"], device="cuda")
predictions = self.predict(x)
loss_value = lam * F.cross_entropy(predictions, yi) + (1 - lam) * F.cross_entropy(predictions, yj)
return loss_value
class AbstractMMD(ERM):
"""
Perform ERM while matching the pair-wise domain feature distributions using MMD
"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams,
grp_sizes=None, attr_sizes=None, gaussian=False):
super(AbstractMMD, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
if gaussian:
self.kernel_type = "gaussian"
else:
self.kernel_type = "mean_cov"
@staticmethod
def my_cdist(x1, x2):
x1_norm = x1.pow(2).sum(dim=-1, keepdim=True)
x2_norm = x2.pow(2).sum(dim=-1, keepdim=True)
res = torch.addmm(x2_norm.transpose(-2, -1),
x1,
x2.transpose(-2, -1), alpha=-2).add_(x1_norm)
return res.clamp_min_(1e-30)
def gaussian_kernel(self, x, y, gamma=[0.001, 0.01, 0.1, 1, 10, 100, 1000]):
D = self.my_cdist(x, y)
K = torch.zeros_like(D)
for g in gamma:
K.add_(torch.exp(D.mul(-g)))
return K
def mmd(self, x, y):
if self.kernel_type == "gaussian":
Kxx = self.gaussian_kernel(x, x).mean()
Kyy = self.gaussian_kernel(y, y).mean()
Kxy = self.gaussian_kernel(x, y).mean()
return Kxx + Kyy - 2 * Kxy
else:
mean_x = x.mean(0, keepdim=True)
mean_y = y.mean(0, keepdim=True)
cent_x = x - mean_x
cent_y = y - mean_y
cova_x = (cent_x.t() @ cent_x) / (len(x) - 1)
cova_y = (cent_y.t() @ cent_y) / (len(y) - 1)
mean_diff = (mean_x - mean_y).pow(2).mean()
cova_diff = (cova_x - cova_y).pow(2).mean()
return mean_diff + cova_diff
def _compute_loss(self, i, x, y, a, step):
all_feats = self.featurizer(x)
outputs = self.classifier(all_feats)
objective = F.cross_entropy(outputs, y)
features = []
for _, idx_samples in self.return_attributes(a):
features.append(all_feats[idx_samples])
penalty = 0.
for i in range(len(features)):
for j in range(i + 1, len(features)):
penalty += self.mmd(features[i], features[j])
if len(features) > 1:
penalty /= (len(features) * (len(features) - 1) / 2)
loss_value = objective + (self.hparams['mmd_gamma'] * penalty)
return loss_value
class MMD(AbstractMMD):
"""MMD using Gaussian kernel"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(MMD, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes, gaussian=True)
class CORAL(AbstractMMD):
"""MMD using mean and covariance difference"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(CORAL, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes, gaussian=False)
class AbstractDANN(Algorithm):
"""Domain-Adversarial Neural Networks (abstract class)"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams,
grp_sizes=None, attr_sizes=None, conditional=False, class_balance=False):
super(AbstractDANN, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes)
self.register_buffer('update_count', torch.tensor([0]))
self.conditional = conditional
self.class_balance = class_balance
self.featurizer = networks.Featurizer(data_type, input_shape, self.hparams)
self.classifier = networks.Classifier(
self.featurizer.n_outputs,
num_classes,
self.hparams['nonlinear_classifier']
)
self.discriminator = networks.MLP(self.featurizer.n_outputs, num_attributes, self.hparams)
self.class_embeddings = nn.Embedding(num_classes, self.featurizer.n_outputs)
# optimizers
self.disc_opt = torch.optim.SGD(
(list(self.discriminator.parameters()) + list(self.class_embeddings.parameters())),
lr=self.hparams["lr_d"],
weight_decay=self.hparams['weight_decay_d'],
momentum=0.9)
self.gen_opt = torch.optim.SGD(
(list(self.featurizer.parameters()) + list(self.classifier.parameters())),
lr=self.hparams["lr_g"],
weight_decay=self.hparams['weight_decay_g'],
momentum=0.9)
def update(self, minibatch, step):
all_i, all_x, all_y, all_a = minibatch
self.update_count += 1
all_z = self.featurizer(all_x)
if self.conditional:
disc_input = all_z + self.class_embeddings(all_y)
else:
disc_input = all_z
disc_out = self.discriminator(disc_input)
if self.class_balance:
y_counts = F.one_hot(all_y).sum(dim=0)
weights = 1. / (y_counts[all_y] * y_counts.shape[0]).float()
disc_loss = F.cross_entropy(disc_out, all_a, reduction='none')
disc_loss = (weights * disc_loss).sum()
else:
disc_loss = F.cross_entropy(disc_out, all_a)
disc_softmax = F.softmax(disc_out, dim=1)
input_grad = autograd.grad(disc_softmax[:, all_a].sum(),
[disc_input], create_graph=True)[0]
grad_penalty = (input_grad ** 2).sum(dim=1).mean(dim=0)
disc_loss += self.hparams['grad_penalty'] * grad_penalty
d_steps_per_g = self.hparams['d_steps_per_g_step']
if self.update_count.item() % (1 + d_steps_per_g) < d_steps_per_g:
self.disc_opt.zero_grad()
disc_loss.backward()
self.disc_opt.step()
return {'disc_loss': disc_loss.item()}
else:
all_preds = self.classifier(all_z)
classifier_loss = F.cross_entropy(all_preds, all_y)
gen_loss = classifier_loss + (self.hparams['lambda'] * -disc_loss)
self.disc_opt.zero_grad()
self.gen_opt.zero_grad()
gen_loss.backward()
self.gen_opt.step()
return {'gen_loss': gen_loss.item()}
def return_feats(self, x):
return self.featurizer(x)
def predict(self, x):
return self.classifier(self.featurizer(x))
class DANN(AbstractDANN):
"""Unconditional DANN"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(DANN, self).__init__(data_type, input_shape, num_classes, num_attributes, num_examples, hparams,
grp_sizes, attr_sizes, conditional=False, class_balance=False)
class CDANN(AbstractDANN):
"""Conditional DANN"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(CDANN, self).__init__(data_type, input_shape, num_classes, num_attributes, num_examples, hparams,
grp_sizes, attr_sizes, conditional=True, class_balance=True)
class CVaRDRO(ERM):
"""
DRO with CVaR uncertainty set
https://arxiv.org/pdf/2010.05893.pdf
"""
def __init__(self, data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes=None, attr_sizes=None):
super(CVaRDRO, self).__init__(
data_type, input_shape, num_classes, num_attributes, num_examples, hparams, grp_sizes, attr_sizes) | self._joint_dro_loss_computer = joint_dro.RobustLoss(hparams['joint_dro_alpha'], 0, "cvar") | 1 | 2023-12-15 04:10:31+00:00 | 8k |
RomGai/BrainVis | process.py | [
{
"identifier": "CE",
"path": "loss.py",
"snippet": "class CE:\n def __init__(self, model):\n self.model = model\n self.ce = nn.CrossEntropyLoss()\n self.ce_pretrain = nn.CrossEntropyLoss(ignore_index=0)\n\n def computeft(self, batch):\n seqs, labels ,clip,clip_moreinf=... | import time
import torch
import numpy as np
import argparse
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
from tqdm import tqdm
from loss import CE, Align, Reconstruct,CM
from torch.optim.lr_scheduler import LambdaLR
from classification import fit_lr, get_rep_with_label,get_freqrep_with_label
from model.BrainVisModels import AlignNet,TimeFreqEncoder,FreqEncoder | 5,083 | metrics['f1'] = f1_score(y_true=label, y_pred=pred)
metrics['precision'] = precision_score(y_true=label, y_pred=pred)
metrics['recall'] = recall_score(y_true=label, y_pred=pred)
else:
metrics['f1'] = f1_score(y_true=label, y_pred=pred, average='macro')
metrics['micro_f1'] = f1_score(y_true=label, y_pred=pred, average='micro')
metrics['acc'] = accuracy_score(y_true=label, y_pred=pred)
metrics['test_loss'] = test_loss / (idx + 1)
return metrics
def compute_metrics(self, batch):
seqs, label, clip, clip_moreinf = batch
lastrep, rep,scores = self.model(seqs)
_, pred = torch.topk(scores, 1)
test_loss = self.test_cr(scores, label.view(-1).long())
pred = pred.view(-1).tolist()
return pred, label.tolist(), test_loss
def compute_metrics_freq(self, batch,model):
#if len(batch) == 2:
seqs, label,clip,clip_moreinf = batch
lastrep, rep,scores = model(seqs)
#else:
# seqs1, seqs2, label = batch
# lastrep, rep, scores = self.model((seqs1, seqs2))
_, pred = torch.topk(scores, 1)
#print(np.shape(scores))
test_loss = self.test_cr(scores, label.view(-1).long())
pred = pred.view(-1).tolist()
return pred, label.tolist(), test_loss
def _confusion_mat(self, label, pred):
mat = np.zeros((self.args.num_class, self.args.num_class))
for _label, _pred in zip(label, pred):
mat[_label, _pred] += 1
return mat
def print_process(self, *x):
if self.verbose:
print(*x)
def cont_pretrain(self):
start_epoch=300
state_dict = torch.load(self.save_path + '/pretrain_model_epoch300.pkl', map_location=self.device)
eval_acc=0.0 # It should be modified.
self.model.load_state_dict(state_dict)
print('cont_pretraining')
self.optimizer = torch.optim.AdamW(self.model.parameters(), lr=self.args.lr)
align = Align()
reconstruct = Reconstruct()
self.model.copy_weight()
for epoch in range(self.num_epoch_pretrain):
if(epoch<start_epoch):
continue
print('Epoch:' + str(epoch + 1))
self.model.train()
tqdm_dataloader = tqdm(self.train_loader)
loss_sum = 0
loss_mse = 0
loss_ce = 0
hits_sum = 0
NDCG_sum = 0
for idx, batch in enumerate(tqdm_dataloader):
batch = [x.to(self.device) for x in batch]
self.optimizer.zero_grad()
[rep_mask, rep_mask_prediction], [token_prediction_prob, tokens] = self.model.pretrain_forward(batch[0])
align_loss = align.compute(rep_mask, rep_mask_prediction)
loss_mse += align_loss.item()
reconstruct_loss, hits, NDCG = reconstruct.compute(token_prediction_prob, tokens)
loss_ce += reconstruct_loss.item()
hits_sum += hits.item()
NDCG_sum += NDCG
loss = self.alpha * align_loss + self.beta * reconstruct_loss
loss.backward()
self.optimizer.step()
self.model.momentum_update()
loss_sum += loss.item()
print('pretrain epoch{0}, loss{1}, mse{2}, ce{3}, hits{4}, ndcg{5}'.format(epoch + 1, loss_sum / (idx + 1),
loss_mse / (idx + 1),
loss_ce / (idx + 1), hits_sum,
NDCG_sum / (idx + 1)))
if (epoch + 1) % 10 == 0:
torch.save(self.model.state_dict(), self.save_path + '/pretrain_model_epoch'+str(epoch+1)+'.pkl')
if (epoch + 1) % 3 == 0:
self.model.eval()
train_rep, train_label = get_rep_with_label(self.model, self.train_linear_loader)
test_rep, test_label = get_rep_with_label(self.model, self.test_loader)
clf = fit_lr(train_rep, train_label)
acc = clf.score(test_rep, test_label)
print(acc)
if acc > eval_acc:
eval_acc = acc
torch.save(self.model.state_dict(), self.save_path + '/pretrain_model.pkl')
def finetune_CLIP(self):
eval_cosine = 0.0
freq_model_options = {key: int(value) if value.isdigit() else (float(value) if value[0].isdigit() else value) for
(key, value) in [x.split("=") for x in opt.model_params]}
freq_model = FreqEncoder(**freq_model_options)
self.timefreq_model=TimeFreqEncoder(self.model,freq_model,self.args)
self.timefreq_model = self.timefreq_model.to(torch.device(self.device))
freqtime_state_dict = torch.load(self.save_path + '/timefreqmodel.pkl', map_location=self.device)
self.timefreq_model.load_state_dict(freqtime_state_dict)
self.timefreq_model.to(torch.device("cpu"))
freq_size=freq_model.output_size
time_size=self.model.d
clip_size=int(77*768)
self.alignmodel=AlignNet(time_size,freq_size,clip_size,self.timefreq_model)
self.alignmodel=self.alignmodel.to(torch.device(self.device))
print('CLIP_finetune')
self.optimizer = torch.optim.AdamW(self.alignmodel.parameters(), lr=self.args.lr)
|
parser = argparse.ArgumentParser(description="Template")
parser.add_argument('-mt','--model_type', default='FreqEncoder', help='')
parser.add_argument('-mp','--model_params', default='', nargs='*', help='list of key=value pairs of model options')
parser.add_argument('--pretrained_net', default='lstm__subject0_epoch_900.pth', help="path to pre-trained net")
# Parse arguments
opt = parser.parse_args()
def l1_regularization(model, lambda_):
l1_norm = 0
for param in model.parameters():
l1_norm += param.abs().sum()
l1_penalty = lambda_ * l1_norm
return l1_penalty
class Trainer():
def __init__(self, args, time_model, train_loader, train_linear_loader, test_loader, verbose=False):
self.args = args
self.verbose = verbose
self.device = args.device
self.print_process(self.device)
self.model = time_model.to(torch.device(self.device))
self.train_loader = train_loader
#self.train_linear_loader = train_linear_loader
self.train_linear_loader = train_loader
self.test_loader = test_loader
self.lr_decay = args.lr_decay_rate
self.lr_decay_steps = args.lr_decay_steps
self.cr = CE(self.model)
self.alpha = args.alpha
self.beta = args.beta
self.test_cr = torch.nn.CrossEntropyLoss()
self.num_epoch = args.num_epoch
self.num_epoch_pretrain = args.num_epoch_pretrain
self.eval_per_steps = args.eval_per_steps
self.save_path = args.save_path
self.step = 0
self.best_metric = -1e9
self.metric = 'acc'
def pretrain(self):
print('pretraining')
self.optimizer = torch.optim.AdamW(self.model.parameters(), lr=self.args.lr)
eval_acc = 0
align = Align()
reconstruct = Reconstruct()
self.model.copy_weight()
for epoch in range(self.num_epoch_pretrain):
print('Epoch:' + str(epoch+1))
self.model.train()
tqdm_dataloader = tqdm(self.train_loader)
loss_sum = 0
loss_mse = 0
loss_ce = 0
hits_sum = 0
NDCG_sum = 0
for idx, batch in enumerate(tqdm_dataloader):
batch = [x.to(self.device) for x in batch]
self.optimizer.zero_grad() # 梯度清零
[rep_mask, rep_mask_prediction], [token_prediction_prob, tokens] = self.model.pretrain_forward(batch[0])
align_loss = align.compute(rep_mask, rep_mask_prediction)
loss_mse += align_loss.item()
reconstruct_loss, hits, NDCG = reconstruct.compute(token_prediction_prob, tokens)
loss_ce += reconstruct_loss.item()
hits_sum += hits.item()
NDCG_sum += NDCG
loss = self.alpha * align_loss + self.beta * reconstruct_loss
loss.backward()
self.optimizer.step()
self.model.momentum_update()
loss_sum += loss.item()
print('pretrain epoch{0}, loss{1}, mse{2}, ce{3}, hits{4}, ndcg{5}'.format(epoch + 1, loss_sum / (idx + 1),
loss_mse / (idx + 1),
loss_ce / (idx + 1), hits_sum,
NDCG_sum / (idx + 1)))
if (epoch + 1) % 20 == 0:
torch.save(self.model.state_dict(), self.save_path + '/pretrain_model_epoch'+str(epoch+1)+'.pkl')
if (epoch + 1) % 3 == 0:
self.model.eval()
train_rep, train_label = get_rep_with_label(self.model, self.train_linear_loader)
test_rep, test_label = get_rep_with_label(self.model, self.test_loader)
clf = fit_lr(train_rep, train_label)
acc = clf.score(test_rep, test_label)
print(acc)
if acc > eval_acc:
eval_acc = acc
torch.save(self.model.state_dict(), self.save_path + '/pretrain_model.pkl')
# It is worth noting that the highest pretraining accuracy does not mean the model is the
# best one for finetuning, so the one with larger training epoch should be used.
def finetune(self):
print('finetune')
self.model.linear_proba = True
#self.args.load_pretrained_model=False
if self.args.load_pretrained_model:
print('load pretrained model')
state_dict = torch.load(self.save_path + '/pretrain_model_epoch300.pkl', map_location=self.device)
try:
self.model.load_state_dict(state_dict)
except:
model_state_dict = self.model.state_dict()
for pretrain, random_intial in zip(state_dict, model_state_dict):
assert pretrain == random_intial
if pretrain in ['input_projection.weight', 'input_projection.bias', 'predict_head.weight',
'predict_head.bias', 'position.pe.weight']:
state_dict[pretrain] = model_state_dict[pretrain]
self.model.load_state_dict(state_dict)
self.model.eval()
train_rep, train_label = get_rep_with_label(self.model, self.train_linear_loader)
test_rep, test_label = get_rep_with_label(self.model, self.test_loader)
clf = fit_lr(train_rep, train_label)
acc = clf.score(test_rep, test_label)
pred_label = np.argmax(clf.predict_proba(test_rep), axis=1)
f1 = f1_score(test_label, pred_label, average='macro')
print(acc, f1)
self.model.linear_proba = False #If linear_proba = True, freeze pretrained model, train only classifier
self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.args.lr)
self.scheduler = LambdaLR(self.optimizer, lr_lambda=lambda step: self.lr_decay ** step, verbose=self.verbose)
for epoch in range(self.num_epoch):
loss_epoch, time_cost = self._train_one_epoch()
self.print_process(
'Finetune epoch:{0},loss:{1},training_time:{2}'.format(epoch + 1, loss_epoch, time_cost))
if (epoch + 1) % 5 == 0:
torch.save(self.model.state_dict(),
self.save_path + '/finetune_model_epoch' + str(epoch + 1) + '.pkl')
self.print_process(self.best_metric)
return self.best_metric
def _train_one_epoch(self):
t0 = time.perf_counter()
self.model.train()
tqdm_dataloader = tqdm(self.train_linear_loader) if self.verbose else self.train_linear_loader
loss_sum = 0
pos=0
for idx, batch in enumerate(tqdm_dataloader):
batch = [x.to(self.device) for x in batch]
self.optimizer.zero_grad()
l1=l1_regularization(self.model,0.000003)
loss = self.cr.computeft(batch)#+l1
loss_sum += loss.item()
loss.backward()
# torch.nn.utils.clip_grad_norm_(self.model.parameters(), 5)
self.optimizer.step()
pos=pos+1
self.step += 1
# if self.step % self.eval_per_steps == 0:
metric = self.eval_model()
self.print_process(metric)
if metric[self.metric] >= self.best_metric:
torch.save(self.model.state_dict(), self.save_path + '/finetune_model.pkl')
self.best_metric = metric[self.metric]
self.model.train()
return loss_sum / (idx + 1), time.perf_counter() - t0
def eval_model(self):
self.model.eval()
tqdm_data_loader = tqdm(self.test_loader) if self.verbose else self.test_loader
metrics = {'acc': 0, 'f1': 0}
pred = []
label = []
test_loss = 0
with torch.no_grad():
for idx, batch in enumerate(tqdm_data_loader):
batch = [x.to(self.device) for x in batch]
ret = self.compute_metrics(batch)
if len(ret) == 2:
pred_b, label_b = ret
pred += pred_b
label += label_b
else:
pred_b, label_b, test_loss_b = ret
pred += pred_b
label += label_b
test_loss += test_loss_b.cpu().item()
print("aaa")
print(len(label))
confusion_mat = self._confusion_mat(label, pred)
self.print_process(confusion_mat)
if self.args.num_class == 2:
metrics['f1'] = f1_score(y_true=label, y_pred=pred)
metrics['precision'] = precision_score(y_true=label, y_pred=pred)
metrics['recall'] = recall_score(y_true=label, y_pred=pred)
else:
metrics['f1'] = f1_score(y_true=label, y_pred=pred, average='macro')
metrics['micro_f1'] = f1_score(y_true=label, y_pred=pred, average='micro')
metrics['acc'] = accuracy_score(y_true=label, y_pred=pred)
metrics['test_loss'] = test_loss / (idx + 1)
return metrics
def compute_metrics(self, batch):
seqs, label, clip, clip_moreinf = batch
lastrep, rep,scores = self.model(seqs)
_, pred = torch.topk(scores, 1)
test_loss = self.test_cr(scores, label.view(-1).long())
pred = pred.view(-1).tolist()
return pred, label.tolist(), test_loss
def compute_metrics_freq(self, batch,model):
#if len(batch) == 2:
seqs, label,clip,clip_moreinf = batch
lastrep, rep,scores = model(seqs)
#else:
# seqs1, seqs2, label = batch
# lastrep, rep, scores = self.model((seqs1, seqs2))
_, pred = torch.topk(scores, 1)
#print(np.shape(scores))
test_loss = self.test_cr(scores, label.view(-1).long())
pred = pred.view(-1).tolist()
return pred, label.tolist(), test_loss
def _confusion_mat(self, label, pred):
mat = np.zeros((self.args.num_class, self.args.num_class))
for _label, _pred in zip(label, pred):
mat[_label, _pred] += 1
return mat
def print_process(self, *x):
if self.verbose:
print(*x)
def cont_pretrain(self):
start_epoch=300
state_dict = torch.load(self.save_path + '/pretrain_model_epoch300.pkl', map_location=self.device)
eval_acc=0.0 # It should be modified.
self.model.load_state_dict(state_dict)
print('cont_pretraining')
self.optimizer = torch.optim.AdamW(self.model.parameters(), lr=self.args.lr)
align = Align()
reconstruct = Reconstruct()
self.model.copy_weight()
for epoch in range(self.num_epoch_pretrain):
if(epoch<start_epoch):
continue
print('Epoch:' + str(epoch + 1))
self.model.train()
tqdm_dataloader = tqdm(self.train_loader)
loss_sum = 0
loss_mse = 0
loss_ce = 0
hits_sum = 0
NDCG_sum = 0
for idx, batch in enumerate(tqdm_dataloader):
batch = [x.to(self.device) for x in batch]
self.optimizer.zero_grad()
[rep_mask, rep_mask_prediction], [token_prediction_prob, tokens] = self.model.pretrain_forward(batch[0])
align_loss = align.compute(rep_mask, rep_mask_prediction)
loss_mse += align_loss.item()
reconstruct_loss, hits, NDCG = reconstruct.compute(token_prediction_prob, tokens)
loss_ce += reconstruct_loss.item()
hits_sum += hits.item()
NDCG_sum += NDCG
loss = self.alpha * align_loss + self.beta * reconstruct_loss
loss.backward()
self.optimizer.step()
self.model.momentum_update()
loss_sum += loss.item()
print('pretrain epoch{0}, loss{1}, mse{2}, ce{3}, hits{4}, ndcg{5}'.format(epoch + 1, loss_sum / (idx + 1),
loss_mse / (idx + 1),
loss_ce / (idx + 1), hits_sum,
NDCG_sum / (idx + 1)))
if (epoch + 1) % 10 == 0:
torch.save(self.model.state_dict(), self.save_path + '/pretrain_model_epoch'+str(epoch+1)+'.pkl')
if (epoch + 1) % 3 == 0:
self.model.eval()
train_rep, train_label = get_rep_with_label(self.model, self.train_linear_loader)
test_rep, test_label = get_rep_with_label(self.model, self.test_loader)
clf = fit_lr(train_rep, train_label)
acc = clf.score(test_rep, test_label)
print(acc)
if acc > eval_acc:
eval_acc = acc
torch.save(self.model.state_dict(), self.save_path + '/pretrain_model.pkl')
def finetune_CLIP(self):
eval_cosine = 0.0
freq_model_options = {key: int(value) if value.isdigit() else (float(value) if value[0].isdigit() else value) for
(key, value) in [x.split("=") for x in opt.model_params]}
freq_model = FreqEncoder(**freq_model_options)
self.timefreq_model=TimeFreqEncoder(self.model,freq_model,self.args)
self.timefreq_model = self.timefreq_model.to(torch.device(self.device))
freqtime_state_dict = torch.load(self.save_path + '/timefreqmodel.pkl', map_location=self.device)
self.timefreq_model.load_state_dict(freqtime_state_dict)
self.timefreq_model.to(torch.device("cpu"))
freq_size=freq_model.output_size
time_size=self.model.d
clip_size=int(77*768)
self.alignmodel=AlignNet(time_size,freq_size,clip_size,self.timefreq_model)
self.alignmodel=self.alignmodel.to(torch.device(self.device))
print('CLIP_finetune')
self.optimizer = torch.optim.AdamW(self.alignmodel.parameters(), lr=self.args.lr) | CLIPloss = CM() | 3 | 2023-12-16 12:52:14+00:00 | 8k |
Rajeshwaran2001/DRM-Media-Tool | main.py | [
{
"identifier": "KeyGeter",
"path": "key_getter.py",
"snippet": "class KeyGeter(QWidget):\n def __init__(self, debug_logger, info_logger):\n super().__init__()\n self.debug_logger = debug_logger\n self.info_logger = info_logger\n self.init_ui()\n\n def init_ui(self):\n ... | import sys
import platform
import webbrowser
import os
from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QMessageBox, QAction, QMenu
from PyQt5.QtGui import QIcon
from key_getter import KeyGeter
from decrypter import Decrypter
from logger import setup_logging
from version import __version__, CHANNEL | 4,894 |
info_logger, debug_logger = setup_logging()
current_dir = os.path.dirname(os.path.abspath(__file__))
icon = os.path.join(current_dir, 'assets', 'logo.ico')
git = os.path.join(current_dir, 'assets', 'github.png')
discord = os.path.join(current_dir, 'assets', 'discord.svg')
bug = os.path.join(current_dir, 'assets', 'bug.svg')
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowIcon(QIcon(icon))
self.init_ui()
def init_ui(self):
self.setWindowTitle(f"DRM & Media Tool {__version__} ({CHANNEL})")
self.setGeometry(100, 100, 650, 350)
# Create the tab widget
tab_widget = QTabWidget(self)
# Create the menu bar
menu_bar = self.menuBar()
# Create the Help menu
help_menu = menu_bar.addMenu('Help')
# Create "Tools Used" action
tools_used_action = QAction('Tools Used', self)
tools_used_action.triggered.connect(self.show_tools_used)
help_menu.addAction(tools_used_action)
# Create "About" action
about_action = QAction('About', self)
about_action.triggered.connect(self.show_about)
help_menu.addAction(about_action)
feature_bug_menu = QMenu('Feature/Bug', self)
request_feature_bug_action = QAction(
'Request a New Feature or Report Bug', self)
request_feature_bug_action.triggered.connect(
self.open_feature_bug_form)
feature_bug_menu.addAction(request_feature_bug_action)
menu_bar.addMenu(feature_bug_menu)
help_menu = menu_bar.addMenu('Discord')
open_discord_action = QAction('Open Discord', self)
open_discord_action.triggered.connect(self.open_discord)
help_menu.addAction(open_discord_action)
# Create tabs
|
info_logger, debug_logger = setup_logging()
current_dir = os.path.dirname(os.path.abspath(__file__))
icon = os.path.join(current_dir, 'assets', 'logo.ico')
git = os.path.join(current_dir, 'assets', 'github.png')
discord = os.path.join(current_dir, 'assets', 'discord.svg')
bug = os.path.join(current_dir, 'assets', 'bug.svg')
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowIcon(QIcon(icon))
self.init_ui()
def init_ui(self):
self.setWindowTitle(f"DRM & Media Tool {__version__} ({CHANNEL})")
self.setGeometry(100, 100, 650, 350)
# Create the tab widget
tab_widget = QTabWidget(self)
# Create the menu bar
menu_bar = self.menuBar()
# Create the Help menu
help_menu = menu_bar.addMenu('Help')
# Create "Tools Used" action
tools_used_action = QAction('Tools Used', self)
tools_used_action.triggered.connect(self.show_tools_used)
help_menu.addAction(tools_used_action)
# Create "About" action
about_action = QAction('About', self)
about_action.triggered.connect(self.show_about)
help_menu.addAction(about_action)
feature_bug_menu = QMenu('Feature/Bug', self)
request_feature_bug_action = QAction(
'Request a New Feature or Report Bug', self)
request_feature_bug_action.triggered.connect(
self.open_feature_bug_form)
feature_bug_menu.addAction(request_feature_bug_action)
menu_bar.addMenu(feature_bug_menu)
help_menu = menu_bar.addMenu('Discord')
open_discord_action = QAction('Open Discord', self)
open_discord_action.triggered.connect(self.open_discord)
help_menu.addAction(open_discord_action)
# Create tabs | hello_tab = KeyGeter(debug_logger, info_logger) | 0 | 2023-12-18 11:50:40+00:00 | 8k |
gmum/ViewingDirectionGaussianSplatting | 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,242 | #
# 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")
| #
# 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) | 0 | 2023-12-21 10:09:17+00:00 | 8k |
gauravsdeshmukh/ChemGCN | train_chemgcn.py | [
{
"identifier": "ChemGCN",
"path": "chem_gcn/model.py",
"snippet": "class ChemGCN(nn.Module):\n \"\"\"\n Create a graph neural network to predict water solubilities.\n \"\"\"\n\n def __init__(\n self,\n node_vec_len: int,\n node_fea_len: int,\n hidden_fea_len: int... | import numpy as np
import torch
from pathlib import Path
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
from chem_gcn.model import ChemGCN
from chem_gcn.utils import (
train_model,
test_model,
parity_plot,
loss_curve,
Standardizer,
)
from chem_gcn.graphs import GraphData, collate_graph_dataset | 5,653 | """Train a ChemGCN model."""
#### Fix seeds
np.random.seed(0)
torch.manual_seed(0)
use_GPU = torch.cuda.is_available()
#### Inputs
max_atoms = 200
node_vec_len = 60
train_size = 0.7
batch_size = 32
hidden_nodes = 60
n_conv_layers = 4
n_hidden_layers = 2
learning_rate = 0.01
n_epochs = 50
#### Start by creating dataset
main_path = Path(__file__).resolve().parent
data_path = main_path / "data" / "solubility_data.csv"
dataset = GraphData(
dataset_path=data_path, max_atoms=max_atoms, node_vec_len=node_vec_len
)
#### Split data into training and test sets
# Get train and test sizes
dataset_indices = np.arange(0, len(dataset), 1)
train_size = int(np.round(train_size * len(dataset)))
test_size = len(dataset) - train_size
# Randomly sample train and test indices
train_indices = np.random.choice(dataset_indices, size=train_size, replace=False)
test_indices = np.array(list(set(dataset_indices) - set(train_indices)))
# Create dataoaders
train_sampler = SubsetRandomSampler(train_indices)
test_sampler = SubsetRandomSampler(test_indices)
train_loader = DataLoader(
dataset,
batch_size=batch_size,
sampler=train_sampler,
collate_fn=collate_graph_dataset,
)
test_loader = DataLoader(
dataset,
batch_size=batch_size,
sampler=test_sampler,
collate_fn=collate_graph_dataset,
)
#### Initialize model, standardizer, optimizer, and loss function
# Model
model = ChemGCN(
node_vec_len=node_vec_len,
node_fea_len=hidden_nodes,
hidden_fea_len=hidden_nodes,
n_conv=n_conv_layers,
n_hidden=n_hidden_layers,
n_outputs=1,
p_dropout=0.1,
)
# Transfer to GPU if needed
if use_GPU:
model.cuda()
# Standardizer
outputs = [dataset[i][1] for i in range(len(dataset))]
standardizer = Standardizer(torch.Tensor(outputs))
# Optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Loss function
loss_fn = torch.nn.MSELoss()
#### Train the model
loss = []
mae = []
epoch = []
for i in range(n_epochs):
epoch_loss, epoch_mae = train_model(
i,
model,
train_loader,
optimizer,
loss_fn,
standardizer,
use_GPU,
max_atoms,
node_vec_len,
)
loss.append(epoch_loss)
mae.append(epoch_mae)
epoch.append(i)
#### Test the model
# Call test model function
| """Train a ChemGCN model."""
#### Fix seeds
np.random.seed(0)
torch.manual_seed(0)
use_GPU = torch.cuda.is_available()
#### Inputs
max_atoms = 200
node_vec_len = 60
train_size = 0.7
batch_size = 32
hidden_nodes = 60
n_conv_layers = 4
n_hidden_layers = 2
learning_rate = 0.01
n_epochs = 50
#### Start by creating dataset
main_path = Path(__file__).resolve().parent
data_path = main_path / "data" / "solubility_data.csv"
dataset = GraphData(
dataset_path=data_path, max_atoms=max_atoms, node_vec_len=node_vec_len
)
#### Split data into training and test sets
# Get train and test sizes
dataset_indices = np.arange(0, len(dataset), 1)
train_size = int(np.round(train_size * len(dataset)))
test_size = len(dataset) - train_size
# Randomly sample train and test indices
train_indices = np.random.choice(dataset_indices, size=train_size, replace=False)
test_indices = np.array(list(set(dataset_indices) - set(train_indices)))
# Create dataoaders
train_sampler = SubsetRandomSampler(train_indices)
test_sampler = SubsetRandomSampler(test_indices)
train_loader = DataLoader(
dataset,
batch_size=batch_size,
sampler=train_sampler,
collate_fn=collate_graph_dataset,
)
test_loader = DataLoader(
dataset,
batch_size=batch_size,
sampler=test_sampler,
collate_fn=collate_graph_dataset,
)
#### Initialize model, standardizer, optimizer, and loss function
# Model
model = ChemGCN(
node_vec_len=node_vec_len,
node_fea_len=hidden_nodes,
hidden_fea_len=hidden_nodes,
n_conv=n_conv_layers,
n_hidden=n_hidden_layers,
n_outputs=1,
p_dropout=0.1,
)
# Transfer to GPU if needed
if use_GPU:
model.cuda()
# Standardizer
outputs = [dataset[i][1] for i in range(len(dataset))]
standardizer = Standardizer(torch.Tensor(outputs))
# Optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Loss function
loss_fn = torch.nn.MSELoss()
#### Train the model
loss = []
mae = []
epoch = []
for i in range(n_epochs):
epoch_loss, epoch_mae = train_model(
i,
model,
train_loader,
optimizer,
loss_fn,
standardizer,
use_GPU,
max_atoms,
node_vec_len,
)
loss.append(epoch_loss)
mae.append(epoch_mae)
epoch.append(i)
#### Test the model
# Call test model function | test_loss, test_mae = test_model( | 2 | 2023-12-21 07:46:28+00:00 | 8k |
Ruiyuan-Zhang/CCS | multi_part_assembly/models/wx_transformer/wx_transformers.py | [
{
"identifier": "TransformerEncoderLayer",
"path": "multi_part_assembly/utils/wx_transformer_utilities/transformer_layer.py",
"snippet": "class TransformerEncoderLayer(nn.Module):\n \"\"\"Encoder layer block.\n In the original paper each operation (multi-head attention or FFN) is\n postprocesse... | import torch
import torch.nn as nn
import types
import math
import numpy as np
import math
import time
import time
from multi_part_assembly.utils.wx_transformer_utilities.transformer_layer import TransformerEncoderLayer, TransformerEncoderLayerVanilla
from multi_part_assembly.utils.wx_transformer_utilities.pos_enc import PositionEncoder
from multi_part_assembly.utils.wx_transformer_utilities.GroupLinearLayer import GroupLinearLayer | 5,903 | args.topk_ratio = 1.0
args.dropout = 0.2
args.encoder_normalize_before = True
args.encoder_ffn_embed_dim = 2048
args.use_nfm = 'false'
args.shared_memory_attention = False
args.self_attention = True
args.mem_slots = 4
args.use_topk = False
args.topk = 3
args.num_steps = 5
class SelectAttention(nn.Module):
"""docstring for SelectAttention"""
def __init__(self, d_read, d_write, d_k = 16, num_read = 5, num_write = 5, share_query = False, share_key = False):
super(SelectAttention, self).__init__()
if not share_key:
self.gll_write = GroupLinearLayer(d_write,d_k, num_write)
else:
self.gll_write = nn.Linear(d_write, d_k)
if not share_query:
self.gll_read = GroupLinearLayer(d_read,d_k, num_read)
else:
self.gll_read = nn.Linear(d_read, d_k)
self.temperature = math.sqrt(d_k)
def forward(self, q, k):
read = self.gll_read(q)
write = self.gll_write(k)
return torch.bmm(read, write.permute(0, 2, 1)) / self.temperature
class TransformerEncoder(nn.Module):
def __init__(self,
embed_dim,
ffn_dim,
num_layers = 6,
num_heads = 4,
dropout = 0.1,
functional = False,
shared_memory_attention = False,
shared_memory_percentage = 0.1,
share_parameters = False,
mem_slots = 4,
num_attention_schemas = 3,
num_gru_schemas = 3,
schema_specific = False,
use_topk = False,
topk = 3,
num_steps = 5,
null_attention = False,
regressive = False):
super().__init__()
if schema_specific and (num_gru_schemas != num_attention_schemas):
print('Cannot use schema specific as num_gru_schemas != num_attention_schemas, continuing without')
self.schema_specific = False
else:
self.schema_specific = schema_specific
args.mem_slots = mem_slots
args.encoder_embed_dim = embed_dim
args.encoder_ffn_embed_dim = ffn_dim
args.encoder_attention_heads = num_heads
args.dropout = dropout
args.shared_memory_attention = shared_memory_attention
args.num_steps = num_steps
args.null_attention = null_attention
args.regressive = regressive
self.num_layers = num_layers
self.shared_memory_attention = shared_memory_attention
self.shared_memory_percentage = shared_memory_percentage
print('transformer embed_dim', embed_dim)
self.functional = functional
print('functional? '+str(self.functional))
if not self.functional:
layer_lst = []
args.use_topk = use_topk
args.topk = topk
args.encoder_embed_dim = embed_dim
self.share_parameters = share_parameters
if share_parameters:
self.enc = TransformerEncoderLayerVanilla(args)
else:
layer_lst = []
for i in range(self.num_layers):
layer_lst.append(TransformerEncoderLayerVanilla(args))
self.layers = nn.ModuleList(layer_lst)
else:
#args.encoder_embed_dim = inp_dim
#print('init_layer initialize')
#self.init_layer = TransformerEncoderLayerVanilla(args=args, out_proj=h_dim)
print('NUM GRU SCHEMAS:' + str(num_gru_schemas))
print('NUM Attention SCHEMAS:' + str(num_attention_schemas))
print('SCHEMA SPECIFIC:' + str(self.schema_specific))
args.use_topk = use_topk
args.topk = topk
print('inp_att initialize')
self.num_gru_schemas = num_gru_schemas
self.num_att_schemas = num_attention_schemas
self.schema_stats = np.zeros(self.num_gru_schemas)
args.self_attention = True
self.inp_att = nn.ModuleList([TransformerEncoderLayerVanilla(args=args) for _ in range(num_attention_schemas)])
self.select_attention_inp_att = SelectAttention( args.encoder_embed_dim, args.encoder_embed_dim, num_read = 1, num_write = num_attention_schemas)
print('gru initialize')
hidden_dim = args.encoder_embed_dim
self.gru_pool = nn.ModuleList([nn.GRUCell(hidden_dim, hidden_dim) for _ in range(num_gru_schemas)])
#args.self_attention = True
#self.state_att = TransformerEncoderLayerVanilla(args=args)
self.select_attention = SelectAttention( hidden_dim + hidden_dim, hidden_dim, num_read = 1, num_write = num_gru_schemas)
| #from transformer import TransformerEncoder
args = types.SimpleNamespace()
args.use_module_communication = 'true'
args.encoder_embed_dim = 512
args.encoder_attention_heads = 8 #was 8
args.attention_dropout = 0.1
args.topk_ratio = 1.0
args.dropout = 0.2
args.encoder_normalize_before = True
args.encoder_ffn_embed_dim = 2048
args.use_nfm = 'false'
args.shared_memory_attention = False
args.self_attention = True
args.mem_slots = 4
args.use_topk = False
args.topk = 3
args.num_steps = 5
class SelectAttention(nn.Module):
"""docstring for SelectAttention"""
def __init__(self, d_read, d_write, d_k = 16, num_read = 5, num_write = 5, share_query = False, share_key = False):
super(SelectAttention, self).__init__()
if not share_key:
self.gll_write = GroupLinearLayer(d_write,d_k, num_write)
else:
self.gll_write = nn.Linear(d_write, d_k)
if not share_query:
self.gll_read = GroupLinearLayer(d_read,d_k, num_read)
else:
self.gll_read = nn.Linear(d_read, d_k)
self.temperature = math.sqrt(d_k)
def forward(self, q, k):
read = self.gll_read(q)
write = self.gll_write(k)
return torch.bmm(read, write.permute(0, 2, 1)) / self.temperature
class TransformerEncoder(nn.Module):
def __init__(self,
embed_dim,
ffn_dim,
num_layers = 6,
num_heads = 4,
dropout = 0.1,
functional = False,
shared_memory_attention = False,
shared_memory_percentage = 0.1,
share_parameters = False,
mem_slots = 4,
num_attention_schemas = 3,
num_gru_schemas = 3,
schema_specific = False,
use_topk = False,
topk = 3,
num_steps = 5,
null_attention = False,
regressive = False):
super().__init__()
if schema_specific and (num_gru_schemas != num_attention_schemas):
print('Cannot use schema specific as num_gru_schemas != num_attention_schemas, continuing without')
self.schema_specific = False
else:
self.schema_specific = schema_specific
args.mem_slots = mem_slots
args.encoder_embed_dim = embed_dim
args.encoder_ffn_embed_dim = ffn_dim
args.encoder_attention_heads = num_heads
args.dropout = dropout
args.shared_memory_attention = shared_memory_attention
args.num_steps = num_steps
args.null_attention = null_attention
args.regressive = regressive
self.num_layers = num_layers
self.shared_memory_attention = shared_memory_attention
self.shared_memory_percentage = shared_memory_percentage
print('transformer embed_dim', embed_dim)
self.functional = functional
print('functional? '+str(self.functional))
if not self.functional:
layer_lst = []
args.use_topk = use_topk
args.topk = topk
args.encoder_embed_dim = embed_dim
self.share_parameters = share_parameters
if share_parameters:
self.enc = TransformerEncoderLayerVanilla(args)
else:
layer_lst = []
for i in range(self.num_layers):
layer_lst.append(TransformerEncoderLayerVanilla(args))
self.layers = nn.ModuleList(layer_lst)
else:
#args.encoder_embed_dim = inp_dim
#print('init_layer initialize')
#self.init_layer = TransformerEncoderLayerVanilla(args=args, out_proj=h_dim)
print('NUM GRU SCHEMAS:' + str(num_gru_schemas))
print('NUM Attention SCHEMAS:' + str(num_attention_schemas))
print('SCHEMA SPECIFIC:' + str(self.schema_specific))
args.use_topk = use_topk
args.topk = topk
print('inp_att initialize')
self.num_gru_schemas = num_gru_schemas
self.num_att_schemas = num_attention_schemas
self.schema_stats = np.zeros(self.num_gru_schemas)
args.self_attention = True
self.inp_att = nn.ModuleList([TransformerEncoderLayerVanilla(args=args) for _ in range(num_attention_schemas)])
self.select_attention_inp_att = SelectAttention( args.encoder_embed_dim, args.encoder_embed_dim, num_read = 1, num_write = num_attention_schemas)
print('gru initialize')
hidden_dim = args.encoder_embed_dim
self.gru_pool = nn.ModuleList([nn.GRUCell(hidden_dim, hidden_dim) for _ in range(num_gru_schemas)])
#args.self_attention = True
#self.state_att = TransformerEncoderLayerVanilla(args=args)
self.select_attention = SelectAttention( hidden_dim + hidden_dim, hidden_dim, num_read = 1, num_write = num_gru_schemas)
| self.pe = PositionEncoder(args.encoder_embed_dim) | 2 | 2023-12-15 13:13:01+00:00 | 8k |
uc-vision/taichi-splatting | taichi_splatting/perspective/projection.py | [
{
"identifier": "restore_grad",
"path": "taichi_splatting/misc/autograd.py",
"snippet": "@contextmanager\ndef restore_grad(*tensors):\n try:\n grads = [tensor.grad if tensor.grad is not None else None\n for tensor in tensors]\n \n for tensor in tensors: \n if t... | from functools import cache
from typing import Tuple
from beartype import beartype
from taichi_splatting.misc.autograd import restore_grad
from .params import CameraParams
from taichi_splatting.taichi_lib.generic import make_library
from taichi_splatting.taichi_lib.conversions import torch_taichi
import taichi as ti
import torch | 5,476 |
@cache
def project_to_image_function(torch_dtype=torch.float32,
blur_cov:float = 0.3):
dtype = torch_taichi[torch_dtype]
lib = make_library(dtype)
Gaussian3D, Gaussian2D = lib.Gaussian3D, lib.Gaussian2D
@ti.kernel
def project_perspective_kernel(
gaussians: ti.types.ndarray(Gaussian3D.vec, ndim=1), # (N, 3 + feature_vec.n1) # input
T_image_camera: ti.types.ndarray(ndim=2), # (3, 3) camera projection
T_camera_world: ti.types.ndarray(ndim=2), # (4, 4)
points: ti.types.ndarray(Gaussian2D.vec, ndim=1), # (N, 6)
depth_var: ti.types.ndarray(lib.vec3, ndim=1), # (N, 3)
):
for idx in range(gaussians.shape[0]):
position, scale, rotation, alpha = Gaussian3D.unpack_activate(gaussians[idx])
camera_image = lib.mat3_from_ndarray(T_image_camera)
camera_world = lib.mat4_from_ndarray(T_camera_world)
uv, point_in_camera = lib.project_perspective_camera_image(
position, camera_world, camera_image)
cov_in_camera = lib.gaussian_covariance_in_camera(
camera_world, rotation, scale)
uv_cov = lib.upper(lib.project_perspective_gaussian(
camera_image, point_in_camera, cov_in_camera))
# add small fudge factor blur to avoid numerical issues
uv_cov += lib.vec3([blur_cov, 0, blur_cov])
uv_conic = lib.inverse_cov(uv_cov)
depth_var[idx] = lib.vec3(point_in_camera.z, cov_in_camera[2, 2], point_in_camera.z ** 2)
points[idx] = Gaussian2D.to_vec(
uv=uv.xy,
uv_conic=uv_conic,
alpha=alpha,
)
class _module_function(torch.autograd.Function):
@staticmethod
def forward(ctx, gaussians, T_image_camera, T_camera_world):
dtype, device = T_image_camera.dtype, T_image_camera.device
points = torch.empty((gaussians.shape[0], Gaussian2D.vec.n), dtype=dtype, device=device)
depth_vars = torch.empty((gaussians.shape[0], 3), dtype=dtype, device=device)
project_perspective_kernel(gaussians,
T_image_camera, T_camera_world,
points, depth_vars)
ctx.save_for_backward(gaussians, T_image_camera, T_camera_world, points, depth_vars)
return points, depth_vars
@staticmethod
def backward(ctx, dpoints, ddepth_vars):
gaussians, T_image_camera, T_camera_world, points, depth_vars = ctx.saved_tensors
|
@cache
def project_to_image_function(torch_dtype=torch.float32,
blur_cov:float = 0.3):
dtype = torch_taichi[torch_dtype]
lib = make_library(dtype)
Gaussian3D, Gaussian2D = lib.Gaussian3D, lib.Gaussian2D
@ti.kernel
def project_perspective_kernel(
gaussians: ti.types.ndarray(Gaussian3D.vec, ndim=1), # (N, 3 + feature_vec.n1) # input
T_image_camera: ti.types.ndarray(ndim=2), # (3, 3) camera projection
T_camera_world: ti.types.ndarray(ndim=2), # (4, 4)
points: ti.types.ndarray(Gaussian2D.vec, ndim=1), # (N, 6)
depth_var: ti.types.ndarray(lib.vec3, ndim=1), # (N, 3)
):
for idx in range(gaussians.shape[0]):
position, scale, rotation, alpha = Gaussian3D.unpack_activate(gaussians[idx])
camera_image = lib.mat3_from_ndarray(T_image_camera)
camera_world = lib.mat4_from_ndarray(T_camera_world)
uv, point_in_camera = lib.project_perspective_camera_image(
position, camera_world, camera_image)
cov_in_camera = lib.gaussian_covariance_in_camera(
camera_world, rotation, scale)
uv_cov = lib.upper(lib.project_perspective_gaussian(
camera_image, point_in_camera, cov_in_camera))
# add small fudge factor blur to avoid numerical issues
uv_cov += lib.vec3([blur_cov, 0, blur_cov])
uv_conic = lib.inverse_cov(uv_cov)
depth_var[idx] = lib.vec3(point_in_camera.z, cov_in_camera[2, 2], point_in_camera.z ** 2)
points[idx] = Gaussian2D.to_vec(
uv=uv.xy,
uv_conic=uv_conic,
alpha=alpha,
)
class _module_function(torch.autograd.Function):
@staticmethod
def forward(ctx, gaussians, T_image_camera, T_camera_world):
dtype, device = T_image_camera.dtype, T_image_camera.device
points = torch.empty((gaussians.shape[0], Gaussian2D.vec.n), dtype=dtype, device=device)
depth_vars = torch.empty((gaussians.shape[0], 3), dtype=dtype, device=device)
project_perspective_kernel(gaussians,
T_image_camera, T_camera_world,
points, depth_vars)
ctx.save_for_backward(gaussians, T_image_camera, T_camera_world, points, depth_vars)
return points, depth_vars
@staticmethod
def backward(ctx, dpoints, ddepth_vars):
gaussians, T_image_camera, T_camera_world, points, depth_vars = ctx.saved_tensors
| with restore_grad(gaussians, T_image_camera, T_camera_world, points, depth_vars): | 0 | 2023-12-17 15:26:52+00:00 | 8k |
camenduru/FreeInit-hf | animatediff/utils/util.py | [
{
"identifier": "convert_ldm_unet_checkpoint",
"path": "animatediff/utils/convert_from_ckpt.py",
"snippet": "def convert_ldm_unet_checkpoint(checkpoint, config, path=None, extract_ema=False, controlnet=False):\n \"\"\"\n Takes a state dict and a config, and returns a converted checkpoint.\n \"\... | import os
import imageio
import numpy as np
import torch
import torchvision
import torch.distributed as dist
from typing import Union
from safetensors import safe_open
from tqdm import tqdm
from einops import rearrange
from animatediff.utils.convert_from_ckpt import convert_ldm_unet_checkpoint, convert_ldm_clip_checkpoint, convert_ldm_vae_checkpoint
from animatediff.utils.convert_lora_safetensor_to_diffusers import convert_lora, convert_motion_lora_ckpt_to_diffusers | 6,905 |
def zero_rank_print(s):
if (not dist.is_initialized()) and (dist.is_initialized() and dist.get_rank() == 0): print("### " + s)
def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=6, fps=8):
videos = rearrange(videos, "b c t h w -> t b c h w")
outputs = []
for x in videos:
x = torchvision.utils.make_grid(x, nrow=n_rows)
x = x.transpose(0, 1).transpose(1, 2).squeeze(-1)
if rescale:
x = (x + 1.0) / 2.0 # -1,1 -> 0,1
x = (x * 255).numpy().astype(np.uint8)
outputs.append(x)
os.makedirs(os.path.dirname(path), exist_ok=True)
imageio.mimsave(path, outputs, fps=fps)
# DDIM Inversion
@torch.no_grad()
def init_prompt(prompt, pipeline):
uncond_input = pipeline.tokenizer(
[""], padding="max_length", max_length=pipeline.tokenizer.model_max_length,
return_tensors="pt"
)
uncond_embeddings = pipeline.text_encoder(uncond_input.input_ids.to(pipeline.device))[0]
text_input = pipeline.tokenizer(
[prompt],
padding="max_length",
max_length=pipeline.tokenizer.model_max_length,
truncation=True,
return_tensors="pt",
)
text_embeddings = pipeline.text_encoder(text_input.input_ids.to(pipeline.device))[0]
context = torch.cat([uncond_embeddings, text_embeddings])
return context
def next_step(model_output: Union[torch.FloatTensor, np.ndarray], timestep: int,
sample: Union[torch.FloatTensor, np.ndarray], ddim_scheduler):
timestep, next_timestep = min(
timestep - ddim_scheduler.config.num_train_timesteps // ddim_scheduler.num_inference_steps, 999), timestep
alpha_prod_t = ddim_scheduler.alphas_cumprod[timestep] if timestep >= 0 else ddim_scheduler.final_alpha_cumprod
alpha_prod_t_next = ddim_scheduler.alphas_cumprod[next_timestep]
beta_prod_t = 1 - alpha_prod_t
next_original_sample = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
next_sample_direction = (1 - alpha_prod_t_next) ** 0.5 * model_output
next_sample = alpha_prod_t_next ** 0.5 * next_original_sample + next_sample_direction
return next_sample
def get_noise_pred_single(latents, t, context, unet):
noise_pred = unet(latents, t, encoder_hidden_states=context)["sample"]
return noise_pred
@torch.no_grad()
def ddim_loop(pipeline, ddim_scheduler, latent, num_inv_steps, prompt):
context = init_prompt(prompt, pipeline)
uncond_embeddings, cond_embeddings = context.chunk(2)
all_latent = [latent]
latent = latent.clone().detach()
for i in tqdm(range(num_inv_steps)):
t = ddim_scheduler.timesteps[len(ddim_scheduler.timesteps) - i - 1]
noise_pred = get_noise_pred_single(latent, t, cond_embeddings, pipeline.unet)
latent = next_step(noise_pred, t, latent, ddim_scheduler)
all_latent.append(latent)
return all_latent
@torch.no_grad()
def ddim_inversion(pipeline, ddim_scheduler, video_latent, num_inv_steps, prompt=""):
ddim_latents = ddim_loop(pipeline, ddim_scheduler, video_latent, num_inv_steps, prompt)
return ddim_latents
def load_weights(
animation_pipeline,
# motion module
motion_module_path = "",
motion_module_lora_configs = [],
# image layers
dreambooth_model_path = "",
lora_model_path = "",
lora_alpha = 0.8,
):
# 1.1 motion module
unet_state_dict = {}
if motion_module_path != "":
print(f"load motion module from {motion_module_path}")
motion_module_state_dict = torch.load(motion_module_path, map_location="cpu")
motion_module_state_dict = motion_module_state_dict["state_dict"] if "state_dict" in motion_module_state_dict else motion_module_state_dict
unet_state_dict.update({name: param for name, param in motion_module_state_dict.items() if "motion_modules." in name})
missing, unexpected = animation_pipeline.unet.load_state_dict(unet_state_dict, strict=False)
assert len(unexpected) == 0
del unet_state_dict
if dreambooth_model_path != "":
print(f"load dreambooth model from {dreambooth_model_path}")
if dreambooth_model_path.endswith(".safetensors"):
dreambooth_state_dict = {}
with safe_open(dreambooth_model_path, framework="pt", device="cpu") as f:
for key in f.keys():
dreambooth_state_dict[key] = f.get_tensor(key)
elif dreambooth_model_path.endswith(".ckpt"):
dreambooth_state_dict = torch.load(dreambooth_model_path, map_location="cpu")
# 1. vae
converted_vae_checkpoint = convert_ldm_vae_checkpoint(dreambooth_state_dict, animation_pipeline.vae.config)
animation_pipeline.vae.load_state_dict(converted_vae_checkpoint)
# 2. unet
|
def zero_rank_print(s):
if (not dist.is_initialized()) and (dist.is_initialized() and dist.get_rank() == 0): print("### " + s)
def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=6, fps=8):
videos = rearrange(videos, "b c t h w -> t b c h w")
outputs = []
for x in videos:
x = torchvision.utils.make_grid(x, nrow=n_rows)
x = x.transpose(0, 1).transpose(1, 2).squeeze(-1)
if rescale:
x = (x + 1.0) / 2.0 # -1,1 -> 0,1
x = (x * 255).numpy().astype(np.uint8)
outputs.append(x)
os.makedirs(os.path.dirname(path), exist_ok=True)
imageio.mimsave(path, outputs, fps=fps)
# DDIM Inversion
@torch.no_grad()
def init_prompt(prompt, pipeline):
uncond_input = pipeline.tokenizer(
[""], padding="max_length", max_length=pipeline.tokenizer.model_max_length,
return_tensors="pt"
)
uncond_embeddings = pipeline.text_encoder(uncond_input.input_ids.to(pipeline.device))[0]
text_input = pipeline.tokenizer(
[prompt],
padding="max_length",
max_length=pipeline.tokenizer.model_max_length,
truncation=True,
return_tensors="pt",
)
text_embeddings = pipeline.text_encoder(text_input.input_ids.to(pipeline.device))[0]
context = torch.cat([uncond_embeddings, text_embeddings])
return context
def next_step(model_output: Union[torch.FloatTensor, np.ndarray], timestep: int,
sample: Union[torch.FloatTensor, np.ndarray], ddim_scheduler):
timestep, next_timestep = min(
timestep - ddim_scheduler.config.num_train_timesteps // ddim_scheduler.num_inference_steps, 999), timestep
alpha_prod_t = ddim_scheduler.alphas_cumprod[timestep] if timestep >= 0 else ddim_scheduler.final_alpha_cumprod
alpha_prod_t_next = ddim_scheduler.alphas_cumprod[next_timestep]
beta_prod_t = 1 - alpha_prod_t
next_original_sample = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
next_sample_direction = (1 - alpha_prod_t_next) ** 0.5 * model_output
next_sample = alpha_prod_t_next ** 0.5 * next_original_sample + next_sample_direction
return next_sample
def get_noise_pred_single(latents, t, context, unet):
noise_pred = unet(latents, t, encoder_hidden_states=context)["sample"]
return noise_pred
@torch.no_grad()
def ddim_loop(pipeline, ddim_scheduler, latent, num_inv_steps, prompt):
context = init_prompt(prompt, pipeline)
uncond_embeddings, cond_embeddings = context.chunk(2)
all_latent = [latent]
latent = latent.clone().detach()
for i in tqdm(range(num_inv_steps)):
t = ddim_scheduler.timesteps[len(ddim_scheduler.timesteps) - i - 1]
noise_pred = get_noise_pred_single(latent, t, cond_embeddings, pipeline.unet)
latent = next_step(noise_pred, t, latent, ddim_scheduler)
all_latent.append(latent)
return all_latent
@torch.no_grad()
def ddim_inversion(pipeline, ddim_scheduler, video_latent, num_inv_steps, prompt=""):
ddim_latents = ddim_loop(pipeline, ddim_scheduler, video_latent, num_inv_steps, prompt)
return ddim_latents
def load_weights(
animation_pipeline,
# motion module
motion_module_path = "",
motion_module_lora_configs = [],
# image layers
dreambooth_model_path = "",
lora_model_path = "",
lora_alpha = 0.8,
):
# 1.1 motion module
unet_state_dict = {}
if motion_module_path != "":
print(f"load motion module from {motion_module_path}")
motion_module_state_dict = torch.load(motion_module_path, map_location="cpu")
motion_module_state_dict = motion_module_state_dict["state_dict"] if "state_dict" in motion_module_state_dict else motion_module_state_dict
unet_state_dict.update({name: param for name, param in motion_module_state_dict.items() if "motion_modules." in name})
missing, unexpected = animation_pipeline.unet.load_state_dict(unet_state_dict, strict=False)
assert len(unexpected) == 0
del unet_state_dict
if dreambooth_model_path != "":
print(f"load dreambooth model from {dreambooth_model_path}")
if dreambooth_model_path.endswith(".safetensors"):
dreambooth_state_dict = {}
with safe_open(dreambooth_model_path, framework="pt", device="cpu") as f:
for key in f.keys():
dreambooth_state_dict[key] = f.get_tensor(key)
elif dreambooth_model_path.endswith(".ckpt"):
dreambooth_state_dict = torch.load(dreambooth_model_path, map_location="cpu")
# 1. vae
converted_vae_checkpoint = convert_ldm_vae_checkpoint(dreambooth_state_dict, animation_pipeline.vae.config)
animation_pipeline.vae.load_state_dict(converted_vae_checkpoint)
# 2. unet | converted_unet_checkpoint = convert_ldm_unet_checkpoint(dreambooth_state_dict, animation_pipeline.unet.config) | 0 | 2023-12-19 21:06:32+00:00 | 8k |
exislow/tidal-dl-ng | tidal_dl_ng/download.py | [
{
"identifier": "Settings",
"path": "tidal_dl_ng/config.py",
"snippet": "class Settings(BaseConfig, metaclass=SingletonMeta):\n cls_model = ModelSettings\n data = None\n\n def __init__(self):\n self.file_path = path_file_settings()\n self.read(self.file_path)"
},
{
"identi... | import base64
import json
import os
import random
import shutil
import tempfile
import time
import ffmpeg
import m3u8
import requests
from collections.abc import Callable
from logging import Logger
from uuid import uuid4
from mpegdash.parser import MPEGDASHParser
from requests.exceptions import HTTPError
from rich.progress import Progress, TaskID
from tidalapi import Album, Mix, Playlist, Session, Track, UserPlaylist, Video
from tidal_dl_ng.config import Settings
from tidal_dl_ng.constants import REQUESTS_TIMEOUT_SEC, CoverDimensions, MediaType, SkipExisting, StreamManifestMimeType
from tidal_dl_ng.helper.decryption import decrypt_file, decrypt_security_token
from tidal_dl_ng.helper.exceptions import MediaMissing, MediaUnknown, UnknownManifestFormat
from tidal_dl_ng.helper.path import check_file_exists, format_path_media, path_file_sanitize
from tidal_dl_ng.helper.tidal import name_builder_item
from tidal_dl_ng.helper.wrapper import WrapperLogger
from tidal_dl_ng.metadata import Metadata
from tidal_dl_ng.model.gui_data import ProgressBars
from tidal_dl_ng.model.tidal import StreamManifest | 5,153 | # Advance progress bar.
progress.advance(p_task)
# To send the progress to the GUI, we need to emit the percentage.
if not progress_stdout:
progress_gui.item.emit(progress.tasks[p_task].percentage)
except HTTPError as e:
# TODO: Handle Exception...
fn_logger(e)
# Check if file is encrypted.
needs_decryption = self.is_encrypted(stream_manifest.encryption_type)
if needs_decryption:
key, nonce = decrypt_security_token(stream_manifest.encryption_key)
tmp_path_file_decrypted = path_file + "_decrypted"
decrypt_file(path_file, tmp_path_file_decrypted, key, nonce)
else:
tmp_path_file_decrypted = path_file
# Write metadata to file.
if not isinstance(media, Video):
self.metadata_write(media, tmp_path_file_decrypted)
return tmp_path_file_decrypted
def instantiate_media(
self,
session: Session,
media_type: type[MediaType.TRACK, MediaType.VIDEO, MediaType.ALBUM, MediaType.PLAYLIST, MediaType.MIX],
id_media: str,
) -> Track | Video:
if media_type == MediaType.TRACK:
media = Track(session, id_media)
elif media_type == MediaType.VIDEO:
media = Video(session, id_media)
elif media_type == MediaType.ALBUM:
media = Album(self.session, id_media)
elif media_type == MediaType.PLAYLIST:
media = Playlist(self.session, id_media)
elif media_type == MediaType.MIX:
media = Mix(self.session, id_media)
else:
raise MediaUnknown
return media
def item(
self,
path_base: str,
file_template: str,
fn_logger: Callable,
media: Track | Video = None,
media_id: str = None,
media_type: MediaType = None,
video_download: bool = True,
progress_gui: ProgressBars = None,
progress: Progress = None,
) -> (bool, str):
# If no media instance is provided, we need to create the media instance.
if media_id and media_type:
media = self.instantiate_media(self.session, media_type, media_id)
elif not media:
raise MediaMissing
# If video download is not allowed end here
if not video_download:
fn_logger.info(
f"Video downloads are deactivated (see settings). Skipping video: {name_builder_item(media)}"
)
return False, ""
# Create file name and path
file_name_relative = format_path_media(file_template, media)
path_file = os.path.abspath(os.path.normpath(os.path.join(path_base, file_name_relative)))
# Populate StreamManifest for further download.
if isinstance(media, Track):
stream = media.stream()
manifest: str = stream.manifest
mime_type: str = stream.manifest_mime_type
else:
manifest: str = media.get_url()
mime_type: str = StreamManifestMimeType.VIDEO.value
stream_manifest = self.stream_manifest_parse(manifest, mime_type)
# Sanitize final path_file to fit into OS boundaries.
path_file = path_file_sanitize(path_file + stream_manifest.file_extension, adapt=True)
# Compute if and how downloads need to be skipped.
if self.skip_existing.value:
extension_ignore = self.skip_existing == SkipExisting.ExtensionIgnore
# TODO: Check if extension is already in `path_file` or not.
download_skip = check_file_exists(path_file, extension_ignore=extension_ignore)
else:
download_skip = False
if not download_skip:
# Create a temp directory and file.
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp_path_dir:
tmp_path_file = os.path.join(tmp_path_dir, str(uuid4()) + stream_manifest.file_extension)
# Download media.
tmp_path_file = self._download(fn_logger, media, progress, progress_gui, stream_manifest, tmp_path_file)
if isinstance(media, Video) and self.settings.data.video_convert_mp4:
# TODO: Make optional.
# Convert `*.ts` file to `*.mp4` using ffmpeg
tmp_path_file = self._video_convert(tmp_path_file)
path_file = os.path.splitext(path_file)[0] + ".mp4"
# Move final file to the configured destination directory.
os.makedirs(os.path.dirname(path_file), exist_ok=True)
shutil.move(tmp_path_file, path_file)
else:
fn_logger.debug(f"Download skipped, since file exists: '{path_file}'")
return not download_skip, path_file
|
# TODO: Set appropriate client string and use it for video download.
# https://github.com/globocom/m3u8#using-different-http-clients
class RequestsClient:
def download(
self, uri: str, timeout: int = REQUESTS_TIMEOUT_SEC, headers: dict | None = None, verify_ssl: bool = True
):
if not headers:
headers = {}
o = requests.get(uri, timeout=timeout, headers=headers)
return o.text, o.url
class Download:
settings: Settings = None
session: Session = None
skip_existing: SkipExisting = False
def __init__(self, session: Session, skip_existing: SkipExisting = SkipExisting.Disabled):
self.settings = Settings()
self.session = session
self.skip_existing = skip_existing
def _download(
self,
fn_logger: Callable,
media: Track | Video,
progress: Progress,
progress_gui: ProgressBars,
stream_manifest: StreamManifest,
path_file: str,
):
media_name: str = name_builder_item(media)
# Set the correct progress output channel.
if progress_gui is None:
progress_stdout: bool = True
else:
progress_stdout: bool = False
# Send signal to GUI with media name
progress_gui.item_name.emit(media_name)
try:
# Compute total iterations for progress
urls_count: int = len(stream_manifest.urls)
if urls_count > 1:
progress_total: int = urls_count
block_size: int | None = None
else:
# Compute progress iterations based on the file size.
r = requests.get(stream_manifest.urls[0], stream=True, timeout=REQUESTS_TIMEOUT_SEC)
r.raise_for_status()
# Get file size and compute progress steps
total_size_in_bytes: int = int(r.headers.get("content-length", 0))
block_size: int | None = 4096
progress_total: float = total_size_in_bytes / block_size
# Create progress Task
p_task: TaskID = progress.add_task(
f"[blue]Item '{media_name[:30]}'",
total=progress_total,
visible=progress_stdout,
)
# Write content to file until progress is finished.
while not progress.tasks[p_task].finished:
with open(path_file, "wb") as f:
for url in stream_manifest.urls:
# Create the request object with stream=True, so the content won't be loaded into memory at once.
r = requests.get(url, stream=True, timeout=REQUESTS_TIMEOUT_SEC)
r.raise_for_status()
# Write the content to disk. If `chunk_size` is set to `None` the whole file will be written at once.
for data in r.iter_content(chunk_size=block_size):
f.write(data)
# Advance progress bar.
progress.advance(p_task)
# To send the progress to the GUI, we need to emit the percentage.
if not progress_stdout:
progress_gui.item.emit(progress.tasks[p_task].percentage)
except HTTPError as e:
# TODO: Handle Exception...
fn_logger(e)
# Check if file is encrypted.
needs_decryption = self.is_encrypted(stream_manifest.encryption_type)
if needs_decryption:
key, nonce = decrypt_security_token(stream_manifest.encryption_key)
tmp_path_file_decrypted = path_file + "_decrypted"
decrypt_file(path_file, tmp_path_file_decrypted, key, nonce)
else:
tmp_path_file_decrypted = path_file
# Write metadata to file.
if not isinstance(media, Video):
self.metadata_write(media, tmp_path_file_decrypted)
return tmp_path_file_decrypted
def instantiate_media(
self,
session: Session,
media_type: type[MediaType.TRACK, MediaType.VIDEO, MediaType.ALBUM, MediaType.PLAYLIST, MediaType.MIX],
id_media: str,
) -> Track | Video:
if media_type == MediaType.TRACK:
media = Track(session, id_media)
elif media_type == MediaType.VIDEO:
media = Video(session, id_media)
elif media_type == MediaType.ALBUM:
media = Album(self.session, id_media)
elif media_type == MediaType.PLAYLIST:
media = Playlist(self.session, id_media)
elif media_type == MediaType.MIX:
media = Mix(self.session, id_media)
else:
raise MediaUnknown
return media
def item(
self,
path_base: str,
file_template: str,
fn_logger: Callable,
media: Track | Video = None,
media_id: str = None,
media_type: MediaType = None,
video_download: bool = True,
progress_gui: ProgressBars = None,
progress: Progress = None,
) -> (bool, str):
# If no media instance is provided, we need to create the media instance.
if media_id and media_type:
media = self.instantiate_media(self.session, media_type, media_id)
elif not media:
raise MediaMissing
# If video download is not allowed end here
if not video_download:
fn_logger.info(
f"Video downloads are deactivated (see settings). Skipping video: {name_builder_item(media)}"
)
return False, ""
# Create file name and path
file_name_relative = format_path_media(file_template, media)
path_file = os.path.abspath(os.path.normpath(os.path.join(path_base, file_name_relative)))
# Populate StreamManifest for further download.
if isinstance(media, Track):
stream = media.stream()
manifest: str = stream.manifest
mime_type: str = stream.manifest_mime_type
else:
manifest: str = media.get_url()
mime_type: str = StreamManifestMimeType.VIDEO.value
stream_manifest = self.stream_manifest_parse(manifest, mime_type)
# Sanitize final path_file to fit into OS boundaries.
path_file = path_file_sanitize(path_file + stream_manifest.file_extension, adapt=True)
# Compute if and how downloads need to be skipped.
if self.skip_existing.value:
extension_ignore = self.skip_existing == SkipExisting.ExtensionIgnore
# TODO: Check if extension is already in `path_file` or not.
download_skip = check_file_exists(path_file, extension_ignore=extension_ignore)
else:
download_skip = False
if not download_skip:
# Create a temp directory and file.
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp_path_dir:
tmp_path_file = os.path.join(tmp_path_dir, str(uuid4()) + stream_manifest.file_extension)
# Download media.
tmp_path_file = self._download(fn_logger, media, progress, progress_gui, stream_manifest, tmp_path_file)
if isinstance(media, Video) and self.settings.data.video_convert_mp4:
# TODO: Make optional.
# Convert `*.ts` file to `*.mp4` using ffmpeg
tmp_path_file = self._video_convert(tmp_path_file)
path_file = os.path.splitext(path_file)[0] + ".mp4"
# Move final file to the configured destination directory.
os.makedirs(os.path.dirname(path_file), exist_ok=True)
shutil.move(tmp_path_file, path_file)
else:
fn_logger.debug(f"Download skipped, since file exists: '{path_file}'")
return not download_skip, path_file
| def cover_url(self, sid: str, dimension: CoverDimensions = CoverDimensions.Px320): | 2 | 2023-12-19 23:05:47+00:00 | 8k |
smoores-dev/storyteller | storyteller/synchronize/sync.py | [
{
"identifier": "CACHE_DIR",
"path": "storyteller/synchronize/files.py",
"snippet": "CACHE_DIR = f\"{DATA_DIR}/cache\""
},
{
"identifier": "TEXT_DIR",
"path": "storyteller/synchronize/files.py",
"snippet": "TEXT_DIR = f\"{DATA_DIR}/assets/text\""
},
{
"identifier": "get_audio_cha... | from dataclasses import dataclass
from itertools import groupby
from pathlib import Path
from typing import Any, Callable, Dict, List, TypedDict, Union, cast
from fuzzysearch import Match, find_near_matches
from ebooklib import epub
from mutagen.mp4 import MP4
from mutagen.mp3 import MP3
from .files import CACHE_DIR, TEXT_DIR
from .audio import (
get_audio_chapter_filenames,
get_transcriptions,
)
from .epub import (
SentenceRange,
create_media_overlay,
get_chapter_sentences,
get_chapter_text,
get_epub_audio_filename,
get_sentences_with_offsets,
read_epub,
get_chapters,
tag_sentences,
)
import json
import math
import os
import sys
import whisperx.types | 3,768 | count = sentence_range.id - last_sentence_range.id
diff = last_sentence_range.end - last_sentence_range.start
interpolated_length = diff / count
for i in range(1, count):
interpolated_sentence_range = SentenceRange(
last_sentence_range.id + i,
last_sentence_range.start + interpolated_length * i,
last_sentence_range.start + interpolated_length * (i + 1),
last_sentence_range.audiofile,
)
interpolated.append(interpolated_sentence_range)
interpolated.append(sentence_range)
return interpolated
def get_chapter_duration(sentence_ranges: List[SentenceRange]):
duration = 0
for _, file_group in groupby(sentence_ranges, key=lambda r: r.audiofile):
file_group_list = list(file_group)
duration += file_group_list[-1].end - file_group_list[0].start
return duration
@dataclass
class SyncedChapter:
chapter: epub.EpubHtml
sentence_ranges: List[SentenceRange]
audio: List[epub.EpubItem]
def sync_chapter(
start_sentence: int,
transcription: StorytellerTranscription,
chapter: epub.EpubHtml,
transcription_offset: int,
last_sentence_range: Union[SentenceRange, None],
):
chapter_sentences = get_chapter_sentences(chapter)
sentence_ranges = get_sentence_ranges(
start_sentence,
transcription,
chapter_sentences,
transcription_offset,
last_sentence_range,
)
sentence_ranges = interpolate_sentence_ranges(sentence_ranges)
tag_sentences(chapter)
chapter_filepath_length = len(chapter.file_name.split(os.path.sep)) - 1
relative_ups = "../" * chapter_filepath_length
chapter.add_link(
rel="stylesheet",
href=f"{relative_ups}Styles/storyteller-readaloud.css",
type="text/css",
)
audiofiles = set([sentence_range.audiofile for sentence_range in sentence_ranges])
audio_items = []
for audiofile in audiofiles:
epub_audio_filename = get_epub_audio_filename(audiofile)
audio_item = epub.EpubItem(
uid=epub_audio_filename,
file_name=epub_audio_filename,
content=open(audiofile, "rb").read(), # type: ignore
media_type="audio/mpeg",
)
audio_items.append(audio_item)
return SyncedChapter(
chapter=chapter,
sentence_ranges=sentence_ranges,
audio=audio_items,
)
def format_duration(duration: float):
hours = math.floor(duration / 3600)
minutes = math.floor(duration / 60 - hours * 60)
seconds = duration - minutes * 60 - hours * 3600
return f"{str(hours).zfill(2)}:{str(minutes).zfill(2)}:{round(seconds, 3)}"
def update_synced_chapter(book: epub.EpubBook, synced: SyncedChapter):
base_filename, _ = os.path.splitext(os.path.basename(synced.chapter.file_name))
media_overlay_item = epub.EpubSMIL(
uid=f"{base_filename}_overlay",
file_name=f"MediaOverlays/{base_filename}.smil",
content=create_media_overlay(
base_filename, synced.chapter.file_name, synced.sentence_ranges
),
)
synced.chapter.media_overlay = media_overlay_item.id
duration = get_chapter_duration(synced.sentence_ranges)
book.add_metadata(
None,
"meta",
format_duration(duration),
{"property": "media:duration", "refines": f"#{media_overlay_item.id}"},
)
for audio_item in synced.audio:
if book.get_item_with_id(audio_item.id) is None:
book.add_item(audio_item)
book.add_item(media_overlay_item)
return duration
def sync_book(
ebook_name: str,
audiobook_name: str,
on_progress: Callable[[float], None] | None = None,
):
|
class NullIO:
def __enter__(self):
self._original_stdout = sys.stdout
self._original_stderr = sys.stderr
sys.stdout = open(os.devnull, "w")
sys.stderr = open(os.devnull, "w")
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = self._original_stdout
sys.stderr.close()
sys.stderr = self._original_stderr
OFFSET_SEARCH_WINDOW_SIZE = 5000
def find_best_offset(
epub_sentences: list[str], transcription_text: str, last_match_offset: int
):
i = 0
while i < len(transcription_text):
start_sentence = 0
start_index = (last_match_offset + i) % len(transcription_text)
end_index = (start_index + OFFSET_SEARCH_WINDOW_SIZE) % len(transcription_text)
if end_index > start_index:
transcription_text_slice = transcription_text[start_index:end_index]
else:
transcription_text_slice = (
transcription_text[start_index:] + transcription_text[:end_index]
)
while start_sentence < len(epub_sentences):
query_string = " ".join(epub_sentences[start_sentence : start_sentence + 6])
with NullIO():
matches = find_near_matches(
query_string.lower(),
transcription_text_slice.lower(),
max_l_dist=math.floor(0.1 * len(query_string)),
)
matches = cast(List[Match], matches)
if len(matches) > 0:
return (start_sentence, matches[0].start + start_index)
start_sentence += 3
i += OFFSET_SEARCH_WINDOW_SIZE // 2
return (0, None)
class StorytellerTranscriptionSegment(whisperx.types.SingleAlignedSegment):
audiofile: str
class StorytellerTranscription(TypedDict):
segments: List[StorytellerTranscriptionSegment]
word_segments: List[whisperx.types.SingleWordSegment]
def concat_transcriptions(
transcriptions: List[whisperx.types.AlignedTranscriptionResult],
audiofiles: List[str],
):
result = StorytellerTranscription(segments=[], word_segments=[])
for transcription, audiofile in zip(transcriptions, audiofiles):
result["word_segments"].extend(transcription["word_segments"])
result["segments"].extend(
[
StorytellerTranscriptionSegment(**segment, audiofile=audiofile)
for segment in transcription["segments"]
]
)
return result
def get_transcription_text(transcription: StorytellerTranscription):
return " ".join([segment["text"] for segment in transcription["segments"]])
def find_timestamps(match_start_index: int, transcription: StorytellerTranscription):
s = 0
position = 0
while True:
while position + len(transcription["segments"][s]["text"]) < match_start_index: # type: ignore
position += len(transcription["segments"][s]["text"]) + 1 # type: ignore
s += 1
w = 0
segment = transcription["segments"][s]
while (
w < len(segment["words"])
and position + len(segment["words"][w]["word"]) <= match_start_index
):
position += len(segment["words"][w]["word"]) + 1
w += 1
if w >= len(segment["words"]):
s += 1
continue
break
start_word = segment["words"][w]
# If a segment only has one word, the start and
# end timestamps are only placed on the segment
if "start" in start_word:
return start_word["start"], segment["audiofile"]
return segment["start"], segment["audiofile"]
def get_window_index_from_offset(window: List[str], offset: int):
index = 0
while offset >= len(window[index]):
offset -= len(window[index])
index += 1
return index
def get_sentence_ranges(
start_sentence: int,
transcription: StorytellerTranscription,
sentences: List[str],
chapter_offset: int,
last_sentence_range: Union[SentenceRange, None],
):
sentence_ranges: List[SentenceRange] = []
transcription_text = get_transcription_text(transcription).lower()[chapter_offset:]
transcription_sentences = get_sentences_with_offsets(transcription_text)
transcription_window_index = 0
last_good_transcription_window = 0
not_found = 0
sentence_index = start_sentence
while sentence_index < len(sentences):
sentence = sentences[sentence_index]
transcription_window_list = transcription_sentences[
transcription_window_index : transcription_window_index + 10
]
transcription_window = "".join(transcription_window_list)
matches = find_near_matches(
sentence.strip().lower(),
transcription_window,
max_l_dist=math.floor(0.25 * len(sentence)),
)
matches = cast(List[Match], matches)
if len(matches) == 0:
sentence_index += 1
not_found += 1
if not_found == 3 or sentence_index == len(sentences) - 1:
transcription_window_index += 1
if transcription_window_index == last_good_transcription_window + 30:
transcription_window_index = last_good_transcription_window
not_found = 0
continue
sentence_index -= not_found
not_found = 0
continue
first_match = matches[0]
transcription_offset = (
len("".join(transcription_sentences[:transcription_window_index])) + 1
)
start, audiofile = find_timestamps(
first_match.start + transcription_offset + chapter_offset, transcription
)
if len(sentence_ranges) > 0:
last_audiofile = sentence_ranges[-1].audiofile
if audiofile == last_audiofile:
sentence_ranges[-1].end = start
else:
last_mp4 = (
MP4(last_audiofile)
if last_audiofile.endswith(".mp4")
else MP3(last_audiofile)
)
sentence_ranges[-1].end = last_mp4.info.length
start = 0
elif last_sentence_range is not None:
if audiofile == last_sentence_range.audiofile:
last_sentence_range.end = start
else:
last_mp4 = (
MP4(last_sentence_range.audiofile)
if last_sentence_range.audiofile.endswith(".mp4")
else MP3(last_sentence_range.audiofile)
)
last_sentence_range.end = last_mp4.info.length
start = 0
else:
start = 0
sentence_ranges.append(SentenceRange(sentence_index, start, start, audiofile))
not_found = 0
transcription_window_index = (
get_window_index_from_offset(transcription_window_list, first_match.start)
+ transcription_window_index
)
last_good_transcription_window = transcription_window_index
sentence_index += 1
return sentence_ranges
def interpolate_sentence_ranges(
sentence_ranges: List[SentenceRange],
) -> List[SentenceRange]:
interpolated: List[SentenceRange] = []
for sentence_range in sentence_ranges:
if len(interpolated) == 0:
interpolated.append(sentence_range)
continue
last_sentence_range = interpolated[-1]
count = sentence_range.id - last_sentence_range.id
diff = last_sentence_range.end - last_sentence_range.start
interpolated_length = diff / count
for i in range(1, count):
interpolated_sentence_range = SentenceRange(
last_sentence_range.id + i,
last_sentence_range.start + interpolated_length * i,
last_sentence_range.start + interpolated_length * (i + 1),
last_sentence_range.audiofile,
)
interpolated.append(interpolated_sentence_range)
interpolated.append(sentence_range)
return interpolated
def get_chapter_duration(sentence_ranges: List[SentenceRange]):
duration = 0
for _, file_group in groupby(sentence_ranges, key=lambda r: r.audiofile):
file_group_list = list(file_group)
duration += file_group_list[-1].end - file_group_list[0].start
return duration
@dataclass
class SyncedChapter:
chapter: epub.EpubHtml
sentence_ranges: List[SentenceRange]
audio: List[epub.EpubItem]
def sync_chapter(
start_sentence: int,
transcription: StorytellerTranscription,
chapter: epub.EpubHtml,
transcription_offset: int,
last_sentence_range: Union[SentenceRange, None],
):
chapter_sentences = get_chapter_sentences(chapter)
sentence_ranges = get_sentence_ranges(
start_sentence,
transcription,
chapter_sentences,
transcription_offset,
last_sentence_range,
)
sentence_ranges = interpolate_sentence_ranges(sentence_ranges)
tag_sentences(chapter)
chapter_filepath_length = len(chapter.file_name.split(os.path.sep)) - 1
relative_ups = "../" * chapter_filepath_length
chapter.add_link(
rel="stylesheet",
href=f"{relative_ups}Styles/storyteller-readaloud.css",
type="text/css",
)
audiofiles = set([sentence_range.audiofile for sentence_range in sentence_ranges])
audio_items = []
for audiofile in audiofiles:
epub_audio_filename = get_epub_audio_filename(audiofile)
audio_item = epub.EpubItem(
uid=epub_audio_filename,
file_name=epub_audio_filename,
content=open(audiofile, "rb").read(), # type: ignore
media_type="audio/mpeg",
)
audio_items.append(audio_item)
return SyncedChapter(
chapter=chapter,
sentence_ranges=sentence_ranges,
audio=audio_items,
)
def format_duration(duration: float):
hours = math.floor(duration / 3600)
minutes = math.floor(duration / 60 - hours * 60)
seconds = duration - minutes * 60 - hours * 3600
return f"{str(hours).zfill(2)}:{str(minutes).zfill(2)}:{round(seconds, 3)}"
def update_synced_chapter(book: epub.EpubBook, synced: SyncedChapter):
base_filename, _ = os.path.splitext(os.path.basename(synced.chapter.file_name))
media_overlay_item = epub.EpubSMIL(
uid=f"{base_filename}_overlay",
file_name=f"MediaOverlays/{base_filename}.smil",
content=create_media_overlay(
base_filename, synced.chapter.file_name, synced.sentence_ranges
),
)
synced.chapter.media_overlay = media_overlay_item.id
duration = get_chapter_duration(synced.sentence_ranges)
book.add_metadata(
None,
"meta",
format_duration(duration),
{"property": "media:duration", "refines": f"#{media_overlay_item.id}"},
)
for audio_item in synced.audio:
if book.get_item_with_id(audio_item.id) is None:
book.add_item(audio_item)
book.add_item(media_overlay_item)
return duration
def sync_book(
ebook_name: str,
audiobook_name: str,
on_progress: Callable[[float], None] | None = None,
): | book = read_epub(ebook_name) | 10 | 2023-12-15 16:07:12+00:00 | 8k |
zyrant/SPGroup3D | mmdet3d/core/visualizer/show_result.py | [
{
"identifier": "draw_camera_bbox3d_on_img",
"path": "mmdet3d/core/visualizer/image_vis.py",
"snippet": "def draw_camera_bbox3d_on_img(bboxes3d,\n raw_img,\n cam2img,\n img_metas,\n color=... | from os import path as osp
from .image_vis import (draw_camera_bbox3d_on_img, draw_depth_bbox3d_on_img,
draw_lidar_bbox3d_on_img)
from .open3d_vis import Visualizer
from .open3d_vis import Visualizer
import mmcv
import numpy as np
import trimesh
import matplotlib.pyplot as plt | 4,274 | superpoints = map_color[superpoints]
superpoints = np.concatenate([points[:, :3], superpoints],
axis=1)
_write_obj(superpoints, osp.join(result_path, f'{filename}_superpoints.obj'))
if gt_corners is not None:
_write_oriented_bbox_v2(gt_corners, gt_labels,
osp.join(result_path, f'{filename}_gt.obj'))
if pred_corners is not None:
_write_oriented_bbox_v2(pred_corners, pred_labels,
osp.join(result_path, f'{filename}_pred.obj'))
def show_seg_result(points,
gt_seg,
pred_seg,
out_dir,
filename,
palette,
ignore_index=None,
show=False,
snapshot=False):
"""Convert results into format that is directly readable for meshlab.
Args:
points (np.ndarray): Points.
gt_seg (np.ndarray): Ground truth segmentation mask.
pred_seg (np.ndarray): Predicted segmentation mask.
out_dir (str): Path of output directory
filename (str): Filename of the current frame.
palette (np.ndarray): Mapping between class labels and colors.
ignore_index (int, optional): The label index to be ignored, e.g.
unannotated points. Defaults to None.
show (bool, optional): Visualize the results online. Defaults to False.
snapshot (bool, optional): Whether to save the online results.
Defaults to False.
"""
# we need 3D coordinates to visualize segmentation mask
if gt_seg is not None or pred_seg is not None:
assert points is not None, \
'3D coordinates are required for segmentation visualization'
# filter out ignored points
if gt_seg is not None and ignore_index is not None:
if points is not None:
points = points[gt_seg != ignore_index]
if pred_seg is not None:
pred_seg = pred_seg[gt_seg != ignore_index]
gt_seg = gt_seg[gt_seg != ignore_index]
if gt_seg is not None:
gt_seg_color = palette[gt_seg]
gt_seg_color = np.concatenate([points[:, :3], gt_seg_color], axis=1)
if pred_seg is not None:
pred_seg_color = palette[pred_seg]
pred_seg_color = np.concatenate([points[:, :3], pred_seg_color],
axis=1)
result_path = osp.join(out_dir, filename)
mmcv.mkdir_or_exist(result_path)
# online visualization of segmentation mask
# we show three masks in a row, scene_points, gt_mask, pred_mask
if show:
mode = 'xyzrgb' if points.shape[1] == 6 else 'xyz'
vis = Visualizer(points, mode=mode)
if gt_seg is not None:
vis.add_seg_mask(gt_seg_color)
if pred_seg is not None:
vis.add_seg_mask(pred_seg_color)
show_path = osp.join(result_path,
f'{filename}_online.png') if snapshot else None
vis.show(show_path)
if points is not None:
_write_obj(points, osp.join(result_path, f'{filename}_points.obj'))
if gt_seg is not None:
_write_obj(gt_seg_color, osp.join(result_path, f'{filename}_gt.obj'))
if pred_seg is not None:
_write_obj(pred_seg_color, osp.join(result_path,
f'{filename}_pred.obj'))
def show_multi_modality_result(img,
gt_bboxes,
pred_bboxes,
proj_mat,
out_dir,
filename,
box_mode='lidar',
img_metas=None,
show=False,
gt_bbox_color=(61, 102, 255),
pred_bbox_color=(241, 101, 72)):
"""Convert multi-modality detection results into 2D results.
Project the predicted 3D bbox to 2D image plane and visualize them.
Args:
img (np.ndarray): The numpy array of image in cv2 fashion.
gt_bboxes (:obj:`BaseInstance3DBoxes`): Ground truth boxes.
pred_bboxes (:obj:`BaseInstance3DBoxes`): Predicted boxes.
proj_mat (numpy.array, shape=[4, 4]): The projection matrix
according to the camera intrinsic parameters.
out_dir (str): Path of output directory.
filename (str): Filename of the current frame.
box_mode (str, optional): Coordinate system the boxes are in.
Should be one of 'depth', 'lidar' and 'camera'.
Defaults to 'lidar'.
img_metas (dict, optional): Used in projecting depth bbox.
Defaults to None.
show (bool, optional): Visualize the results online. Defaults to False.
gt_bbox_color (str or tuple(int), optional): Color of bbox lines.
The tuple of color should be in BGR order. Default: (255, 102, 61).
pred_bbox_color (str or tuple(int), optional): Color of bbox lines.
The tuple of color should be in BGR order. Default: (72, 101, 241).
"""
if box_mode == 'depth':
| # Copyright (c) OpenMMLab. All rights reserved.
def _write_obj(points, out_filename):
"""Write points into ``obj`` format for meshlab visualization.
Args:
points (np.ndarray): Points in shape (N, dim).
out_filename (str): Filename to be saved.
"""
N = points.shape[0]
fout = open(out_filename, 'w')
for i in range(N):
if points.shape[1] == 6:
c = points[i, 3:].astype(int)
fout.write(
'v %f %f %f %d %d %d\n' %
(points[i, 0], points[i, 1], points[i, 2], c[0], c[1], c[2]))
else:
fout.write('v %f %f %f\n' %
(points[i, 0], points[i, 1], points[i, 2]))
fout.close()
def _write_oriented_bbox(scene_bbox, out_filename):
"""Export oriented (around Z axis) scene bbox to meshes.
Args:
scene_bbox(list[ndarray] or ndarray): xyz pos of center and
3 lengths (x_size, y_size, z_size) and heading angle around Z axis.
Y forward, X right, Z upward. heading angle of positive X is 0,
heading angle of positive Y is 90 degrees.
out_filename(str): Filename.
"""
def heading2rotmat(heading_angle):
rotmat = np.zeros((3, 3))
rotmat[2, 2] = 1
cosval = np.cos(heading_angle)
sinval = np.sin(heading_angle)
rotmat[0:2, 0:2] = np.array([[cosval, -sinval], [sinval, cosval]])
return rotmat
def convert_oriented_box_to_trimesh_fmt(box):
ctr = box[:3]
lengths = box[3:6]
trns = np.eye(4)
trns[0:3, 3] = ctr
trns[3, 3] = 1.0
trns[0:3, 0:3] = heading2rotmat(box[6])
box_trimesh_fmt = trimesh.creation.box(lengths, trns)
return box_trimesh_fmt
if len(scene_bbox) == 0:
scene_bbox = np.zeros((1, 7))
scene = trimesh.scene.Scene()
for box in scene_bbox:
scene.add_geometry(convert_oriented_box_to_trimesh_fmt(box))
mesh_list = trimesh.util.concatenate(scene.dump())
# save to obj file
trimesh.io.export.export_mesh(mesh_list, out_filename, file_type='obj')
return
def _write_oriented_bbox_v2(corners, labels, out_filename):
colors = np.multiply([
plt.cm.get_cmap('nipy_spectral', 19)((i * 5 + 11) % 18 + 1)[:3] for i in range(18)
], 255).astype(np.uint8).tolist()
with open(out_filename, 'w') as file:
for i, (corner, label) in enumerate(zip(corners, labels)):
c = colors[label]
for p in corner:
file.write(f'v {p[0]} {p[1]} {p[2]} {c[0]} {c[1]} {c[2]}\n')
j = i * 8 + 1
for k in [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4],
[2, 3, 7, 6], [3, 0, 4, 7], [1, 2, 6, 5]]:
file.write('f')
for l in k:
file.write(f' {j + l}')
file.write('\n')
def show_result(points,
gt_bboxes,
pred_bboxes,
out_dir,
filename,
show=False,
snapshot=False,
pred_labels=None):
"""Convert results into format that is directly readable for meshlab.
Args:
points (np.ndarray): Points.
gt_bboxes (np.ndarray): Ground truth boxes.
pred_bboxes (np.ndarray): Predicted boxes.
out_dir (str): Path of output directory
filename (str): Filename of the current frame.
show (bool, optional): Visualize the results online. Defaults to False.
snapshot (bool, optional): Whether to save the online results.
Defaults to False.
pred_labels (np.ndarray, optional): Predicted labels of boxes.
Defaults to None.
"""
result_path = osp.join(out_dir, filename)
mmcv.mkdir_or_exist(result_path)
if show:
vis = Visualizer(points)
if pred_bboxes is not None:
if pred_labels is None:
vis.add_bboxes(bbox3d=pred_bboxes)
else:
palette = np.random.randint(
0, 255, size=(pred_labels.max() + 1, 3)) / 256
labelDict = {}
for j in range(len(pred_labels)):
i = int(pred_labels[j].numpy())
if labelDict.get(i) is None:
labelDict[i] = []
labelDict[i].append(pred_bboxes[j])
for i in labelDict:
vis.add_bboxes(
bbox3d=np.array(labelDict[i]),
bbox_color=palette[i],
points_in_box_color=palette[i])
if gt_bboxes is not None:
vis.add_bboxes(bbox3d=gt_bboxes, bbox_color=(0, 0, 1))
show_path = osp.join(result_path,
f'{filename}_online.png') if snapshot else None
vis.show(show_path)
if points is not None:
_write_obj(points, osp.join(result_path, f'{filename}_points.obj'))
if gt_bboxes is not None:
# bottom center to gravity center
gt_bboxes[..., 2] += gt_bboxes[..., 5] / 2
_write_oriented_bbox(gt_bboxes,
osp.join(result_path, f'{filename}_gt.obj'))
if pred_bboxes is not None:
# bottom center to gravity center
pred_bboxes[..., 2] += pred_bboxes[..., 5] / 2
_write_oriented_bbox(pred_bboxes,
osp.join(result_path, f'{filename}_pred.obj'))
def show_result_v2(points,
gt_corners,
gt_labels,
pred_corners,
pred_labels,
out_dir,
filename):
result_path = osp.join(out_dir, filename)
mmcv.mkdir_or_exist(result_path)
if points is not None:
_write_obj(points, osp.join(result_path, f'{filename}_points.obj'))
if gt_corners is not None:
_write_oriented_bbox_v2(gt_corners, gt_labels,
osp.join(result_path, f'{filename}_gt.obj'))
if pred_corners is not None:
_write_oriented_bbox_v2(pred_corners, pred_labels,
osp.join(result_path, f'{filename}_pred.obj'))
def show_result_v2_with_superpoint(points,
superpoints,
gt_corners,
gt_labels,
pred_corners,
pred_labels,
out_dir,
filename):
result_path = osp.join(out_dir, filename)
mmcv.mkdir_or_exist(result_path)
if points is not None:
_write_obj(points, osp.join(result_path, f'{filename}_points.obj'))
if superpoints is not None:
map_color = []
for i in range(superpoints.max()+1):
r = np.random.rand(1, 1)
g = np.random.rand(1, 1)
b = np.random.rand(1, 1)
xx = np.concatenate((r, g, b), axis=1) * 255.
map_color.append(xx)
map_color = np.concatenate(map_color, axis=0)
superpoints = map_color[superpoints]
superpoints = np.concatenate([points[:, :3], superpoints],
axis=1)
_write_obj(superpoints, osp.join(result_path, f'{filename}_superpoints.obj'))
if gt_corners is not None:
_write_oriented_bbox_v2(gt_corners, gt_labels,
osp.join(result_path, f'{filename}_gt.obj'))
if pred_corners is not None:
_write_oriented_bbox_v2(pred_corners, pred_labels,
osp.join(result_path, f'{filename}_pred.obj'))
def show_seg_result(points,
gt_seg,
pred_seg,
out_dir,
filename,
palette,
ignore_index=None,
show=False,
snapshot=False):
"""Convert results into format that is directly readable for meshlab.
Args:
points (np.ndarray): Points.
gt_seg (np.ndarray): Ground truth segmentation mask.
pred_seg (np.ndarray): Predicted segmentation mask.
out_dir (str): Path of output directory
filename (str): Filename of the current frame.
palette (np.ndarray): Mapping between class labels and colors.
ignore_index (int, optional): The label index to be ignored, e.g.
unannotated points. Defaults to None.
show (bool, optional): Visualize the results online. Defaults to False.
snapshot (bool, optional): Whether to save the online results.
Defaults to False.
"""
# we need 3D coordinates to visualize segmentation mask
if gt_seg is not None or pred_seg is not None:
assert points is not None, \
'3D coordinates are required for segmentation visualization'
# filter out ignored points
if gt_seg is not None and ignore_index is not None:
if points is not None:
points = points[gt_seg != ignore_index]
if pred_seg is not None:
pred_seg = pred_seg[gt_seg != ignore_index]
gt_seg = gt_seg[gt_seg != ignore_index]
if gt_seg is not None:
gt_seg_color = palette[gt_seg]
gt_seg_color = np.concatenate([points[:, :3], gt_seg_color], axis=1)
if pred_seg is not None:
pred_seg_color = palette[pred_seg]
pred_seg_color = np.concatenate([points[:, :3], pred_seg_color],
axis=1)
result_path = osp.join(out_dir, filename)
mmcv.mkdir_or_exist(result_path)
# online visualization of segmentation mask
# we show three masks in a row, scene_points, gt_mask, pred_mask
if show:
mode = 'xyzrgb' if points.shape[1] == 6 else 'xyz'
vis = Visualizer(points, mode=mode)
if gt_seg is not None:
vis.add_seg_mask(gt_seg_color)
if pred_seg is not None:
vis.add_seg_mask(pred_seg_color)
show_path = osp.join(result_path,
f'{filename}_online.png') if snapshot else None
vis.show(show_path)
if points is not None:
_write_obj(points, osp.join(result_path, f'{filename}_points.obj'))
if gt_seg is not None:
_write_obj(gt_seg_color, osp.join(result_path, f'{filename}_gt.obj'))
if pred_seg is not None:
_write_obj(pred_seg_color, osp.join(result_path,
f'{filename}_pred.obj'))
def show_multi_modality_result(img,
gt_bboxes,
pred_bboxes,
proj_mat,
out_dir,
filename,
box_mode='lidar',
img_metas=None,
show=False,
gt_bbox_color=(61, 102, 255),
pred_bbox_color=(241, 101, 72)):
"""Convert multi-modality detection results into 2D results.
Project the predicted 3D bbox to 2D image plane and visualize them.
Args:
img (np.ndarray): The numpy array of image in cv2 fashion.
gt_bboxes (:obj:`BaseInstance3DBoxes`): Ground truth boxes.
pred_bboxes (:obj:`BaseInstance3DBoxes`): Predicted boxes.
proj_mat (numpy.array, shape=[4, 4]): The projection matrix
according to the camera intrinsic parameters.
out_dir (str): Path of output directory.
filename (str): Filename of the current frame.
box_mode (str, optional): Coordinate system the boxes are in.
Should be one of 'depth', 'lidar' and 'camera'.
Defaults to 'lidar'.
img_metas (dict, optional): Used in projecting depth bbox.
Defaults to None.
show (bool, optional): Visualize the results online. Defaults to False.
gt_bbox_color (str or tuple(int), optional): Color of bbox lines.
The tuple of color should be in BGR order. Default: (255, 102, 61).
pred_bbox_color (str or tuple(int), optional): Color of bbox lines.
The tuple of color should be in BGR order. Default: (72, 101, 241).
"""
if box_mode == 'depth': | draw_bbox = draw_depth_bbox3d_on_img | 1 | 2023-12-21 12:50:35+00:00 | 8k |
jdejaegh/irm-kmi-ha | custom_components/irm_kmi/coordinator.py | [
{
"identifier": "IrmKmiApiClient",
"path": "custom_components/irm_kmi/api.py",
"snippet": "class IrmKmiApiClient:\n \"\"\"API client for IRM KMI weather data\"\"\"\n COORD_DECIMALS = 6\n\n def __init__(self, session: aiohttp.ClientSession) -> None:\n self._session = session\n self... | import asyncio
import logging
import async_timeout
import pytz
from datetime import datetime, timedelta
from typing import Any, List, Tuple
from homeassistant.components.weather import Forecast
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE, CONF_ZONE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import issue_registry
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import (DataUpdateCoordinator,
UpdateFailed)
from .api import IrmKmiApiClient, IrmKmiApiError
from .const import CONF_DARK_MODE, CONF_STYLE, DOMAIN
from .const import IRM_KMI_TO_HA_CONDITION_MAP as CDT_MAP
from .const import LANGS
from .const import MAP_WARNING_ID_TO_SLUG as SLUG_MAP
from .const import OPTION_STYLE_SATELLITE, OUT_OF_BENELUX, STYLE_TO_PARAM_MAP
from .data import (AnimationFrameData, CurrentWeatherData, IrmKmiForecast,
ProcessedCoordinatorData, RadarAnimationData, WarningData)
from .rain_graph import RainGraph
from .utils import disable_from_config, get_config_value | 6,533 | """DataUpdateCoordinator for the IRM KMI integration."""
_LOGGER = logging.getLogger(__name__)
class IrmKmiCoordinator(DataUpdateCoordinator):
"""Coordinator to update data from IRM KMI"""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry):
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
# Name of the data. For logging purposes.
name="IRM KMI weather",
# Polling interval. Will only be polled if there are subscribers.
update_interval=timedelta(minutes=7),
)
self._api_client = IrmKmiApiClient(session=async_get_clientsession(hass))
self._zone = get_config_value(entry, CONF_ZONE)
| """DataUpdateCoordinator for the IRM KMI integration."""
_LOGGER = logging.getLogger(__name__)
class IrmKmiCoordinator(DataUpdateCoordinator):
"""Coordinator to update data from IRM KMI"""
def __init__(self, hass: HomeAssistant, entry: ConfigEntry):
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
# Name of the data. For logging purposes.
name="IRM KMI weather",
# Polling interval. Will only be polled if there are subscribers.
update_interval=timedelta(minutes=7),
)
self._api_client = IrmKmiApiClient(session=async_get_clientsession(hass))
self._zone = get_config_value(entry, CONF_ZONE) | self._dark_mode = get_config_value(entry, CONF_DARK_MODE) | 2 | 2023-12-17 16:35:01+00:00 | 8k |
v3ucn/Bert-vits2-V2.2 | webui.py | [
{
"identifier": "split_by_language",
"path": "tools/sentence.py",
"snippet": "def split_by_language(text: str, target_languages: list = None) -> list:\n pattern = (\n r\"[\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\-\\.\\/\\:\\;\\<\\>\\=\\?\\@\\[\\]\\{\\}\\\\\\\\\\^\\_\\`\"\n r\"\\!?\\。"#$%&... | import os
import logging
import re_matching
import torch
import utils
import gradio as gr
import webbrowser
import numpy as np
import librosa
from tools.sentence import split_by_language
from infer import infer, latest_version, get_net_g, infer_multilang
from config import config
from tools.translate import translate | 3,828 | net_g=net_g,
device=device,
skip_start=skip_start,
skip_end=skip_end,
)
audio_list_sent.append(audio)
silence = np.zeros((int)(44100 * interval_between_sent))
audio_list_sent.append(silence)
if (interval_between_para - interval_between_sent) > 0:
silence = np.zeros(
(int)(44100 * (interval_between_para - interval_between_sent))
)
audio_list_sent.append(silence)
audio16bit = gr.processing_utils.convert_to_16_bit_wav(
np.concatenate(audio_list_sent)
) # 对完整句子做音量归一
audio_list.append(audio16bit)
audio_concat = np.concatenate(audio_list)
return ("Success", (44100, audio_concat))
def tts_fn(
text: str,
speaker,
sdp_ratio,
noise_scale,
noise_scale_w,
length_scale,
language,
reference_audio,
emotion,
prompt_mode,
):
if prompt_mode == "Audio prompt":
if reference_audio == None:
return ("Invalid audio prompt", None)
else:
reference_audio = load_audio(reference_audio)[1]
else:
reference_audio = None
audio_list = []
if language == "mix":
bool_valid, str_valid = re_matching.validate_text(text)
if not bool_valid:
return str_valid, (
hps.data.sampling_rate,
np.concatenate([np.zeros(hps.data.sampling_rate // 2)]),
)
result = []
for slice in re_matching.text_matching(text):
_speaker = slice.pop()
temp_contant = []
temp_lang = []
for lang, content in slice:
if "|" in content:
temp = []
temp_ = []
for i in content.split("|"):
if i != "":
temp.append([i])
temp_.append([lang])
else:
temp.append([])
temp_.append([])
temp_contant += temp
temp_lang += temp_
else:
if len(temp_contant) == 0:
temp_contant.append([])
temp_lang.append([])
temp_contant[-1].append(content)
temp_lang[-1].append(lang)
for i, j in zip(temp_lang, temp_contant):
result.append([*zip(i, j), _speaker])
for i, one in enumerate(result):
skip_start = i != 0
skip_end = i != len(result) - 1
_speaker = one.pop()
idx = 0
while idx < len(one):
text_to_generate = []
lang_to_generate = []
while True:
lang, content = one[idx]
temp_text = [content]
if len(text_to_generate) > 0:
text_to_generate[-1] += [temp_text.pop(0)]
lang_to_generate[-1] += [lang]
if len(temp_text) > 0:
text_to_generate += [[i] for i in temp_text]
lang_to_generate += [[lang]] * len(temp_text)
if idx + 1 < len(one):
idx += 1
else:
break
skip_start = (idx != 0) and skip_start
skip_end = (idx != len(one) - 1) and skip_end
print(text_to_generate, lang_to_generate)
audio_list.extend(
generate_audio_multilang(
text_to_generate,
sdp_ratio,
noise_scale,
noise_scale_w,
length_scale,
_speaker,
lang_to_generate,
reference_audio,
emotion,
skip_start,
skip_end,
)
)
idx += 1
elif language.lower() == "auto":
for idx, slice in enumerate(text.split("|")):
if slice == "":
continue
skip_start = idx != 0
skip_end = idx != len(text.split("|")) - 1
| # flake8: noqa: E402
logging.getLogger("numba").setLevel(logging.WARNING)
logging.getLogger("markdown_it").setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
logging.getLogger("matplotlib").setLevel(logging.WARNING)
logging.basicConfig(
level=logging.INFO, format="| %(name)s | %(levelname)s | %(message)s"
)
logger = logging.getLogger(__name__)
net_g = None
device = config.webui_config.device
if device == "mps":
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
def generate_audio(
slices,
sdp_ratio,
noise_scale,
noise_scale_w,
length_scale,
speaker,
language,
reference_audio,
emotion,
skip_start=False,
skip_end=False,
):
audio_list = []
# silence = np.zeros(hps.data.sampling_rate // 2, dtype=np.int16)
with torch.no_grad():
for idx, piece in enumerate(slices):
skip_start = (idx != 0) and skip_start
skip_end = (idx != len(slices) - 1) and skip_end
audio = infer(
piece,
reference_audio=reference_audio,
emotion=emotion,
sdp_ratio=sdp_ratio,
noise_scale=noise_scale,
noise_scale_w=noise_scale_w,
length_scale=length_scale,
sid=speaker,
language=language,
hps=hps,
net_g=net_g,
device=device,
skip_start=skip_start,
skip_end=skip_end,
)
audio16bit = gr.processing_utils.convert_to_16_bit_wav(audio)
audio_list.append(audio16bit)
# audio_list.append(silence) # 将静音添加到列表中
return audio_list
def generate_audio_multilang(
slices,
sdp_ratio,
noise_scale,
noise_scale_w,
length_scale,
speaker,
language,
reference_audio,
emotion,
skip_start=False,
skip_end=False,
):
audio_list = []
# silence = np.zeros(hps.data.sampling_rate // 2, dtype=np.int16)
with torch.no_grad():
for idx, piece in enumerate(slices):
skip_start = (idx != 0) and skip_start
skip_end = (idx != len(slices) - 1) and skip_end
audio = infer_multilang(
piece,
reference_audio=reference_audio,
emotion=emotion,
sdp_ratio=sdp_ratio,
noise_scale=noise_scale,
noise_scale_w=noise_scale_w,
length_scale=length_scale,
sid=speaker,
language=language[idx],
hps=hps,
net_g=net_g,
device=device,
skip_start=skip_start,
skip_end=skip_end,
)
audio16bit = gr.processing_utils.convert_to_16_bit_wav(audio)
audio_list.append(audio16bit)
# audio_list.append(silence) # 将静音添加到列表中
return audio_list
def tts_split(
text: str,
speaker,
sdp_ratio,
noise_scale,
noise_scale_w,
length_scale,
language,
cut_by_sent,
interval_between_para,
interval_between_sent,
reference_audio,
emotion,
):
if language == "mix":
return ("invalid", None)
while text.find("\n\n") != -1:
text = text.replace("\n\n", "\n")
para_list = re_matching.cut_para(text)
audio_list = []
if not cut_by_sent:
for idx, p in enumerate(para_list):
skip_start = idx != 0
skip_end = idx != len(para_list) - 1
audio = infer(
p,
reference_audio=reference_audio,
emotion=emotion,
sdp_ratio=sdp_ratio,
noise_scale=noise_scale,
noise_scale_w=noise_scale_w,
length_scale=length_scale,
sid=speaker,
language=language,
hps=hps,
net_g=net_g,
device=device,
skip_start=skip_start,
skip_end=skip_end,
)
audio16bit = gr.processing_utils.convert_to_16_bit_wav(audio)
audio_list.append(audio16bit)
silence = np.zeros((int)(44100 * interval_between_para), dtype=np.int16)
audio_list.append(silence)
else:
for idx, p in enumerate(para_list):
skip_start = idx != 0
skip_end = idx != len(para_list) - 1
audio_list_sent = []
sent_list = re_matching.cut_sent(p)
for idx, s in enumerate(sent_list):
skip_start = (idx != 0) and skip_start
skip_end = (idx != len(sent_list) - 1) and skip_end
audio = infer(
s,
reference_audio=reference_audio,
emotion=emotion,
sdp_ratio=sdp_ratio,
noise_scale=noise_scale,
noise_scale_w=noise_scale_w,
length_scale=length_scale,
sid=speaker,
language=language,
hps=hps,
net_g=net_g,
device=device,
skip_start=skip_start,
skip_end=skip_end,
)
audio_list_sent.append(audio)
silence = np.zeros((int)(44100 * interval_between_sent))
audio_list_sent.append(silence)
if (interval_between_para - interval_between_sent) > 0:
silence = np.zeros(
(int)(44100 * (interval_between_para - interval_between_sent))
)
audio_list_sent.append(silence)
audio16bit = gr.processing_utils.convert_to_16_bit_wav(
np.concatenate(audio_list_sent)
) # 对完整句子做音量归一
audio_list.append(audio16bit)
audio_concat = np.concatenate(audio_list)
return ("Success", (44100, audio_concat))
def tts_fn(
text: str,
speaker,
sdp_ratio,
noise_scale,
noise_scale_w,
length_scale,
language,
reference_audio,
emotion,
prompt_mode,
):
if prompt_mode == "Audio prompt":
if reference_audio == None:
return ("Invalid audio prompt", None)
else:
reference_audio = load_audio(reference_audio)[1]
else:
reference_audio = None
audio_list = []
if language == "mix":
bool_valid, str_valid = re_matching.validate_text(text)
if not bool_valid:
return str_valid, (
hps.data.sampling_rate,
np.concatenate([np.zeros(hps.data.sampling_rate // 2)]),
)
result = []
for slice in re_matching.text_matching(text):
_speaker = slice.pop()
temp_contant = []
temp_lang = []
for lang, content in slice:
if "|" in content:
temp = []
temp_ = []
for i in content.split("|"):
if i != "":
temp.append([i])
temp_.append([lang])
else:
temp.append([])
temp_.append([])
temp_contant += temp
temp_lang += temp_
else:
if len(temp_contant) == 0:
temp_contant.append([])
temp_lang.append([])
temp_contant[-1].append(content)
temp_lang[-1].append(lang)
for i, j in zip(temp_lang, temp_contant):
result.append([*zip(i, j), _speaker])
for i, one in enumerate(result):
skip_start = i != 0
skip_end = i != len(result) - 1
_speaker = one.pop()
idx = 0
while idx < len(one):
text_to_generate = []
lang_to_generate = []
while True:
lang, content = one[idx]
temp_text = [content]
if len(text_to_generate) > 0:
text_to_generate[-1] += [temp_text.pop(0)]
lang_to_generate[-1] += [lang]
if len(temp_text) > 0:
text_to_generate += [[i] for i in temp_text]
lang_to_generate += [[lang]] * len(temp_text)
if idx + 1 < len(one):
idx += 1
else:
break
skip_start = (idx != 0) and skip_start
skip_end = (idx != len(one) - 1) and skip_end
print(text_to_generate, lang_to_generate)
audio_list.extend(
generate_audio_multilang(
text_to_generate,
sdp_ratio,
noise_scale,
noise_scale_w,
length_scale,
_speaker,
lang_to_generate,
reference_audio,
emotion,
skip_start,
skip_end,
)
)
idx += 1
elif language.lower() == "auto":
for idx, slice in enumerate(text.split("|")):
if slice == "":
continue
skip_start = idx != 0
skip_end = idx != len(text.split("|")) - 1 | sentences_list = split_by_language( | 0 | 2023-12-18 04:54:46+00:00 | 8k |
d-krupke/CP-SAT-Log-Analyzer | tests/test_examples.py | [
{
"identifier": "LogParser",
"path": "cpsat_log_parser/parser.py",
"snippet": "class LogParser:\n def __init__(self, log: typing.Union[str, typing.List[str]]) -> None:\n self.comments, log_without_comments = self._extract_comments(log)\n self.blocks = self.parse_blocks(log_without_comme... | import os
import sys
from cpsat_log_parser import LogParser
from cpsat_log_parser.blocks import (
SearchProgressBlock,
SolverBlock,
ResponseBlock,
) | 3,942 |
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
EXAMPLE_DIR = os.path.join(os.path.dirname(__file__), "../example_logs")
def test_all_examples():
for file in os.listdir(EXAMPLE_DIR):
if file.endswith(".txt"):
with open(os.path.join(EXAMPLE_DIR, file)) as f:
print(f"Testing {file}")
data = f.read()
|
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
EXAMPLE_DIR = os.path.join(os.path.dirname(__file__), "../example_logs")
def test_all_examples():
for file in os.listdir(EXAMPLE_DIR):
if file.endswith(".txt"):
with open(os.path.join(EXAMPLE_DIR, file)) as f:
print(f"Testing {file}")
data = f.read() | parser = LogParser(data) | 0 | 2023-12-18 09:18:19+00:00 | 8k |
KatantDev/YMdantic | ymdantic/models/tracks/track.py | [
{
"identifier": "DeprecatedMixin",
"path": "ymdantic/mixins.py",
"snippet": "class DeprecatedMixin:\n \"\"\"Миксин, удаляющий устаревшие поля из модели.\"\"\"\n\n @model_validator(mode=\"before\")\n def remove_deprecated(cls, obj: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"\n Удал... | from typing import List, Optional, Literal
from pydantic import HttpUrl
from ymdantic.mixins import DeprecatedMixin
from ymdantic.models.artists import Artist
from ymdantic.models.base import YMBaseModel
from ymdantic.models.chart_position import ChartPosition
from ymdantic.models.tracks.r128 import R128
from ymdantic.models.tracks.fade import Fade
from ymdantic.models.tracks.derived_colors import DerivedColors
from ymdantic.models.tracks.album import TrackAlbum
from ymdantic.models.tracks.lyrics_info import LyricsInfo
from ymdantic.models.tracks.major import Major
from ymdantic.models.tracks.download_info import DownloadInfo, DownloadInfoDirect | 5,019 | og_image: Optional[str] = None
# OG изображение трека (если есть). OG изображение - это изображение,
# которое отображается при публикации ссылки на трек.
derived_colors: Optional[DerivedColors] = None
# Производные цвета трека (если есть). Производные цвета - это цвета,
# которые были получены из обложки трека.
clip_ids: Optional[List[int]] = None
# Идентификаторы клипов трека. Клип - это видео, которое относится к треку.
content_warning: Optional[str] = None
# Предупреждение о содержании трека (если есть).
is_suitable_for_children: Optional[bool] = None
# Подходит ли трек для детей (если есть).
background_video_uri: Optional[HttpUrl] = None
# URI фонового видео трека (если есть). Фоновое видео - это видео,
# которое отображается вместо обложки трека.
player_id: Optional[str] = None
# Идентификатор плеера трека (если есть). Плеер требуется для
# отображения фонового видео.
best: Optional[bool] = None
# Является ли трек лучшим (поле доступно при получении альбома с треками
# `get_album_with_tracks`).
@property
def artists_names(self) -> Optional[str]:
"""
Получает имена артистов трека.
:return: Имена артистов трека.
"""
if not self.artists:
return None
return ", ".join(artist.name for artist in self.artists)
def get_cover_image_url(self, size: str = "200x200") -> Optional[HttpUrl]:
"""
Получает URL изображения обложки.
:param size: Размер изображения обложки в пикселях.
По умолчанию 200x200.
:return: URL изображения обложки.
"""
if self.cover_uri is None:
return None
return HttpUrl(f"https://{self.cover_uri.replace('%%', size)}")
def get_og_image_url(self, size: str = "200x200") -> Optional[HttpUrl]:
"""
Получает URL изображения обложки.
:param size: Размер изображения обложки в пикселях.
По умолчанию 200x200.
:return: URL изображения обложки.
"""
if self.og_image is None:
return None
return HttpUrl(f"https://{self.og_image.replace('%%', size)}")
class UnavailableTrack(BaseTrack):
"""
Pydantic модель, представляющая недоступный трек.
В случае, если трек недоступен, то его нельзя скачать и прослушать.
Большинство полей, такие как: `storage_dir`, `available_for_options`,
`duration_ms`, `preview_duration_ms`, `file_size` и `lyrics_info` по
сути своей бесполезны для недоступных вида треков и зачастую
отсутствуют. Но по какой-то причине в некоторых треках они всё же есть.
"""
available: Literal[False]
# Доступность трека. В данном случае трек недоступен.
error: Optional[Literal["no-rights"]] = None
# Ошибка, связанная с треком. В данном случае может быть ошибка
# "no-rights", что означает отсутствие прав на трек.
title: Optional[str] = None
# Название трека. В данном случае название может отсутствовать
# (возникает очень редко).
track_sharing_flag: Optional[str] = None
# Флаг, указывающий на возможность делиться треком. В данном случае
# может отсутствовать (возникает очень редко).
storage_dir: Optional[str] = None
# Директория хранения трека. У недоступных треков почти всегда равна
# пустой строке или отсутствует.
available_for_options: Optional[AvailableForOptions] = None
# Доступные опции для трека. В данном случае опции могут отсутствовать.
duration_ms: Optional[int] = None
# Длительность трека в миллисекундах. В данном случае длительность может
# отсутствовать.
preview_duration_ms: Optional[int] = None
# Длительность предпросмотра трека в миллисекундах. В данном случае
# длительность предпросмотра может отсутствовать.
file_size: Optional[int] = None
# Размер файла трека. В данном случае размер файла может отсутствовать.
lyrics_info: Optional[LyricsInfo] = None
# Информация о тексте песни. В данном случае информация о тексте песни
# может отсутствовать.
class Track(BaseTrack):
available: Literal[True]
# Доступность трека. В данном случае трек доступен.
title: str
# Название трека.
track_sharing_flag: str
# Флаг, указывающий на возможность делиться треком.
storage_dir: str
# Директория хранения трека.
lyrics_info: LyricsInfo
# Информация о тексте песни.
duration_ms: int
# Длительность трека в миллисекундах.
preview_duration_ms: int
# Длительность предпросмотра трека в миллисекундах.
file_size: Literal[0]
# Размер файла трека. Всегда равен 0, видимо старая заглушка.
available_for_options: AvailableForOptions
# Доступные опции для трека.
chart: Optional[ChartPosition] = None
# Информация о чарте, если трек входит в чарт.
|
AvailableForOptions = List[Literal["bookmate"]]
TrackSource = Literal["OWN", "OWN_REPLACED_TO_UGC"]
class BaseTrack(YMBaseModel, DeprecatedMixin):
"""Pydantic модель, представляющая базовую информацию о любом треке."""
type: Literal["music", "asmr", "audiobook", "noise", "fairy-tale"]
# Тип трека.
id: str
# Идентификатор трека. Идентификатор трека - это уникальный
# идентификатор, по которому можно получить трек.
real_id: str
# Реальный идентификатор трека. Заглушка для замещенных треков.
available: bool
# Доступность трека. В данном случае трек недоступен. Это влияет на то,
# можно ли скачать и прослушать трек.
available_for_premium_users: bool
# Доступность трека для премиум пользователей.
available_full_without_permission: bool
# Полная доступность трека без разрешения.
disclaimers: List[Literal["modal"]]
# Список отказов от ответственности трека.
artists: List[Artist]
# Список артистов трека. Может быть пустым.
albums: List[TrackAlbum]
# Список альбомов трека. Может быть пустым.
lyrics_available: bool
# Доступность текста песни. Если текст песни доступен, то можно получить
# текст песни по данным из LyricsInfo.
remember_position: bool
# Запоминать ли позицию трека. В типе "music" зачастую равен False.
# В основном используется для подкастов, комментариев и аудиокниг.
track_source: TrackSource
# Источник трека
major: Optional[Major] = None
# Лейбл трека (если есть)
r128: Optional[R128] = None
# Значение R128 трека (если есть). R128 - это стандарт, который
# определяет уровень громкости аудио.
fade: Optional[Fade] = None
# Значение затухания трека (если есть). Затухание - это изменение
# громкости аудио на определенном участке.
cover_uri: Optional[str] = None
# URI обложки трека (если есть).
og_image: Optional[str] = None
# OG изображение трека (если есть). OG изображение - это изображение,
# которое отображается при публикации ссылки на трек.
derived_colors: Optional[DerivedColors] = None
# Производные цвета трека (если есть). Производные цвета - это цвета,
# которые были получены из обложки трека.
clip_ids: Optional[List[int]] = None
# Идентификаторы клипов трека. Клип - это видео, которое относится к треку.
content_warning: Optional[str] = None
# Предупреждение о содержании трека (если есть).
is_suitable_for_children: Optional[bool] = None
# Подходит ли трек для детей (если есть).
background_video_uri: Optional[HttpUrl] = None
# URI фонового видео трека (если есть). Фоновое видео - это видео,
# которое отображается вместо обложки трека.
player_id: Optional[str] = None
# Идентификатор плеера трека (если есть). Плеер требуется для
# отображения фонового видео.
best: Optional[bool] = None
# Является ли трек лучшим (поле доступно при получении альбома с треками
# `get_album_with_tracks`).
@property
def artists_names(self) -> Optional[str]:
"""
Получает имена артистов трека.
:return: Имена артистов трека.
"""
if not self.artists:
return None
return ", ".join(artist.name for artist in self.artists)
def get_cover_image_url(self, size: str = "200x200") -> Optional[HttpUrl]:
"""
Получает URL изображения обложки.
:param size: Размер изображения обложки в пикселях.
По умолчанию 200x200.
:return: URL изображения обложки.
"""
if self.cover_uri is None:
return None
return HttpUrl(f"https://{self.cover_uri.replace('%%', size)}")
def get_og_image_url(self, size: str = "200x200") -> Optional[HttpUrl]:
"""
Получает URL изображения обложки.
:param size: Размер изображения обложки в пикселях.
По умолчанию 200x200.
:return: URL изображения обложки.
"""
if self.og_image is None:
return None
return HttpUrl(f"https://{self.og_image.replace('%%', size)}")
class UnavailableTrack(BaseTrack):
"""
Pydantic модель, представляющая недоступный трек.
В случае, если трек недоступен, то его нельзя скачать и прослушать.
Большинство полей, такие как: `storage_dir`, `available_for_options`,
`duration_ms`, `preview_duration_ms`, `file_size` и `lyrics_info` по
сути своей бесполезны для недоступных вида треков и зачастую
отсутствуют. Но по какой-то причине в некоторых треках они всё же есть.
"""
available: Literal[False]
# Доступность трека. В данном случае трек недоступен.
error: Optional[Literal["no-rights"]] = None
# Ошибка, связанная с треком. В данном случае может быть ошибка
# "no-rights", что означает отсутствие прав на трек.
title: Optional[str] = None
# Название трека. В данном случае название может отсутствовать
# (возникает очень редко).
track_sharing_flag: Optional[str] = None
# Флаг, указывающий на возможность делиться треком. В данном случае
# может отсутствовать (возникает очень редко).
storage_dir: Optional[str] = None
# Директория хранения трека. У недоступных треков почти всегда равна
# пустой строке или отсутствует.
available_for_options: Optional[AvailableForOptions] = None
# Доступные опции для трека. В данном случае опции могут отсутствовать.
duration_ms: Optional[int] = None
# Длительность трека в миллисекундах. В данном случае длительность может
# отсутствовать.
preview_duration_ms: Optional[int] = None
# Длительность предпросмотра трека в миллисекундах. В данном случае
# длительность предпросмотра может отсутствовать.
file_size: Optional[int] = None
# Размер файла трека. В данном случае размер файла может отсутствовать.
lyrics_info: Optional[LyricsInfo] = None
# Информация о тексте песни. В данном случае информация о тексте песни
# может отсутствовать.
class Track(BaseTrack):
available: Literal[True]
# Доступность трека. В данном случае трек доступен.
title: str
# Название трека.
track_sharing_flag: str
# Флаг, указывающий на возможность делиться треком.
storage_dir: str
# Директория хранения трека.
lyrics_info: LyricsInfo
# Информация о тексте песни.
duration_ms: int
# Длительность трека в миллисекундах.
preview_duration_ms: int
# Длительность предпросмотра трека в миллисекундах.
file_size: Literal[0]
# Размер файла трека. Всегда равен 0, видимо старая заглушка.
available_for_options: AvailableForOptions
# Доступные опции для трека.
chart: Optional[ChartPosition] = None
# Информация о чарте, если трек входит в чарт.
| async def get_download_info(self) -> List[DownloadInfo]: | 10 | 2023-12-21 21:24:10+00:00 | 8k |
MMC-K/multimodal_understanding | text_generated_image_to_image_retriever/text_to_image_retrieval.py | [
{
"identifier": "FaissScorerExhaustiveGPU",
"path": "index_scorer.py",
"snippet": "class FaissScorerExhaustiveGPU(object):\n _NEED_TO_SET_CANDIDATES=False\n\n def __init__(self, \n fvec_root,\n nprobe=1,\n gpu=0,\n **kwargs,\n ) -> None:\n ... | import argparse
import sys
import os
import csv
import time
import json
import shutil
import logging
import hashlib
import functools
import numpy as np
import tqdm
import torch
import torch.nn.functional as F
import torch.distributed as dist
import torch.utils.data
import torch.utils.data.distributed
import torch.nn.parallel
from numpy.core.numeric import indices
from torch.utils.data import DataLoader
from torch.nn import CrossEntropyLoss
from torch import optim
from torch.nn.parallel import DistributedDataParallel as DDP
from transformers import AutoTokenizer, ViTFeatureExtractor
from torch.utils.tensorboard import SummaryWriter
from index_scorer import FaissScorerExhaustiveGPU, FaissScorerExhaustiveMultiGPU, FaissScorer
from data_utils import DatasetForImages
from modeling_encoder import (
VisionT5SimpleBiEncoder,
VisionT5MeanBiEncoder,
VisionT5SimpleBiEncoderHN,
VisionT5MeanBiEncoderHN,
)
from training_retriever import (
create_directory_info,
MODEL_CLS) | 4,376 | # See the License for the specific language governing permissions and
# limitations under the License.
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../")
logger = logging.getLogger(__name__)
faiss_scorer = None
image_tokenizer = None
text_tokenizer = None
model = None
ref_data = None
def retrieve_image_with_text(text_query_list, FVECS_DIR="result/simple_query_ko/fvecs", HF_PATH="result/simple_query_ko/hf_model", MARKDOWN_OUT="result/simple_query_ko/md"):
global faiss_scorer, image_tokenizer, model, ref_data
parser = argparse.ArgumentParser()
# data
parser.add_argument("--data_path",
default="cc12m_filtered.tsv", type=str)
# parser.add_argument("--query_path",
# default="query.json", type=str)
parser.add_argument("--fvecs_dir",
default=None, type=str)
parser.add_argument("--index_path",
default=None, type=str)
parser.add_argument("--index_str",
default="IVF65536,Flat", type=str)
parser.add_argument("--nprobe",
default=4, type=int)
# model
parser.add_argument("--vision_model",
default="google/vit-base-patch16-384", type=str)
parser.add_argument("--language_model",
default="KETI-AIR/ke-t5-base", type=str)
parser.add_argument("--model_cls", default="VisionT5MeanBiEncoder",
choices=["VisionT5SimpleBiEncoder",
"VisionT5MeanBiEncoder"],
type=str, help="model class")
parser.add_argument("--dir_suffix",
default=None, type=str)
parser.add_argument("--output_dir",
default="output", type=str)
parser.add_argument("--markdown_out",
default="md", type=str)
# resume
parser.add_argument("--hf_path", default=None, type=str,
help="path to score huggingface model")
parser.add_argument("--topk", default=10,
type=int, help="top k")
parser.add_argument("--image_size", default=180,
type=int, help="image size for html formatting")
# default settings for training, evaluation
parser.add_argument("--batch_size", default=16,
type=int, help="mini batch size")
parser.add_argument("--num_workers", default=0, type=int,
help="number of workers")
# distributed setting
parser.add_argument("--local_rank", type=int, default=-1,
help="local_rank for distributed training on gpus")
parser.add_argument("--local_world_size", type=int, default=1,
help="The size of the local worker group.")
parser.add_argument("--rank", type=int, default=0,
help="The rank of the worker within a worker group.")
parser.add_argument("--world_size", type=int, default=1,
help="world size. (num_nodes*num_dev_per_node)")
parser.add_argument("--distributed", action='store_true',
help="is distributed training")
parser.add_argument('--model_gpu',
default=0, type=int)
parser.add_argument('--scorer_gpus', nargs="+",
default=[0, 1, 2, 3], type=int)
# --data_path ../kfashion_images_group.tsv --fvecs_dir result/simple_query_ko/fvecs --hf_path result/simple_query_ko/hf_model --query_path query.json --markdown_out result/simple_query_ko/md --model_cls VisionT5MeanBiEncoder
args = parser.parse_args(["--data_path", "../kfashion_images_group.tsv",\
"--fvecs_dir", FVECS_DIR, \
"--hf_path", HF_PATH,\
"--markdown_out", MARKDOWN_OUT,\
"--model_cls", "VisionT5MeanBiEncoder",\
"--scorer_gpus", "0"])
print(args.scorer_gpus)
print(args.fvecs_dir)
path_info = create_directory_info(args, create_dir=False)
if args.fvecs_dir is None:
args.fvecs_dir = os.path.join(path_info["model_dir"], "fvecs")
if args.hf_path.lower()=='default':
args.hf_path = os.path.join(path_info["model_dir"], "hf")
model_device = torch.device('cuda:{}'.format(args.model_gpu))
if faiss_scorer is None:
faiss_scorer = FaissScorerExhaustiveMultiGPU(
fvec_root=args.fvecs_dir,
gpu_list=args.scorer_gpus
)
# get model class
| # Copyright 2022 san kim
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../")
logger = logging.getLogger(__name__)
faiss_scorer = None
image_tokenizer = None
text_tokenizer = None
model = None
ref_data = None
def retrieve_image_with_text(text_query_list, FVECS_DIR="result/simple_query_ko/fvecs", HF_PATH="result/simple_query_ko/hf_model", MARKDOWN_OUT="result/simple_query_ko/md"):
global faiss_scorer, image_tokenizer, model, ref_data
parser = argparse.ArgumentParser()
# data
parser.add_argument("--data_path",
default="cc12m_filtered.tsv", type=str)
# parser.add_argument("--query_path",
# default="query.json", type=str)
parser.add_argument("--fvecs_dir",
default=None, type=str)
parser.add_argument("--index_path",
default=None, type=str)
parser.add_argument("--index_str",
default="IVF65536,Flat", type=str)
parser.add_argument("--nprobe",
default=4, type=int)
# model
parser.add_argument("--vision_model",
default="google/vit-base-patch16-384", type=str)
parser.add_argument("--language_model",
default="KETI-AIR/ke-t5-base", type=str)
parser.add_argument("--model_cls", default="VisionT5MeanBiEncoder",
choices=["VisionT5SimpleBiEncoder",
"VisionT5MeanBiEncoder"],
type=str, help="model class")
parser.add_argument("--dir_suffix",
default=None, type=str)
parser.add_argument("--output_dir",
default="output", type=str)
parser.add_argument("--markdown_out",
default="md", type=str)
# resume
parser.add_argument("--hf_path", default=None, type=str,
help="path to score huggingface model")
parser.add_argument("--topk", default=10,
type=int, help="top k")
parser.add_argument("--image_size", default=180,
type=int, help="image size for html formatting")
# default settings for training, evaluation
parser.add_argument("--batch_size", default=16,
type=int, help="mini batch size")
parser.add_argument("--num_workers", default=0, type=int,
help="number of workers")
# distributed setting
parser.add_argument("--local_rank", type=int, default=-1,
help="local_rank for distributed training on gpus")
parser.add_argument("--local_world_size", type=int, default=1,
help="The size of the local worker group.")
parser.add_argument("--rank", type=int, default=0,
help="The rank of the worker within a worker group.")
parser.add_argument("--world_size", type=int, default=1,
help="world size. (num_nodes*num_dev_per_node)")
parser.add_argument("--distributed", action='store_true',
help="is distributed training")
parser.add_argument('--model_gpu',
default=0, type=int)
parser.add_argument('--scorer_gpus', nargs="+",
default=[0, 1, 2, 3], type=int)
# --data_path ../kfashion_images_group.tsv --fvecs_dir result/simple_query_ko/fvecs --hf_path result/simple_query_ko/hf_model --query_path query.json --markdown_out result/simple_query_ko/md --model_cls VisionT5MeanBiEncoder
args = parser.parse_args(["--data_path", "../kfashion_images_group.tsv",\
"--fvecs_dir", FVECS_DIR, \
"--hf_path", HF_PATH,\
"--markdown_out", MARKDOWN_OUT,\
"--model_cls", "VisionT5MeanBiEncoder",\
"--scorer_gpus", "0"])
print(args.scorer_gpus)
print(args.fvecs_dir)
path_info = create_directory_info(args, create_dir=False)
if args.fvecs_dir is None:
args.fvecs_dir = os.path.join(path_info["model_dir"], "fvecs")
if args.hf_path.lower()=='default':
args.hf_path = os.path.join(path_info["model_dir"], "hf")
model_device = torch.device('cuda:{}'.format(args.model_gpu))
if faiss_scorer is None:
faiss_scorer = FaissScorerExhaustiveMultiGPU(
fvec_root=args.fvecs_dir,
gpu_list=args.scorer_gpus
)
# get model class | model_cls_cfg = MODEL_CLS[args.model_cls] | 9 | 2023-12-18 10:37:51+00:00 | 8k |
CASIA-IVA-Lab/FLAP | lib/prune.py | [
{
"identifier": "WrappedGPT",
"path": "lib/layerwrapper.py",
"snippet": "class WrappedGPT:\n \"\"\"\n This class wraps a GPT layer for specific operations.\n \"\"\"\n\n def __init__(self, layer, layer_id=0, layer_name=\"none\"):\n self.layer = layer\n self.dev = self.layer.weig... | import torch
import torch.nn as nn
import math
from .layerwrapper import WrappedGPT, BiasGPT
from .data import get_loaders
from tqdm import tqdm | 4,665 | for name in wrapped_layers:
handles.append(subset[name].register_forward_hook(add_batch(name)))
for j in range(args.nsamples):
with torch.no_grad():
outs[j] = layer(inps[j].unsqueeze(0), attention_mask=attention_mask, position_ids=position_ids)[0]
for h in handles:
h.remove()
for name in subset:
if name == 'self_attn.o_proj':
W_metric = metrics[args.metrics](wrapped_layers, subset, name) ** 2
if args.structure == "UL-UM":
W_metric = W_metric.reshape(-1, 128).sum(dim=1)
thresh = torch.sort(W_metric.cuda())[0][int(args.pruning_ratio*layer.self_attn.num_heads)].cpu()
W_mask = (W_metric>=thresh)
attn_mask.append(W_mask)
elif args.structure == "UL-MM":
W_metric = W_metric.reshape(-1, 128).sum(dim=1)
thresh = torch.sort(W_metric.cuda())[0][args.remove_heads // len(layers)].cpu()
W_mask = (W_metric>=thresh)
attn_mask.append(W_mask)
else:
attn_metric_list.append(W_metric.cpu())
attn_baseline_inp_list.append(wrapped_layers[name].baseline_inp.type(torch.half))
else:
W_metric = metrics[args.metrics](wrapped_layers, subset, name)
if args.structure == "UL-UM":
thresh = torch.sort(W_metric.cuda())[0][int(W_metric.numel()*args.pruning_ratio)].cpu()
W_mask = (W_metric>=thresh)
mlp_mask.append(W_mask)
elif args.structure == "UL-MM":
thresh = torch.sort(W_metric.cuda())[0][cal_remove_neuron(args, model)].cpu()
W_mask = (W_metric>=thresh)
mlp_mask.append(W_mask)
else:
mlp_metric_list.append(W_metric.cpu())
mlp_baseline_inp_list.append(wrapped_layers[name].baseline_inp.type(torch.half))
wrapped_layers[name].free()
inps, outs = outs, inps # Use the original output as input to the next layer
torch.cuda.empty_cache()
standarlization = lambda x: (x - torch.mean(x, axis=1, keepdim=True)) / torch.std(x, axis=1, keepdim=True)
if args.structure in ["AL-MM", "AL-AM"]:
attn_metric = torch.stack(attn_metric_list)
attn_metric = standarlization(attn_metric)
attn_metric = attn_metric.reshape(len(layers), -1, 128).mean(dim=2)
mlp_metric = torch.stack(mlp_metric_list)
mlp_metric = standarlization(mlp_metric)
if args.structure == "AL-MM":
sorted_attn = torch.sort(attn_metric.view(-1), descending=True)[0]
attn_thres = sorted_attn[-int(args.remove_heads)]
attn_mask = (attn_metric > attn_thres) # 1 means retain
sorted_mlp = torch.sort(mlp_metric.view(-1), descending=True)[0]
mlp_thres = sorted_mlp[-cal_remove_neuron(args, model)]
mlp_mask = (mlp_metric > mlp_thres)
else:
prune_metric = torch.cat([attn_metric.view(-1), mlp_metric.view(-1)])
sorted_prune, indices = torch.sort(prune_metric, descending=True)
compression_weight = torch.ones_like(indices)
compression_weight[indices < attn_metric.numel()] = 512.0 / 3
threshold = sorted_prune[torch.argmin(torch.abs(torch.cumsum(compression_weight, 0) - torch.sum(compression_weight)*(1 - args.pruning_ratio)))]
attn_mask = (attn_metric > threshold)
mlp_mask = (mlp_metric > threshold)
else:
attn_mask = torch.stack(attn_mask)
mlp_mask = torch.stack(mlp_mask)
for idx in range(len(layers)):
if f"model.layers.{i}" in getattr(model, 'hf_device_map', {}):
compress(model.model.layers[idx], attn_mask[idx], None, attn_baseline_inp_list[idx], None, model.hf_device_map[f"model.layers.{idx}"], unstr=args.unstr)
else:
compress(model.model.layers[idx], attn_mask[idx], None, attn_baseline_inp_list[idx], None, device, unstr=args.unstr)
if f"model.layers.{i}" in getattr(model, 'hf_device_map', {}):
compress(model.model.layers[idx], None, mlp_mask[idx], None, mlp_baseline_inp_list[idx], model.hf_device_map[f"model.layers.{idx}"], unstr=args.unstr)
else:
compress(model.model.layers[idx], None, mlp_mask[idx], None, mlp_baseline_inp_list[idx], device, unstr=args.unstr)
model.config.use_cache = use_cache
torch.cuda.empty_cache()
def prune_wanda_sp(args, model, tokenizer, device=torch.device("cuda:0")):
"""
Wanda on structured pruning.
Args:
args (object): Command line arguments parsed via argparse.
model (nn.Module): PyTorch model to prune.
tokenizer (Tokenizer): Tokenizer associated with the model.
device (torch.device, optional): Device to move tensors to. Defaults to CUDA device 0.
"""
use_cache = model.config.use_cache
model.config.use_cache = False
print("loading calibdation data")
dataloader, _ = get_loaders("c4",nsamples=128,seed=args.seed,seqlen=model.seqlen,tokenizer=tokenizer)
print("dataset loading complete")
with torch.no_grad():
inps, outs, attention_mask, position_ids = prepare_calibration_input(model, dataloader, device)
layers = model.model.layers
for i in range(len(layers)):
layer = layers[i]
subset = {}
subset.update({'self_attn.o_proj': find_layers(layer)['self_attn.o_proj']})
subset.update({'mlp.down_proj': find_layers(layer)['mlp.down_proj']})
if f"model.layers.{i}" in getattr(model, 'hf_device_map', {}): ## handle the case for llama-30B and llama-65B, when the device map has multiple GPUs;
dev = model.hf_device_map[f"model.layers.{i}"]
inps, outs, attention_mask, position_ids = inps.to(dev), outs.to(dev), attention_mask.to(dev), position_ids.to(dev)
wrapped_layers = {}
for name in subset:
|
# create a dictionary to map the method name to the function
"""
'IFV': Input Feature Variance
'WIFV': Weighted Input Feature Variance
'WIFN': Weighted Input Feature Norm
"""
metrics = {
'IFV': lambda wrapped_layers, subset, name: wrapped_layers[name].fluc_inp,
'WIFV': lambda wrapped_layers, subset, name: wrapped_layers[name].fluc_inp * torch.sum(subset[name].weight.data.pow(2), dim=0),
'WIFN': lambda wrapped_layers, subset, name: (torch.abs(subset[name].weight.data) * torch.sqrt(wrapped_layers[name].scaler_inp.reshape((1,-1)))).mean(axis=0),
}
def find_layers(module, layers=[nn.Linear], name=''):
"""
Recursively find the layers of a certain type in a module.
Args:
module (nn.Module): PyTorch module.
layers (list): List of layer types to find.
name (str): Name of the module.
Returns:
dict: Dictionary of layers of the given type(s) within the module.
"""
if type(module) in layers:
return {name: module}
res = {}
for name1, child in module.named_children():
res.update(find_layers(
child, layers=layers, name=name + '.' + name1 if name != '' else name1
))
return res
def check_sparsity(model):
"""
Check the sparsity of the weights in different layers of the model.
Args:
model (nn.Module): The model to check.
Returns:
float: Ratio of the count of non-zero weights to total parameters in the model.
"""
use_cache = model.config.use_cache
model.config.use_cache = False
layers = model.model.layers
intermediate_size = model.config.intermediate_size
hidden_size = model.config.hidden_size
count = 0
total_params = 0
for i in range(len(layers)):
layer = layers[i]
subset = find_layers(layer)
sub_count = 0
sub_params = 0
for name in subset:
W = subset[name].weight.data
sub_count += W.numel()
count += W.numel()
if 'self_attn' in name:
total_params += hidden_size * hidden_size
sub_params += hidden_size * hidden_size
else:
total_params += hidden_size * intermediate_size
sub_params += hidden_size * intermediate_size
if subset[name].bias is not None:
count += subset[name].bias.data.numel()
sub_count += subset[name].bias.data.numel()
print(f"layer {i} sparsity {float(sub_count)/sub_params:.6f}")
model.config.use_cache = use_cache
return float(count)/total_params
def prepare_calibration_input(model, dataloader, device):
"""
Prepare inputs for model calibration.
Args:
model (nn.Module): The model to prepare inputs for.
dataloader (DataLoader): DataLoader object to fetch input data.
device (torch.device): Device on which the model is loaded.
Returns:
inps (torch.Tensor): Input tensor for calibration.
outs (torch.Tensor): Output tensor for calibration.
attention_mask (torch.Tensor): Attention mask tensor.
position_ids (torch.Tensor): Position IDs tensor.
"""
use_cache = model.config.use_cache
model.config.use_cache = False
layers = model.model.layers
if "model.embed_tokens" in getattr(model, 'hf_device_map', {}):
device = model.hf_device_map["model.embed_tokens"]
dtype = next(iter(model.parameters())).dtype
inps = torch.zeros((2048, model.seqlen, model.config.hidden_size), dtype=dtype, device=device)
inps.requires_grad = False
cache = {'i': 0, 'attention_mask': None, "position_ids": None}
class Catcher(nn.Module):
def __init__(self, module):
super().__init__()
self.module = module
def forward(self, inp, **kwargs):
inps[cache['i']] = inp
cache['i'] += 1
cache['attention_mask'] = kwargs['attention_mask']
cache['position_ids'] = kwargs['position_ids']
raise ValueError
layers[0] = Catcher(layers[0])
for batch in dataloader:
try:
model(batch[0].to(device))
except ValueError:
pass
layers[0] = layers[0].module
outs = torch.zeros_like(inps)
attention_mask = cache['attention_mask']
position_ids = cache['position_ids']
model.config.use_cache = use_cache
return inps, outs, attention_mask, position_ids
def compress(layer, attn_mask, mlp_mask, attn_mean_inp, mlp_mean_inp, device, bias=True, unstr=False):
"""
Compress a model layer by masking or pruning based on the given masks.
Args:
layer (nn.Module): The model layer to compress.
attn_mask (torch.Tensor): The mask to apply to the attention weights.
mlp_mask (torch.Tensor): The mask to apply to the MLP weights.
attn_mean_inp (torch.Tensor): The mean attention input.
mlp_mean_inp (torch.Tensor): The mean MLP input.
device (torch.device): Device on which the model is loaded.
bias (bool, optional): Whether to consider bias while compressing. Defaults to True.
unstr (bool, optional): If True, only mask without real pruning. Defaults to False.
Returns:
None: This function modifies the layer in-place and doesn't return anything.
"""
if unstr: # Only mask, do not really prune
# Attention Weight Masking
if attn_mask is not None:
retain_heads = torch.count_nonzero(attn_mask)
attn_mask = attn_mask.repeat_interleave(128)
# Apply the mask to the query, key and value projection weights
layer.self_attn.q_proj.weight.data *= attn_mask.unsqueeze(-1).to(device)
layer.self_attn.k_proj.weight.data *= attn_mask.unsqueeze(-1).to(device)
layer.self_attn.v_proj.weight.data *= attn_mask.unsqueeze(-1).to(device)
output_weight = layer.self_attn.o_proj.weight.data
if bias:
# Add the additional bias to compensate for the loss
output_bias = ((attn_mean_inp * ~attn_mask.to(device)) @ output_weight.T)
# Note: the weight data is masked, but the weight tensor shape remains unchanged
if bias:
layer.self_attn.o_proj.bias.data = output_bias
layer.self_attn.o_proj.weight.data = output_weight
# MLP Weight Masking
if mlp_mask is not None:
# Apply the mask to the up and gate projection weights
layer.mlp.up_proj.weight.data *= mlp_mask.unsqueeze(-1).to(device)
layer.mlp.gate_proj.weight.data *= mlp_mask.unsqueeze(-1).to(device)
output_weight = layer.mlp.down_proj.weight.data
if bias:
# Add the additional bias to compensate for the loss
output_bias = ((mlp_mean_inp * ~mlp_mask.to(device)) @ output_weight.T)
# Note: the weight data is masked, but the weight tensor shape remains unchanged
if bias:
layer.mlp.down_proj.bias.data = output_bias
layer.mlp.down_proj.weight.data = output_weight
else:
# Real Pruning
# Attention Weight Pruning
if attn_mask is not None:
retain_heads = torch.count_nonzero(attn_mask)
attn_mask = attn_mask.repeat_interleave(128)
# Prune the query, key and value projection weights
# We reduce the size of the weights based on the attention mask
layer.self_attn.q_proj.weight.data = layer.self_attn.q_proj.weight.data[torch.where(attn_mask)[0]]
layer.self_attn.k_proj.weight.data = layer.self_attn.k_proj.weight.data[torch.where(attn_mask)[0]]
layer.self_attn.v_proj.weight.data = layer.self_attn.v_proj.weight.data[torch.where(attn_mask)[0]]
# Update output dimensions of q, k, v projections based on remaining heads
layer.self_attn.q_proj.out_features = attn_mask.sum().item()
layer.self_attn.k_proj.out_features = attn_mask.sum().item()
layer.self_attn.v_proj.out_features = attn_mask.sum().item()
output_weight = layer.self_attn.o_proj.weight.data
if bias:
# Add the additional bias to compensate for the loss
output_bias = ((attn_mean_inp * ~attn_mask.to(device)) @ output_weight.T)
# Prune the output projection weight
output_weight = layer.self_attn.o_proj.weight.data[:, torch.where(attn_mask)[0]]
# Update layer configurations for the new output shape after pruning
layer.self_attn.num_heads = retain_heads
layer.self_attn.hidden_size = retain_heads * 128
if bias:
# Re-initialize the Linear layer with new shape and bias
layer.self_attn.o_proj.in_features = attn_mask.sum().item()
# layer.self_attn.o_proj = torch.nn.Linear(in_features=output_weight.shape[1], out_features=output_weight.shape[0], bias=True).to(device)
layer.self_attn.o_proj.bias.data = output_bias
# Assign the pruned weights
layer.self_attn.o_proj.weight.data = output_weight
# MLP Weight Pruning
if mlp_mask is not None:
# Prune the up and gate projection weights
layer.mlp.up_proj.weight.data = layer.mlp.up_proj.weight.data[torch.where(mlp_mask)[0]]
layer.mlp.gate_proj.weight.data = layer.mlp.gate_proj.weight.data[torch.where(mlp_mask)[0]]
# Update output dimensions of up and gate projections based on the mlp mask
layer.mlp.up_proj.out_features = mlp_mask.sum().item()
layer.mlp.gate_proj.out_features = mlp_mask.sum().item()
output_weight = layer.mlp.down_proj.weight.data
layer.mlp.intermediate_size = mlp_mask.sum().item()
if bias:
# Add the additional bias to compensate for the loss
output_bias = ((mlp_mean_inp * ~mlp_mask.to(device)) @ output_weight.T)
# Prune the down projection weight
output_weight = layer.mlp.down_proj.weight.data[:, torch.where(mlp_mask)[0]]
if bias:
# Re-initialize the Linear layer with new shape and bias
layer.mlp.down_proj.in_features = mlp_mask.sum().item()
# layer.mlp.down_proj = torch.nn.Linear(in_features=output_weight.shape[1], out_features=output_weight.shape[0], bias=True).to(device)
layer.mlp.down_proj.bias.data = output_bias
# Assign the pruned weights
layer.mlp.down_proj.weight.data = output_weight
# Explicitly empty the CUDA cache to clean up some memory
torch.cuda.empty_cache()
def cal_remove_neuron(args, model):
intermediate_size = model.config.intermediate_size
hidden_size = model.config.hidden_size
num_layers = model.config.num_hidden_layers
if args.structure == "UL-MM":
remove_params = args.pruning_ratio * (intermediate_size * hidden_size * 3 + hidden_size * hidden_size * 4)
remove_head_params = hidden_size * 4 * (args.remove_heads // num_layers) * 128
return int((remove_params - remove_head_params) / (hidden_size * 3))
else:
remove_params = num_layers * args.pruning_ratio * (intermediate_size * hidden_size * 3 + hidden_size * hidden_size * 4)
remove_head_params = hidden_size * 4 * args.remove_heads * 128
return int((remove_params - remove_head_params) / (hidden_size * 3))
def prune_flap(args, model, tokenizer, device=torch.device("cuda:0")):
"""
Our FLAP Pruning.
Args:
args (object): Command line arguments parsed via argparse.
model (nn.Module): PyTorch model to prune.
tokenizer (Tokenizer): Tokenizer associated with the model.
device (torch.device, optional): Device to move tensors to. Defaults to CUDA device 0.
"""
use_cache = model.config.use_cache
model.config.use_cache = False
print("loading calibdation data")
dataloader, _ = get_loaders("wikitext2", nsamples=args.nsamples,seed=args.seed,seqlen=model.seqlen,tokenizer=tokenizer)
print("dataset loading complete")
with torch.no_grad():
inps, outs, attention_mask, position_ids = prepare_calibration_input(model, dataloader, device)
layers = model.model.layers
attn_metric_list, mlp_metric_list = [], []
attn_baseline_inp_list, mlp_baseline_inp_list = [], []
attn_mask, mlp_mask = [], []
# Split into sub-problems, separate statistics for each module
for i in tqdm(range(len(layers)), desc="Processing layers"):
layer = layers[i]
subset = {}
subset.update({'self_attn.o_proj': find_layers(layer)['self_attn.o_proj']})
subset.update({'mlp.down_proj': find_layers(layer)['mlp.down_proj']})
if f"model.layers.{i}" in getattr(model, 'hf_device_map', {}): ## handle the case for llama-30B and llama-65B, when the device map has multiple GPUs;
dev = model.hf_device_map[f"model.layers.{i}"]
inps, outs, attention_mask, position_ids = inps.to(dev), outs.to(dev), attention_mask.to(dev), position_ids.to(dev)
wrapped_layers = {}
for name in subset:
wrapped_layers[name] = BiasGPT(subset[name], args.metrics)
def add_batch(name):
def tmp(_, inp, out):
wrapped_layers[name].add_batch(inp[0].data, out.data)
return tmp
handles = []
for name in wrapped_layers:
handles.append(subset[name].register_forward_hook(add_batch(name)))
for j in range(args.nsamples):
with torch.no_grad():
outs[j] = layer(inps[j].unsqueeze(0), attention_mask=attention_mask, position_ids=position_ids)[0]
for h in handles:
h.remove()
for name in subset:
if name == 'self_attn.o_proj':
W_metric = metrics[args.metrics](wrapped_layers, subset, name) ** 2
if args.structure == "UL-UM":
W_metric = W_metric.reshape(-1, 128).sum(dim=1)
thresh = torch.sort(W_metric.cuda())[0][int(args.pruning_ratio*layer.self_attn.num_heads)].cpu()
W_mask = (W_metric>=thresh)
attn_mask.append(W_mask)
elif args.structure == "UL-MM":
W_metric = W_metric.reshape(-1, 128).sum(dim=1)
thresh = torch.sort(W_metric.cuda())[0][args.remove_heads // len(layers)].cpu()
W_mask = (W_metric>=thresh)
attn_mask.append(W_mask)
else:
attn_metric_list.append(W_metric.cpu())
attn_baseline_inp_list.append(wrapped_layers[name].baseline_inp.type(torch.half))
else:
W_metric = metrics[args.metrics](wrapped_layers, subset, name)
if args.structure == "UL-UM":
thresh = torch.sort(W_metric.cuda())[0][int(W_metric.numel()*args.pruning_ratio)].cpu()
W_mask = (W_metric>=thresh)
mlp_mask.append(W_mask)
elif args.structure == "UL-MM":
thresh = torch.sort(W_metric.cuda())[0][cal_remove_neuron(args, model)].cpu()
W_mask = (W_metric>=thresh)
mlp_mask.append(W_mask)
else:
mlp_metric_list.append(W_metric.cpu())
mlp_baseline_inp_list.append(wrapped_layers[name].baseline_inp.type(torch.half))
wrapped_layers[name].free()
inps, outs = outs, inps # Use the original output as input to the next layer
torch.cuda.empty_cache()
standarlization = lambda x: (x - torch.mean(x, axis=1, keepdim=True)) / torch.std(x, axis=1, keepdim=True)
if args.structure in ["AL-MM", "AL-AM"]:
attn_metric = torch.stack(attn_metric_list)
attn_metric = standarlization(attn_metric)
attn_metric = attn_metric.reshape(len(layers), -1, 128).mean(dim=2)
mlp_metric = torch.stack(mlp_metric_list)
mlp_metric = standarlization(mlp_metric)
if args.structure == "AL-MM":
sorted_attn = torch.sort(attn_metric.view(-1), descending=True)[0]
attn_thres = sorted_attn[-int(args.remove_heads)]
attn_mask = (attn_metric > attn_thres) # 1 means retain
sorted_mlp = torch.sort(mlp_metric.view(-1), descending=True)[0]
mlp_thres = sorted_mlp[-cal_remove_neuron(args, model)]
mlp_mask = (mlp_metric > mlp_thres)
else:
prune_metric = torch.cat([attn_metric.view(-1), mlp_metric.view(-1)])
sorted_prune, indices = torch.sort(prune_metric, descending=True)
compression_weight = torch.ones_like(indices)
compression_weight[indices < attn_metric.numel()] = 512.0 / 3
threshold = sorted_prune[torch.argmin(torch.abs(torch.cumsum(compression_weight, 0) - torch.sum(compression_weight)*(1 - args.pruning_ratio)))]
attn_mask = (attn_metric > threshold)
mlp_mask = (mlp_metric > threshold)
else:
attn_mask = torch.stack(attn_mask)
mlp_mask = torch.stack(mlp_mask)
for idx in range(len(layers)):
if f"model.layers.{i}" in getattr(model, 'hf_device_map', {}):
compress(model.model.layers[idx], attn_mask[idx], None, attn_baseline_inp_list[idx], None, model.hf_device_map[f"model.layers.{idx}"], unstr=args.unstr)
else:
compress(model.model.layers[idx], attn_mask[idx], None, attn_baseline_inp_list[idx], None, device, unstr=args.unstr)
if f"model.layers.{i}" in getattr(model, 'hf_device_map', {}):
compress(model.model.layers[idx], None, mlp_mask[idx], None, mlp_baseline_inp_list[idx], model.hf_device_map[f"model.layers.{idx}"], unstr=args.unstr)
else:
compress(model.model.layers[idx], None, mlp_mask[idx], None, mlp_baseline_inp_list[idx], device, unstr=args.unstr)
model.config.use_cache = use_cache
torch.cuda.empty_cache()
def prune_wanda_sp(args, model, tokenizer, device=torch.device("cuda:0")):
"""
Wanda on structured pruning.
Args:
args (object): Command line arguments parsed via argparse.
model (nn.Module): PyTorch model to prune.
tokenizer (Tokenizer): Tokenizer associated with the model.
device (torch.device, optional): Device to move tensors to. Defaults to CUDA device 0.
"""
use_cache = model.config.use_cache
model.config.use_cache = False
print("loading calibdation data")
dataloader, _ = get_loaders("c4",nsamples=128,seed=args.seed,seqlen=model.seqlen,tokenizer=tokenizer)
print("dataset loading complete")
with torch.no_grad():
inps, outs, attention_mask, position_ids = prepare_calibration_input(model, dataloader, device)
layers = model.model.layers
for i in range(len(layers)):
layer = layers[i]
subset = {}
subset.update({'self_attn.o_proj': find_layers(layer)['self_attn.o_proj']})
subset.update({'mlp.down_proj': find_layers(layer)['mlp.down_proj']})
if f"model.layers.{i}" in getattr(model, 'hf_device_map', {}): ## handle the case for llama-30B and llama-65B, when the device map has multiple GPUs;
dev = model.hf_device_map[f"model.layers.{i}"]
inps, outs, attention_mask, position_ids = inps.to(dev), outs.to(dev), attention_mask.to(dev), position_ids.to(dev)
wrapped_layers = {}
for name in subset: | wrapped_layers[name] = WrappedGPT(subset[name]) | 0 | 2023-12-18 06:28:41+00:00 | 8k |
alibaba/u2mot | yolox/tracker/u2mot_tracker.py | [
{
"identifier": "BaseTrack",
"path": "yolox/tracker/basetrack.py",
"snippet": "class BaseTrack(object):\n _count = 0\n\n track_id = 0\n is_activated = False\n state = TrackState.New\n\n history = OrderedDict()\n features = []\n curr_feature = None\n score = 0\n start_frame = 0... | import numpy as np
from collections import deque
from .basetrack import BaseTrack, TrackState
from .kalman_filter import KalmanFilter
from .gmc import GMC
from . import matching | 5,956 | #!/usr/bin/env python3
# -*- encoding:utf-8 -*-
# Copyright (c) Alibaba, Inc. and its affiliates.
class STrack(BaseTrack):
shared_kalman = KalmanFilter()
def __init__(self, tlwh, score, cls=0, feat=None, feat_history=50):
# wait activate
self._tlwh = np.asarray(tlwh, dtype=np.float)
self.kalman_filter = None
self.mean, self.covariance = None, None
self.is_activated = False
self.cls = -1
self.cls_hist = [] # (cls id, freq)
self.update_cls(cls, score)
self.score = score
self.tracklet_len = 0
self.smooth_feat = None
self.curr_feat = None
self.features = deque([], maxlen=feat_history)
if feat is not None:
self.update_features(feat)
self.alpha = 0.9
def update_features(self, feat):
feat /= np.linalg.norm(feat)
self.curr_feat = feat
if self.smooth_feat is None:
self.smooth_feat = feat
else:
self.smooth_feat = self.alpha * self.smooth_feat + (1 - self.alpha) * feat
self.features.append(feat)
self.smooth_feat /= np.linalg.norm(self.smooth_feat)
def update_cls(self, cls, score):
if len(self.cls_hist) > 0:
max_freq = 0
found = False
for c in self.cls_hist:
if cls == c[0]:
c[1] += score
found = True
if c[1] > max_freq:
max_freq = c[1]
self.cls = c[0]
if not found:
self.cls_hist.append([cls, score])
self.cls = cls
else:
self.cls_hist.append([cls, score])
self.cls = cls
def predict(self):
mean_state = self.mean.copy()
| #!/usr/bin/env python3
# -*- encoding:utf-8 -*-
# Copyright (c) Alibaba, Inc. and its affiliates.
class STrack(BaseTrack):
shared_kalman = KalmanFilter()
def __init__(self, tlwh, score, cls=0, feat=None, feat_history=50):
# wait activate
self._tlwh = np.asarray(tlwh, dtype=np.float)
self.kalman_filter = None
self.mean, self.covariance = None, None
self.is_activated = False
self.cls = -1
self.cls_hist = [] # (cls id, freq)
self.update_cls(cls, score)
self.score = score
self.tracklet_len = 0
self.smooth_feat = None
self.curr_feat = None
self.features = deque([], maxlen=feat_history)
if feat is not None:
self.update_features(feat)
self.alpha = 0.9
def update_features(self, feat):
feat /= np.linalg.norm(feat)
self.curr_feat = feat
if self.smooth_feat is None:
self.smooth_feat = feat
else:
self.smooth_feat = self.alpha * self.smooth_feat + (1 - self.alpha) * feat
self.features.append(feat)
self.smooth_feat /= np.linalg.norm(self.smooth_feat)
def update_cls(self, cls, score):
if len(self.cls_hist) > 0:
max_freq = 0
found = False
for c in self.cls_hist:
if cls == c[0]:
c[1] += score
found = True
if c[1] > max_freq:
max_freq = c[1]
self.cls = c[0]
if not found:
self.cls_hist.append([cls, score])
self.cls = cls
else:
self.cls_hist.append([cls, score])
self.cls = cls
def predict(self):
mean_state = self.mean.copy() | if self.state != TrackState.Tracked: | 1 | 2023-12-18 10:04:40+00:00 | 8k |
liuhuang31/HiFTNet-sr | train.py | [
{
"identifier": "AttrDict",
"path": "env.py",
"snippet": "class AttrDict(dict):\n def __init__(self, *args, **kwargs):\n super(AttrDict, self).__init__(*args, **kwargs)\n self.__dict__ = self"
},
{
"identifier": "build_env",
"path": "env.py",
"snippet": "def build_env(co... | import warnings
import itertools
import os
import time
import argparse
import json
import torch
import torch.nn.functional as F
import torch.multiprocessing as mp
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DistributedSampler, DataLoader
from torch.distributed import init_process_group
from torch.nn.parallel import DistributedDataParallel
from env import AttrDict, build_env
from meldataset import MelDataset, mel_spectrogram, get_dataset_filelist
from models import Generator, MultiPeriodDiscriminator, MultiResSpecDiscriminator, feature_loss, generator_loss,\
discriminator_loss, discriminator_TPRLS_loss, generator_TPRLS_loss
from utils import plot_spectrogram, scan_checkpoint, load_checkpoint, save_checkpoint
from stft import TorchSTFT
from Utils.JDC.model import JDCNet | 7,127 | warnings.simplefilter(action='ignore', category=FutureWarning)
torch.backends.cudnn.benchmark = True
def train(rank, a, h):
if h.num_gpus > 1:
init_process_group(backend=h.dist_config['dist_backend'], init_method=h.dist_config['dist_url'],
world_size=h.dist_config['world_size'] * h.num_gpus, rank=rank)
torch.cuda.manual_seed(h.seed)
device = torch.device('cuda:{:d}'.format(rank))
F0_model = JDCNet(num_class=1, seq_len=192)
params = torch.load(h.F0_path)['model']
F0_model.load_state_dict(params)
generator = Generator(h, F0_model).to(device)
mpd = MultiPeriodDiscriminator().to(device)
msd = MultiResSpecDiscriminator().to(device)
stft = TorchSTFT(filter_length=h.gen_istft_n_fft, hop_length=h.gen_istft_hop_size, win_length=h.gen_istft_n_fft).to(device)
if rank == 0:
print(generator)
os.makedirs(a.checkpoint_path, exist_ok=True)
print("checkpoints directory : ", a.checkpoint_path)
if os.path.isdir(a.checkpoint_path):
cp_g = scan_checkpoint(a.checkpoint_path, 'g_')
cp_do = scan_checkpoint(a.checkpoint_path, 'do_')
steps = 0
if cp_g is None or cp_do is None:
state_dict_do = None
last_epoch = -1
else:
| warnings.simplefilter(action='ignore', category=FutureWarning)
torch.backends.cudnn.benchmark = True
def train(rank, a, h):
if h.num_gpus > 1:
init_process_group(backend=h.dist_config['dist_backend'], init_method=h.dist_config['dist_url'],
world_size=h.dist_config['world_size'] * h.num_gpus, rank=rank)
torch.cuda.manual_seed(h.seed)
device = torch.device('cuda:{:d}'.format(rank))
F0_model = JDCNet(num_class=1, seq_len=192)
params = torch.load(h.F0_path)['model']
F0_model.load_state_dict(params)
generator = Generator(h, F0_model).to(device)
mpd = MultiPeriodDiscriminator().to(device)
msd = MultiResSpecDiscriminator().to(device)
stft = TorchSTFT(filter_length=h.gen_istft_n_fft, hop_length=h.gen_istft_hop_size, win_length=h.gen_istft_n_fft).to(device)
if rank == 0:
print(generator)
os.makedirs(a.checkpoint_path, exist_ok=True)
print("checkpoints directory : ", a.checkpoint_path)
if os.path.isdir(a.checkpoint_path):
cp_g = scan_checkpoint(a.checkpoint_path, 'g_')
cp_do = scan_checkpoint(a.checkpoint_path, 'do_')
steps = 0
if cp_g is None or cp_do is None:
state_dict_do = None
last_epoch = -1
else: | state_dict_g = load_checkpoint(cp_g, device) | 15 | 2023-12-16 03:53:55+00:00 | 8k |
m-abr/FCPCodebase | scripts/utils/Dribble.py | [
{
"identifier": "Agent",
"path": "agent/Agent.py",
"snippet": "class Agent(Base_Agent):\n def __init__(self, host:str, agent_port:int, monitor_port:int, unum:int,\n team_name:str, enable_log, enable_draw, wait_for_server=True, is_fat_proxy=False) -> None:\n \n # define r... | from agent.Agent import Agent
from agent.Base_Agent import Base_Agent
from scripts.commons.Script import Script
import numpy as np | 7,156 |
'''
Objective:
----------
Dribble and score
'''
class Dribble():
def __init__(self, script:Script) -> None:
self.script = script
def execute(self):
a = self.script.args
# Args: Server IP, Agent Port, Monitor Port, Uniform No., [Robot Type] (for Base_Agent), Team name, Enable Log, Enable Draw
|
'''
Objective:
----------
Dribble and score
'''
class Dribble():
def __init__(self, script:Script) -> None:
self.script = script
def execute(self):
a = self.script.args
# Args: Server IP, Agent Port, Monitor Port, Uniform No., [Robot Type] (for Base_Agent), Team name, Enable Log, Enable Draw | self.script.batch_create(Base_Agent, ((a.i,a.p,a.m,a.u,a.r,a.t,True,True),)) # one dribbler | 1 | 2023-12-16 23:40:23+00:00 | 8k |
koenhendriks/ha-button-plus | custom_components/button_plus/config_flow.py | [
{
"identifier": "ApiClient",
"path": "custom_components/button_plus/button_plus_api/api_client.py",
"snippet": "class ApiClient:\n \"\"\" Client to talk to Button+ website \"\"\"\n\n def __init__(self, session, cookie=None) -> None:\n _LOGGER.debug(f\"DEBUG CONFIG {cookie}\")\n self.... | import ipaddress
import json
import logging
import traceback
import voluptuous as vol
from json import JSONDecodeError
from homeassistant import config_entries, exceptions
from homeassistant.const import CONF_IP_ADDRESS, CONF_EMAIL, CONF_PASSWORD, CONF_HOST
from homeassistant.helpers import aiohttp_client
from .button_plus_api.api_client import ApiClient
from .button_plus_api.local_api_client import LocalApiClient
from .button_plus_api.model import DeviceConfiguration, MqttBroker
from .button_plus_api.event_type import EventType
from homeassistant.helpers.network import get_url
from .const import DOMAIN # pylint:disable=unused-import | 4,125 | )
async def async_step_fetch_website(self, user_input=None):
"""Handle fetching the Button+ devices from the website."""
errors = {}
_LOGGER.debug(f"Fetch website step {user_input}")
if user_input is not None:
try:
api_client = await self.setup_api_client(user_input)
valid = await api_client.test_connection()
if valid:
json_response = await api_client.fetch_configs()
devices = json.loads(json_response)
last_entry = None
total_devices = len(devices)
_LOGGER.info(f"Found {total_devices} devices from Button+ website")
for device in devices:
device_website_id = device.get("Id")
device_ip = device.get('IpAddress')
if not device_ip:
_LOGGER.warning(f"Skipping device {device_website_id}, it has no IP so must be virtual")
continue
_LOGGER.debug(f"loaded device from website with id: {device_website_id} and ip {device_ip}")
device_config = json.loads(device.get("Json"))
device_name = device_config.get('core').get('name')
device_id = device_config.get('info').get('id')
last_entry = self.async_create_entry(
title=f"{device_name}",
description=f"Base module on {device_ip} with local id {device_id} and website id {device_website_id}",
data=device_config
)
return last_entry
except JSONDecodeError as ex: # pylint: disable=broad-except
_LOGGER.error(
f"{DOMAIN} Could not parse json from Button+ website : %s - traceback: %s",
ex,
traceback.format_exc()
)
errors["base"] = "Error connecting or reading from https://api.button.plus/"
except Exception as ex: # pylint: disable=broad-except
_LOGGER.error(
f"{DOMAIN} Exception in login : %s - traceback: %s",
ex,
traceback.format_exc()
)
errors["base"] = "cannot_connect"
if "base" not in errors:
errors["base"] = "cannot_connect"
return self.async_show_form(
step_id="fetch_website",
data_schema=vol.Schema({CONF_EMAIL: str, CONF_PASSWORD: str, "cookie": str}),
errors=errors
)
async def setup_api_client(self, user_input):
_LOGGER.debug(f"Setting up API client with {user_input}")
if "cookie" not in user_input:
client = ApiClient(aiohttp_client.async_get_clientsession(self.hass))
cookie = await client.get_cookie_from_login(user_input.get('email'), user_input.get('password'))
else:
cookie = user_input.get("cookie")
return ApiClient(aiohttp_client.async_get_clientsession(self.hass), cookie)
def validate_ip(self, ip) -> bool:
try:
ipaddress.IPv4Address(ip)
return True
except ValueError:
return False
def add_broker_to_config(self, device_config: DeviceConfiguration) -> DeviceConfiguration:
mqtt_entry = self.mqtt_entry
broker_port = mqtt_entry.data.get("port")
broker_username = mqtt_entry.data.get("username", "")
broker_password = mqtt_entry.data.get("password", "")
broker = MqttBroker(
broker_id=f"ha-button-plus",
url=f"mqtt://{self.broker_endpoint}/",
port=broker_port,
ws_port=9001,
username=broker_username,
password=broker_password
)
device_config.mqtt_brokers.append(broker)
return device_config
def add_topics_to_buttons(self, device_config) -> DeviceConfiguration:
device_id = device_config.info.device_id
active_connectors = [
connector.connector_id
for connector in device_config.info.connectors
if connector.connector_type in [1, 2]
]
for button in filter(lambda b: b.button_id // 2 in active_connectors, device_config.mqtt_buttons):
# Create topics for button main label
button.topics.append({
"brokerid": "ha-button-plus",
"topic": f"buttonplus/{device_id}/button/{button.button_id}/label",
"payload": "",
| """Config flow for Hello World integration."""
from __future__ import annotations
_LOGGER = logging.getLogger(__name__)
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Button+."""
local_brokers = [
"core-mosquitto",
"127.0.0.1",
"localhost"
]
def __init__(self):
self.mqtt_entry = None
self.broker_endpoint = None
VERSION = 1
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_PUSH
async def async_step_user(self, user_input=None):
"""Handle the initial Button+ setup, showing the 2 options and checking the MQTT integration."""
errors = {}
mqtt_entries = self.hass.config_entries.async_entries(domain="mqtt")
if len(mqtt_entries) < 1:
mqtt_url = f'{get_url(self.hass)}/config/integrations/integration/mqtt'
return self.async_abort(
reason="mqtt_not_enabled",
description_placeholders={
"mqtt_integration_link": mqtt_url
})
mqtt_entry = mqtt_entries[0]
broker = self.get_mqtt_endpoint(mqtt_entry.data.get("broker"))
broker_port = mqtt_entry.data.get("port")
broker_username = mqtt_entry.data.get("username", "(No authentication)")
self.mqtt_entry = mqtt_entry
if user_input is not None:
self.broker_endpoint = user_input.get("broker", broker)
return await self.async_step_choose_entry()
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({
vol.Required("broker", default=broker): str
}),
errors=errors,
description_placeholders={
"mqtt_broker": broker,
"mqtt_broker_port": broker_port,
"mqtt_user": broker_username
}
)
async def async_step_choose_entry(self, user_input=None):
errors = {}
# if user_input is not None:
return self.async_show_menu(
step_id="choose_entry",
menu_options=["fetch_website", "manual"],
description_placeholders={}
)
async def async_step_manual(self, user_input=None):
""" Handle setting up button plus from manual IP."""
errors = {}
ip = None
if user_input is not None:
ip = user_input.get(CONF_IP_ADDRESS, None)
valid = self.validate_ip(ip)
if valid:
try:
_LOGGER.debug(f"Fetching button+ device at {ip}")
api_client = LocalApiClient(ip, aiohttp_client.async_get_clientsession(self.hass))
json_config = await api_client.fetch_config()
device_config: DeviceConfiguration = DeviceConfiguration.from_json(json_config)
self.add_broker_to_config(device_config)
self.add_topics_to_buttons(device_config)
await api_client.push_config(device_config)
return self.async_create_entry(
title=f"{device_config.core.name}",
description=f"Base module on {ip} with id {device_config.info.device_id}",
data={"config": json_config}
)
except JSONDecodeError as ex: # pylint: disable=broad-except
_LOGGER.error(
f"{DOMAIN} Could not parse json from IP {ip} : %s - traceback: %s",
ex,
traceback.format_exc()
)
errors["base"] = f"Error connecting or reading from {ip}"
except Exception as ex: # pylint: disable=broad-except
_LOGGER.error(
f"{DOMAIN} Exception in login : %s - traceback: %s",
ex,
traceback.format_exc()
)
errors["base"] = "cannot_connect"
else:
errors["base"] = 'invalid_ip'
return self.async_show_form(
step_id="manual",
data_schema=vol.Schema({CONF_IP_ADDRESS: str}),
errors=errors,
description_placeholders={
"ip": ip
}
)
async def async_step_fetch_website(self, user_input=None):
"""Handle fetching the Button+ devices from the website."""
errors = {}
_LOGGER.debug(f"Fetch website step {user_input}")
if user_input is not None:
try:
api_client = await self.setup_api_client(user_input)
valid = await api_client.test_connection()
if valid:
json_response = await api_client.fetch_configs()
devices = json.loads(json_response)
last_entry = None
total_devices = len(devices)
_LOGGER.info(f"Found {total_devices} devices from Button+ website")
for device in devices:
device_website_id = device.get("Id")
device_ip = device.get('IpAddress')
if not device_ip:
_LOGGER.warning(f"Skipping device {device_website_id}, it has no IP so must be virtual")
continue
_LOGGER.debug(f"loaded device from website with id: {device_website_id} and ip {device_ip}")
device_config = json.loads(device.get("Json"))
device_name = device_config.get('core').get('name')
device_id = device_config.get('info').get('id')
last_entry = self.async_create_entry(
title=f"{device_name}",
description=f"Base module on {device_ip} with local id {device_id} and website id {device_website_id}",
data=device_config
)
return last_entry
except JSONDecodeError as ex: # pylint: disable=broad-except
_LOGGER.error(
f"{DOMAIN} Could not parse json from Button+ website : %s - traceback: %s",
ex,
traceback.format_exc()
)
errors["base"] = "Error connecting or reading from https://api.button.plus/"
except Exception as ex: # pylint: disable=broad-except
_LOGGER.error(
f"{DOMAIN} Exception in login : %s - traceback: %s",
ex,
traceback.format_exc()
)
errors["base"] = "cannot_connect"
if "base" not in errors:
errors["base"] = "cannot_connect"
return self.async_show_form(
step_id="fetch_website",
data_schema=vol.Schema({CONF_EMAIL: str, CONF_PASSWORD: str, "cookie": str}),
errors=errors
)
async def setup_api_client(self, user_input):
_LOGGER.debug(f"Setting up API client with {user_input}")
if "cookie" not in user_input:
client = ApiClient(aiohttp_client.async_get_clientsession(self.hass))
cookie = await client.get_cookie_from_login(user_input.get('email'), user_input.get('password'))
else:
cookie = user_input.get("cookie")
return ApiClient(aiohttp_client.async_get_clientsession(self.hass), cookie)
def validate_ip(self, ip) -> bool:
try:
ipaddress.IPv4Address(ip)
return True
except ValueError:
return False
def add_broker_to_config(self, device_config: DeviceConfiguration) -> DeviceConfiguration:
mqtt_entry = self.mqtt_entry
broker_port = mqtt_entry.data.get("port")
broker_username = mqtt_entry.data.get("username", "")
broker_password = mqtt_entry.data.get("password", "")
broker = MqttBroker(
broker_id=f"ha-button-plus",
url=f"mqtt://{self.broker_endpoint}/",
port=broker_port,
ws_port=9001,
username=broker_username,
password=broker_password
)
device_config.mqtt_brokers.append(broker)
return device_config
def add_topics_to_buttons(self, device_config) -> DeviceConfiguration:
device_id = device_config.info.device_id
active_connectors = [
connector.connector_id
for connector in device_config.info.connectors
if connector.connector_type in [1, 2]
]
for button in filter(lambda b: b.button_id // 2 in active_connectors, device_config.mqtt_buttons):
# Create topics for button main label
button.topics.append({
"brokerid": "ha-button-plus",
"topic": f"buttonplus/{device_id}/button/{button.button_id}/label",
"payload": "", | "eventtype": EventType.LABEL | 4 | 2023-12-18 15:14:21+00:00 | 8k |
Sam-Izdat/tinycio | src/tinycio/colorspace.py | [
{
"identifier": "Float2",
"path": "src/tinycio/numerics/vector.py",
"snippet": "class Float2(np.ndarray):\n \"\"\"\n Float2 type using numpy.ndarray.\n \"\"\"\n def __new__(cls, *args):\n if len(args) == 1:\n if isinstance(args[0], list) or isinstance(args[0], tuple):\n ... | import typing
import torch
import numpy as np
from typing import Union
from enum import IntEnum
from .numerics import Float2, matmul_tl as mm | 6,752 |
mat_xyz_to_rec2020 = [
[1.71665118797127, -0.355670783776393, -0.25336628137366],
[-0.666684351832489, 1.61648123663494, 0.0157685458139111],
[0.0176398574453108, -0.0427706132578085, 0.942103121235474]]
# NOTE: No chromatic adaptation
mat_acescg_to_xyz = [
[ 0.66245418, 0.13400421, 0.15618769],
[ 0.27222872, 0.67408177, 0.05368952],
[-0.00557465, 0.00406073, 1.0103391 ]]
# NOTE: No chromatic adaptation
mat_xyz_to_acescg = [
[ 1.64102338, -0.32480329, -0.2364247 ],
[-0.66366286, 1.61533159, 0.01675635],
[ 0.01172189, -0.00828444, 0.98839486]]
# NOTE: For CIE XYZ color
mat_d60_to_d65 = [
[ 0.98722400,-0.00611327, 0.01595330],
[-0.00759836, 1.00186000, 0.00533002],
[ 0.00307257,-0.00509595, 1.08168000]]
# NOTE: For CIE XYZ color
mat_d65_to_d60 = [
[ 1.01303000, 0.00610531,-0.01497100],
[ 0.00769823, 0.99816500,-0.00503203],
[-0.00284131, 0.00468516, 0.92450700]]
# NOTE: For CIE XYZ color
mat_d65_to_dci = [
[0.976578896646979768, -0.0154362646984919742, -0.016686021704209866],
[-0.0256896658505145926, 1.02853916787996963, -0.00378517365630504153],
[-0.00570574587417104179, 0.0110778657389971485, 0.871176159390377409]]
# NOTE: For CIE XYZ color
mat_dci_to_d65 = [
[1.02449672775257752, 0.0151635410224165156, 0.0196885223342066827],
[0.0256121933371584198, 0.97258630562441342, 0.00471635229242730096],
[0.0063842306500876874, -0.012268082736730219, 1.14794244517367791]]
mat_xyz_to_lms = [
[ 0.8951, 0.2664,-0.1614],
[-0.7502, 1.7135, 0.0367],
[ 0.0389,-0.0685, 1.0296]]
mat_lms_to_xyz = [
[ 0.986993, -0.147054, 0.159963],
[ 0.432305, 0.51836, 0.0492912],
[ -0.00852866, 0.0400428, 0.968487]]
# OKLAB's XYZ to LMS
mat_oklab_m1 = [
[ 0.8189330101, 0.3618667424, -0.1288597137],
[ 0.0329845436, 0.9293118715, 0.0361456387],
[ 0.0482003018, 0.2643662691, 0.6338517070]]
# OKLAB's non-linear L'M'S' to OKLAB
mat_oklab_m2 = [
[ 0.2104542553, 0.7936177850, -0.0040720468],
[ 1.9779984951, -2.4285922050, 0.4505937099],
[ 0.0259040371, 0.7827717662, -0.8086757660]]
# Inverse of OKLAB M1
mat_oklab_m1_inv = [
[ 1.22701385, -0.55779998, 0.28125615],
[-0.04058018, 1.11225687, -0.07167668],
[-0.07638128, -0.42148198, 1.58616322]]
# Inverse of OKLAB M2
mat_oklab_m2_inv = [
[ 1. , 0.39633779, 0.21580376],
[ 1.00000001, -0.10556134, -0.06385417],
[ 1.00000005, -0.08948418, -1.29148554]]
@classmethod
def convert(cls, im:Union[torch.Tensor, ColorImage], source:Variant, destination:Variant) -> torch.Tensor:
"""
Change the color space of an image. Cylindrical transformations HSV/HSL are
treated as their own color spaces and assumed to be relative to sRGB linear.
Unless otherwise noted or required by specification (e.g. ACES), we assume D65 white point.
.. warning::
Tone mapping is not included, so converting the color space of HDR values to
an LDR-designated color space will not automatically reduce dynamic range. For example,
taking an HDR image from :code:`ACESCG` (AP1) to :code:`SRGB` will yield the sRGB
gamma curve, but values outside the required range must still be tone mapped or clamped beforehand.
.. warning::
Cylindrical transformations (HSL, HSV) should be given input in [0, 1] linear sRGB range
(or equivalent). This is not strictly enforced but input outside this range may yield
unpredictable results or *NaN* values.
:param im: [C=3, H, W] image tensor
:type im: torch.Tensor | ColorImage
:param source: color space to convert from
:param destination: color space to convert to
:return: image tensor in designated color space
"""
ip, op = source, destination
cs = cls.Variant
tf = TransferFunction
if ip == op: return im
assert im.dim() == 3 and im.size(0) == 3, f"expected [C=3, H, W] image tensor, got {im.size()}"
assert source != 0, f"Unknown source color space"
assert ip & cs.SUPPORTED, f"Source color space not supported: {source.name}"
assert op & cs.SUPPORTED, f"Destination color space not supported: {destination.name}"
assert ip & ~cs.DISABLED, f"Source color space disabled: {ColorSpace.Variant(ip).name}"
assert op & ~cs.DISABLED, f"Destination color space disabled: {ColorSpace.Variant(op).name}"
err_not_implemented = f"Color space conversion not implemented: {ColorSpace.Variant(ip).name} to {ColorSpace.Variant(op).name}"
# Direct path where it matters, loop-de-loop elsewhere
if ip == cs.SRGB_LIN:
if op == cs.SRGB: im = tf.srgb_oetf(im)
elif op == cs.REC709: im = tf.rec709_oetf(im)
| from __future__ import annotations
class ColorSpace:
"""
Color space conversion. Applies OETFs and EOTFs as needed but omits tonemapping. Cylindrical transformations are
treated as distinct color spaces. Example:
.. highlight:: python
.. code-block:: python
cs_in = ColorSpace.Variant.SRGB_LIN
cs_out = ColorSpace.Variant.OKLAB
oklab_image = ColorSpace.convert(srgb_image, source=cs_in, destination=cs_out)
"""
class Variant(IntEnum):
"""
Color space enum. For a list of available options, see :ref:`ref_color_spaces`.
"""
UNKNOWN = 1<<0
NONCOLOR = 1<<1
CIE_XYZ = 1<<2
CIE_XYY = 1<<3
SRGB = 1<<4
SRGB_LIN = 1<<5
REC709 = 1<<6
REC2020 = 1<<7
REC2020_LIN = 1<<8
DCI_P3 = 1<<9
DCI_P3_LIN = 1<<10
DISPLAY_P3 = 1<<11
ACESCG = 1<<12
ACESCC = 1<<13
ACESCCT = 1<<14
ACES2065_1 = 1<<15
LMS = 1<<16
OKLAB = 1<<17
CIELAB = 1<<18
CIELUV = 1<<19
HSV = 1<<20
HSL = 1<<21
OKHSV = 1<<22
OKHSL = 1<<23
SCENE_LINEAR = SRGB_LIN | REC2020_LIN | DCI_P3_LIN | ACESCG | ACES2065_1 | CIE_XYZ
PERCEPTUAL = OKLAB | CIELAB | CIELUV | OKHSL | OKHSV
CYLINDRICAL = HSL | HSV | OKHSL | OKHSV
GAMUT_SRGB = SRGB | SRGB_LIN | REC709 | HSL | HSV
GAMUT_AP0 = ACES2065_1
GAMUT_AP1 = ACESCG | ACESCC | ACESCCT
GAMUT_REC2020 = REC2020 | REC2020_LIN
GAMUT_DCI_P3 = DCI_P3 | DCI_P3_LIN
GAMUT_DISPLAY_P3= DISPLAY_P3
GAMUT_OKLAB = OKLAB | OKHSL | OKHSV
GAMUT_CIE_XYZ = CIE_XYZ | CIE_XYY
GAMUT_CIELAB = CIELAB
GAMUT_CIELUV = CIELUV
GAMUT_OTHER = LMS | UNKNOWN | NONCOLOR
WP_D65 = SRGB | SRGB_LIN | REC709 | DISPLAY_P3 | REC2020 | REC2020_LIN | CIE_XYZ | CIE_XYY
WP_CCT_6300 = DCI_P3 | DCI_P3_LIN
WP_CCT_6000 = ACESCG | ACESCC | ACESCCT | ACES2065_1
MODEL_RGB = SRGB | SRGB_LIN | REC709 | REC2020 | REC2020_LIN | DCI_P3 | DCI_P3_LIN | DISPLAY_P3 | \
ACESCG | ACESCC | ACESCCT | ACES2065_1
MODEL_CIE = CIE_XYZ | CIE_XYY | CIELAB | CIELUV
MODEL_CAM = 0
MODEL_YUV = 0
MODEL_OTHER = LMS | HSL | HSV | OKLAB # is OKLAB CAM-based?
NEGATIVE = OKLAB | CIELAB | CIELUV | GAMUT_AP0
NON_NEGATIVE = ~NEGATIVE
DISABLED = CIELUV
UNSUPPORTED = OKHSV | OKHSL # disabled doesn't go here - CS must have alternate path
SUPPORTED = ~UNSUPPORTED
# FIXME: LUV doesn't quite match expected values, needs further testing
mat_xyz_to_srgb = [
[3.24096994190452134, -1.53738317757009346, -0.498610760293003284],
[-0.969243636280879826, 1.87596750150772067, 0.0415550574071756125],
[0.0556300796969936084, -0.203976958888976564, 1.05697151424287856]]
mat_srgb_to_xyz = [
[0.412390799265959481, 0.357584339383877964, 0.180480788401834288],
[0.212639005871510358, 0.715168678767755927, 0.072192315360733715],
[0.0193308187155918507, 0.119194779794625988, 0.950532152249660581]]
mat_srgb_to_acescg = [
[ 0.6130974024, 0.3395231462, 0.04737945141],
[ 0.07019372247, 0.916353879, 0.01345239847],
[ 0.02061559288, 0.1095697729, 0.8698146341]]
# NOTE: Includes "D60"/D65 white point conversion
mat_acescg_to_srgb = [
[ 1.705050993, -0.6217921206,-0.083258872],
[-0.1302564175, 1.140804737, -0.01054831907],
[-0.02400335681,-0.1289689761, 1.152972333]]
# NOTE: Includes "D60"/D65 white point conversion
mat_srgb_to_aces2065_1 = [
[ 0.439632982, 0.382988698, 0.17737832],
[ 0.0897764431, 0.813439429, 0.0967841284],
[ 0.0175411704, 0.111546553, 0.870912277]]
mat_aces2065_1_to_srgb = [
[ 2.52168619, -1.13413099, -0.387555198],
[-0.276479914, 1.37271909, -0.0962391736],
[-0.015378065, -0.152975336, 1.1683534]]
mat_srgb_to_displayp3 = [
[ 0.822461969, 0.177538031, 1.15772692e-10],
[ 0.0331941989, 0.966805801, 1.95085037e-11],
[ 0.0170826307, 0.0723974405, 0.910519929]]
mat_displayp3_to_srgb = [
[ 1.22494018, -0.224940176, -4.77534979e-11],
[-0.0420569547, 1.04205695, 3.37864801e-11],
[-0.0196375546,-0.0786360454, 1.0982736]]
# NOTE: No chromatic adaptation
mat_srgb_to_dcip3 = [
[0.868579739716132409, 0.128919138460847047, 0.00250112182302054368],
[0.0345404102543194426, 0.961811386361919975, 0.0036482033837605824],
[0.0167714290414502718, 0.0710399977868858352, 0.912188573171663893]]
# NOTE: No chromatic adaptation
mat_dcip3_to_srgb = [
[ 1.15751640619975871, -0.154962378073857756, -0.00255402812590095854],
[-0.0415000715306859699, 1.04556792307969925, -0.00406785154901328463],
[-0.0180500389562539583,-0.0785782726530290654, 1.09662831160928302]]
# NOTE: No chromatic adaptation
mat_dcip3_to_xyz = [
[ 0.445169815564552417, 0.277134409206777664, 0.172282669815564564],
[ 0.209491677912730539, 0.721595254161043636, 0.0689130679262258258],
[-3.63410131696985616e-17, 0.0470605600539811521, 0.907355394361973415]]
# NOTE: No chromatic adaptation
mat_xyz_to_dcip3 = [
[2.7253940304917328, -1.01800300622718496, -0.440163195190036463],
[-0.795168025808764195, 1.689732054843624, 0.0226471906084774533],
[0.0412418913957000325, -0.0876390192158623825, 1.10092937864632191]]
mat_srgb_to_rec2020 = [
[ 0.627403896, 0.329283039, 0.0433130657],
[ 0.0690972894, 0.919540395, 0.0113623156],
[ 0.0163914389, 0.0880133077, 0.895595253]]
mat_rec2020_to_srgb = [
[ 1.660491, -0.587641139,-0.0728498633],
[-0.124550475, 1.1328999, -0.00834942258],
[-0.0181507633,-0.100578898, 1.11872966]]
mat_rec2020_to_xyz = [
[0.636958048301291, 0.144616903586208, 0.168880975164172],
[0.262700212011267, 0.677998071518871, 0.059301716469862],
[4.99410657446607e-17, 0.0280726930490874, 1.06098505771079]]
mat_xyz_to_rec2020 = [
[1.71665118797127, -0.355670783776393, -0.25336628137366],
[-0.666684351832489, 1.61648123663494, 0.0157685458139111],
[0.0176398574453108, -0.0427706132578085, 0.942103121235474]]
# NOTE: No chromatic adaptation
mat_acescg_to_xyz = [
[ 0.66245418, 0.13400421, 0.15618769],
[ 0.27222872, 0.67408177, 0.05368952],
[-0.00557465, 0.00406073, 1.0103391 ]]
# NOTE: No chromatic adaptation
mat_xyz_to_acescg = [
[ 1.64102338, -0.32480329, -0.2364247 ],
[-0.66366286, 1.61533159, 0.01675635],
[ 0.01172189, -0.00828444, 0.98839486]]
# NOTE: For CIE XYZ color
mat_d60_to_d65 = [
[ 0.98722400,-0.00611327, 0.01595330],
[-0.00759836, 1.00186000, 0.00533002],
[ 0.00307257,-0.00509595, 1.08168000]]
# NOTE: For CIE XYZ color
mat_d65_to_d60 = [
[ 1.01303000, 0.00610531,-0.01497100],
[ 0.00769823, 0.99816500,-0.00503203],
[-0.00284131, 0.00468516, 0.92450700]]
# NOTE: For CIE XYZ color
mat_d65_to_dci = [
[0.976578896646979768, -0.0154362646984919742, -0.016686021704209866],
[-0.0256896658505145926, 1.02853916787996963, -0.00378517365630504153],
[-0.00570574587417104179, 0.0110778657389971485, 0.871176159390377409]]
# NOTE: For CIE XYZ color
mat_dci_to_d65 = [
[1.02449672775257752, 0.0151635410224165156, 0.0196885223342066827],
[0.0256121933371584198, 0.97258630562441342, 0.00471635229242730096],
[0.0063842306500876874, -0.012268082736730219, 1.14794244517367791]]
mat_xyz_to_lms = [
[ 0.8951, 0.2664,-0.1614],
[-0.7502, 1.7135, 0.0367],
[ 0.0389,-0.0685, 1.0296]]
mat_lms_to_xyz = [
[ 0.986993, -0.147054, 0.159963],
[ 0.432305, 0.51836, 0.0492912],
[ -0.00852866, 0.0400428, 0.968487]]
# OKLAB's XYZ to LMS
mat_oklab_m1 = [
[ 0.8189330101, 0.3618667424, -0.1288597137],
[ 0.0329845436, 0.9293118715, 0.0361456387],
[ 0.0482003018, 0.2643662691, 0.6338517070]]
# OKLAB's non-linear L'M'S' to OKLAB
mat_oklab_m2 = [
[ 0.2104542553, 0.7936177850, -0.0040720468],
[ 1.9779984951, -2.4285922050, 0.4505937099],
[ 0.0259040371, 0.7827717662, -0.8086757660]]
# Inverse of OKLAB M1
mat_oklab_m1_inv = [
[ 1.22701385, -0.55779998, 0.28125615],
[-0.04058018, 1.11225687, -0.07167668],
[-0.07638128, -0.42148198, 1.58616322]]
# Inverse of OKLAB M2
mat_oklab_m2_inv = [
[ 1. , 0.39633779, 0.21580376],
[ 1.00000001, -0.10556134, -0.06385417],
[ 1.00000005, -0.08948418, -1.29148554]]
@classmethod
def convert(cls, im:Union[torch.Tensor, ColorImage], source:Variant, destination:Variant) -> torch.Tensor:
"""
Change the color space of an image. Cylindrical transformations HSV/HSL are
treated as their own color spaces and assumed to be relative to sRGB linear.
Unless otherwise noted or required by specification (e.g. ACES), we assume D65 white point.
.. warning::
Tone mapping is not included, so converting the color space of HDR values to
an LDR-designated color space will not automatically reduce dynamic range. For example,
taking an HDR image from :code:`ACESCG` (AP1) to :code:`SRGB` will yield the sRGB
gamma curve, but values outside the required range must still be tone mapped or clamped beforehand.
.. warning::
Cylindrical transformations (HSL, HSV) should be given input in [0, 1] linear sRGB range
(or equivalent). This is not strictly enforced but input outside this range may yield
unpredictable results or *NaN* values.
:param im: [C=3, H, W] image tensor
:type im: torch.Tensor | ColorImage
:param source: color space to convert from
:param destination: color space to convert to
:return: image tensor in designated color space
"""
ip, op = source, destination
cs = cls.Variant
tf = TransferFunction
if ip == op: return im
assert im.dim() == 3 and im.size(0) == 3, f"expected [C=3, H, W] image tensor, got {im.size()}"
assert source != 0, f"Unknown source color space"
assert ip & cs.SUPPORTED, f"Source color space not supported: {source.name}"
assert op & cs.SUPPORTED, f"Destination color space not supported: {destination.name}"
assert ip & ~cs.DISABLED, f"Source color space disabled: {ColorSpace.Variant(ip).name}"
assert op & ~cs.DISABLED, f"Destination color space disabled: {ColorSpace.Variant(op).name}"
err_not_implemented = f"Color space conversion not implemented: {ColorSpace.Variant(ip).name} to {ColorSpace.Variant(op).name}"
# Direct path where it matters, loop-de-loop elsewhere
if ip == cs.SRGB_LIN:
if op == cs.SRGB: im = tf.srgb_oetf(im)
elif op == cs.REC709: im = tf.rec709_oetf(im) | elif op == cs.REC2020: im = tf.rec2020_oetf(mm(im, cls.mat_srgb_to_rec2020)) | 0 | 2023-12-15 15:39:08+00:00 | 8k |
legalontech-oss/simple-search-query-parser-sample | src/Driver1.py | [
{
"identifier": "SimpleSearchQueryLexer",
"path": "src/parser/SimpleSearchQueryLexer.py",
"snippet": "class SimpleSearchQueryLexer(Lexer):\n\n atn = ATNDeserializer().deserialize(serializedATN())\n\n decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]\n\n T__0 = 1\n T... | import sys
from antlr4 import CommonTokenStream, FileStream
from src.parser.SimpleSearchQueryLexer import SimpleSearchQueryLexer
from src.parser.SimpleSearchQueryParser import SimpleSearchQueryParser
from src.VisitorInterp import VisitorInterp | 4,057 |
def main(argv):
input_stream = FileStream(argv[1])
lexer = SimpleSearchQueryLexer(input_stream)
stream = CommonTokenStream(lexer)
parser = SimpleSearchQueryParser(stream)
tree = parser.expr()
if parser.getNumberOfSyntaxErrors() > 0:
print("syntax errors")
else:
|
def main(argv):
input_stream = FileStream(argv[1])
lexer = SimpleSearchQueryLexer(input_stream)
stream = CommonTokenStream(lexer)
parser = SimpleSearchQueryParser(stream)
tree = parser.expr()
if parser.getNumberOfSyntaxErrors() > 0:
print("syntax errors")
else: | vinterp = VisitorInterp() | 2 | 2023-12-19 07:44:19+00:00 | 8k |
thuiar/TCL-MAP | methods/TCL_MAP/manager.py | [
{
"identifier": "restore_model",
"path": "utils/functions.py",
"snippet": "def restore_model(model, model_dir, device):\n output_model_file = os.path.join(model_dir, 'pytorch_model.bin')\n m = torch.load(output_model_file, map_location=device)\n model.load_state_dict(m)\n return model"
},
... | import torch
import torch.nn.functional as F
import logging
import numpy as np
from torch import nn
from utils.functions import restore_model, save_model, EarlyStopping
from tqdm import trange, tqdm
from data.utils import get_dataloader
from utils.metrics import AverageMeter, Metrics
from transformers import AdamW, get_linear_schedule_with_warmup
from .model import TCL_MAP
from .loss import SupConLoss | 3,858 |
__all__ = ['TCL_MAP_manager']
class TCL_MAP_manager:
def __init__(self, args, data):
self.logger = logging.getLogger(args.logger_name)
self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
args.device = self.device
self.model = TCL_MAP(args)
self.model.to(self.device)
self.optimizer, self.scheduler = self._set_optimizer(args, self.model)
mm_dataloader = get_dataloader(args, data.mm_data)
self.train_dataloader, self.eval_dataloader, self.test_dataloader = \
mm_dataloader['train'], mm_dataloader['dev'], mm_dataloader['test']
self.args = args
self.criterion = nn.CrossEntropyLoss()
self.cons_criterion = SupConLoss(temperature=args.temperature)
self.metrics = Metrics(args)
if args.train:
self.best_eval_score = 0
else:
self.model = restore_model(self.model, args.model_output_path, self.device)
def _set_optimizer(self, args, model):
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay},
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
optimizer = AdamW(optimizer_grouped_parameters, lr = args.lr, correct_bias=False)
num_train_optimization_steps = int(args.num_train_examples / args.train_batch_size) * args.num_train_epochs
num_warmup_steps= int(args.num_train_examples * args.num_train_epochs * args.warmup_proportion / args.train_batch_size)
scheduler = get_linear_schedule_with_warmup(optimizer,
num_warmup_steps=num_warmup_steps,
num_training_steps=num_train_optimization_steps)
return optimizer, scheduler
def _train(self, args):
early_stopping = EarlyStopping(args)
for epoch in trange(int(args.num_train_epochs), desc="Epoch"):
self.model.train()
loss_record = AverageMeter()
cons_loss_record = AverageMeter()
cls_loss_record = AverageMeter()
for step, batch in enumerate(tqdm(self.train_dataloader, desc="Iteration")):
text_feats = batch['text_feats'].to(self.device)
cons_text_feats = batch['cons_text_feats'].to(self.device)
condition_idx = batch['condition_idx'].to(self.device)
video_feats = batch['video_feats'].to(self.device)
audio_feats = batch['audio_feats'].to(self.device)
label_ids = batch['label_ids'].to(self.device)
with torch.set_grad_enabled(True):
logits, _, condition, cons_condition = self.model(text_feats, video_feats, audio_feats, cons_text_feats, condition_idx)
cons_feature = torch.cat((condition.unsqueeze(1), cons_condition.unsqueeze(1)), dim=1)
cons_loss = self.cons_criterion(cons_feature)
cls_loss = self.criterion(logits, label_ids)
loss = cls_loss + cons_loss
self.optimizer.zero_grad()
loss.backward()
loss_record.update(loss.item(), label_ids.size(0))
cons_loss_record.update(cons_loss.item(), label_ids.size(0))
cls_loss_record.update(cls_loss.item(), label_ids.size(0))
if args.grad_clip != -1.0:
nn.utils.clip_grad_value_([param for param in self.model.parameters() if param.requires_grad], args.grad_clip)
self.optimizer.step()
self.scheduler.step()
outputs = self._get_outputs(args, self.eval_dataloader)
eval_score = outputs[args.eval_monitor]
eval_results = {
'train_loss': round(loss_record.avg, 4),
'cons_loss': round(cons_loss_record.avg, 4),
'cls_loss': round(cls_loss_record.avg, 4),
'eval_score': round(eval_score, 4),
'best_eval_score': round(early_stopping.best_score, 4),
}
self.logger.info("***** Epoch: %s: Eval results *****", str(epoch + 1))
for key in eval_results.keys():
self.logger.info(" %s = %s", key, str(eval_results[key]))
early_stopping(eval_score, self.model)
if early_stopping.early_stop:
self.logger.info(f'EarlyStopping at epoch {epoch + 1}')
break
self.best_eval_score = early_stopping.best_score
self.model = early_stopping.best_model
|
__all__ = ['TCL_MAP_manager']
class TCL_MAP_manager:
def __init__(self, args, data):
self.logger = logging.getLogger(args.logger_name)
self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
args.device = self.device
self.model = TCL_MAP(args)
self.model.to(self.device)
self.optimizer, self.scheduler = self._set_optimizer(args, self.model)
mm_dataloader = get_dataloader(args, data.mm_data)
self.train_dataloader, self.eval_dataloader, self.test_dataloader = \
mm_dataloader['train'], mm_dataloader['dev'], mm_dataloader['test']
self.args = args
self.criterion = nn.CrossEntropyLoss()
self.cons_criterion = SupConLoss(temperature=args.temperature)
self.metrics = Metrics(args)
if args.train:
self.best_eval_score = 0
else:
self.model = restore_model(self.model, args.model_output_path, self.device)
def _set_optimizer(self, args, model):
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay},
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
optimizer = AdamW(optimizer_grouped_parameters, lr = args.lr, correct_bias=False)
num_train_optimization_steps = int(args.num_train_examples / args.train_batch_size) * args.num_train_epochs
num_warmup_steps= int(args.num_train_examples * args.num_train_epochs * args.warmup_proportion / args.train_batch_size)
scheduler = get_linear_schedule_with_warmup(optimizer,
num_warmup_steps=num_warmup_steps,
num_training_steps=num_train_optimization_steps)
return optimizer, scheduler
def _train(self, args):
early_stopping = EarlyStopping(args)
for epoch in trange(int(args.num_train_epochs), desc="Epoch"):
self.model.train()
loss_record = AverageMeter()
cons_loss_record = AverageMeter()
cls_loss_record = AverageMeter()
for step, batch in enumerate(tqdm(self.train_dataloader, desc="Iteration")):
text_feats = batch['text_feats'].to(self.device)
cons_text_feats = batch['cons_text_feats'].to(self.device)
condition_idx = batch['condition_idx'].to(self.device)
video_feats = batch['video_feats'].to(self.device)
audio_feats = batch['audio_feats'].to(self.device)
label_ids = batch['label_ids'].to(self.device)
with torch.set_grad_enabled(True):
logits, _, condition, cons_condition = self.model(text_feats, video_feats, audio_feats, cons_text_feats, condition_idx)
cons_feature = torch.cat((condition.unsqueeze(1), cons_condition.unsqueeze(1)), dim=1)
cons_loss = self.cons_criterion(cons_feature)
cls_loss = self.criterion(logits, label_ids)
loss = cls_loss + cons_loss
self.optimizer.zero_grad()
loss.backward()
loss_record.update(loss.item(), label_ids.size(0))
cons_loss_record.update(cons_loss.item(), label_ids.size(0))
cls_loss_record.update(cls_loss.item(), label_ids.size(0))
if args.grad_clip != -1.0:
nn.utils.clip_grad_value_([param for param in self.model.parameters() if param.requires_grad], args.grad_clip)
self.optimizer.step()
self.scheduler.step()
outputs = self._get_outputs(args, self.eval_dataloader)
eval_score = outputs[args.eval_monitor]
eval_results = {
'train_loss': round(loss_record.avg, 4),
'cons_loss': round(cons_loss_record.avg, 4),
'cls_loss': round(cls_loss_record.avg, 4),
'eval_score': round(eval_score, 4),
'best_eval_score': round(early_stopping.best_score, 4),
}
self.logger.info("***** Epoch: %s: Eval results *****", str(epoch + 1))
for key in eval_results.keys():
self.logger.info(" %s = %s", key, str(eval_results[key]))
early_stopping(eval_score, self.model)
if early_stopping.early_stop:
self.logger.info(f'EarlyStopping at epoch {epoch + 1}')
break
self.best_eval_score = early_stopping.best_score
self.model = early_stopping.best_model
| if args.save_model: | 1 | 2023-12-20 03:12:38+00:00 | 8k |
replicate/cog-marigold | predict.py | [
{
"identifier": "seed_all",
"path": "src/util/seed_all.py",
"snippet": "def seed_all(seed: int = 0):\n \"\"\"\n Set random seeds of all components.\n \"\"\"\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)"
},
{
"identif... | import os
import time
import shutil
import subprocess
import torch
import numpy as np
from glob import glob
from typing import List
from PIL import Image
from tqdm.auto import tqdm
from torch.utils.data import DataLoader, TensorDataset
from cog import BasePredictor, Input, Path
from src.util.seed_all import seed_all
from src.util.batchsize import find_batch_size
from src.util.ensemble import ensemble_depths
from src.model.marigold_pipeline import MarigoldPipeline
from src.util.image_util import chw2hwc, colorize_depth_maps, resize_max_res | 5,822 |
def predict(
self,
image: Path = Input(description="Input image, use an RGB image for optimal results."),
resize_input: bool = Input(description="Resize the original input resolution to max resolution.", default=True),
num_infer: int = Input(
ge=1, le=20, default=10,
description="Number of inferences to be ensembled, a higher number gives better results but runs slower."
),
denoise_steps: int = Input(
ge=1, le=50, default=10,
description="Inference denoising steps, more steps results in higher accuracy but slower inference speed."
),
regularizer_strength: float = Input(
ge=0.0, le=1, default=0.02,
description="Ensembling parameter, weight of optimization regularizer.",
),
reduction_method: str = Input(
choices=["mean", "median"], default="median",
description="Ensembling parameter, method to merge aligned depth maps."
),
max_iter: int = Input(ge=1, le=20, default=5, description="Ensembling parameter, max optimization iterations."),
seed: int = Input(description="Seed for reproducibility, set to random if left as None.", default=None),
) -> List[Path]:
"""Run a single prediction on the model"""
if seed is None:
seed = int(time.time())
seed_all(seed)
resize_back = True if resize_input else False
n_repeat = num_infer
merging_max_res = None
# Read input image
input_image = Image.open(str(image))
input_size = input_image.size
# Resize image
if resize_input:
input_image = resize_max_res(input_image, max_edge_resolution=768)
# 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).float()
rgb_norm = rgb_norm.to(self.device)
assert rgb_norm.min() >= 0.0 and rgb_norm.max() <= 1.0
# Batch repeated input image
duplicated_rgb = torch.stack([rgb_norm] * n_repeat)
single_rgb_dataset = TensorDataset(duplicated_rgb)
_bs = find_batch_size(n_repeat=n_repeat, input_res=max(rgb_norm.shape[1:]))
single_rgb_loader = DataLoader(single_rgb_dataset, batch_size=_bs, shuffle=False)
# inference
with torch.no_grad():
# Predict depth maps (batched)
depth_pred_ls = []
for batch in tqdm(single_rgb_loader, desc="multiple inference", leave=False):
(batched_img,) = batch
depth_pred_raw = self.model.forward(
batched_img,
num_inference_steps=denoise_steps,
init_depth_latent=None,
show_pbar=True
)
# clip prediction
depth_pred_raw = torch.clip(depth_pred_raw, -1.0, 1.0)
# shift to [0, 1]
depth_pred_raw = depth_pred_raw * 2.0 - 1.0
depth_pred_ls.append(depth_pred_raw.detach().clone())
depth_preds = torch.concat(depth_pred_ls, axis=0).squeeze()
torch.cuda.empty_cache()
# Test-time ensembling
if n_repeat > 1:
depth_pred, pred_uncert = ensemble_depths(
depth_preds,
regularizer_strength=regularizer_strength,
max_iter=max_iter,
tol=1e-3,
reduction=reduction_method,
max_res=merging_max_res,
device=self.device,
)
else:
depth_pred = depth_preds
# Convert to numpy for saving
depth_pred = depth_pred.cpu().numpy()
# Resize back to original resolution
if resize_back:
pred_img = Image.fromarray(depth_pred)
pred_img = pred_img.resize(input_size)
depth_pred = np.asarray(pred_img)
# Save as 16-bit uint png
bw_path = "/tmp/depth_bw.png"
# scale prediction to [0, 1]
min_d = np.min(depth_pred)
max_d = np.max(depth_pred)
depth_to_save = (depth_pred - min_d) / (max_d - min_d)
depth_to_save = (depth_to_save * 65535.0).astype(np.uint16)
Image.fromarray(depth_to_save).save(bw_path, mode="I;16")
# Colorize
percentile = 0.03
min_depth_pct = np.percentile(depth_pred, percentile)
max_depth_pct = np.percentile(depth_pred, 100 - percentile)
color_path = "/tmp/depth_colored.png"
# [3, H, W] - values in (0, 1)
|
class Predictor(BasePredictor):
def setup(self) -> None:
"""Load the model into memory to make running multiple predictions efficient"""
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
ckpt_url = "https://weights.replicate.delivery/default/marigold/checkpoint.tar"
if not os.path.exists("/src/checkpoint"):
print("Downloading checkpoint")
try:
output = subprocess.check_output(["pget", "-x", ckpt_url, "/src/tmp"])
os.rename("/src/tmp/", "/src/checkpoint")
except subprocess.CalledProcessError as e:
raise e
# load model
self.model = MarigoldPipeline.from_pretrained("/src/checkpoint", enable_xformers=True)
self.model.to(self.device)
self.model.unet.eval()
def predict(
self,
image: Path = Input(description="Input image, use an RGB image for optimal results."),
resize_input: bool = Input(description="Resize the original input resolution to max resolution.", default=True),
num_infer: int = Input(
ge=1, le=20, default=10,
description="Number of inferences to be ensembled, a higher number gives better results but runs slower."
),
denoise_steps: int = Input(
ge=1, le=50, default=10,
description="Inference denoising steps, more steps results in higher accuracy but slower inference speed."
),
regularizer_strength: float = Input(
ge=0.0, le=1, default=0.02,
description="Ensembling parameter, weight of optimization regularizer.",
),
reduction_method: str = Input(
choices=["mean", "median"], default="median",
description="Ensembling parameter, method to merge aligned depth maps."
),
max_iter: int = Input(ge=1, le=20, default=5, description="Ensembling parameter, max optimization iterations."),
seed: int = Input(description="Seed for reproducibility, set to random if left as None.", default=None),
) -> List[Path]:
"""Run a single prediction on the model"""
if seed is None:
seed = int(time.time())
seed_all(seed)
resize_back = True if resize_input else False
n_repeat = num_infer
merging_max_res = None
# Read input image
input_image = Image.open(str(image))
input_size = input_image.size
# Resize image
if resize_input:
input_image = resize_max_res(input_image, max_edge_resolution=768)
# 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).float()
rgb_norm = rgb_norm.to(self.device)
assert rgb_norm.min() >= 0.0 and rgb_norm.max() <= 1.0
# Batch repeated input image
duplicated_rgb = torch.stack([rgb_norm] * n_repeat)
single_rgb_dataset = TensorDataset(duplicated_rgb)
_bs = find_batch_size(n_repeat=n_repeat, input_res=max(rgb_norm.shape[1:]))
single_rgb_loader = DataLoader(single_rgb_dataset, batch_size=_bs, shuffle=False)
# inference
with torch.no_grad():
# Predict depth maps (batched)
depth_pred_ls = []
for batch in tqdm(single_rgb_loader, desc="multiple inference", leave=False):
(batched_img,) = batch
depth_pred_raw = self.model.forward(
batched_img,
num_inference_steps=denoise_steps,
init_depth_latent=None,
show_pbar=True
)
# clip prediction
depth_pred_raw = torch.clip(depth_pred_raw, -1.0, 1.0)
# shift to [0, 1]
depth_pred_raw = depth_pred_raw * 2.0 - 1.0
depth_pred_ls.append(depth_pred_raw.detach().clone())
depth_preds = torch.concat(depth_pred_ls, axis=0).squeeze()
torch.cuda.empty_cache()
# Test-time ensembling
if n_repeat > 1:
depth_pred, pred_uncert = ensemble_depths(
depth_preds,
regularizer_strength=regularizer_strength,
max_iter=max_iter,
tol=1e-3,
reduction=reduction_method,
max_res=merging_max_res,
device=self.device,
)
else:
depth_pred = depth_preds
# Convert to numpy for saving
depth_pred = depth_pred.cpu().numpy()
# Resize back to original resolution
if resize_back:
pred_img = Image.fromarray(depth_pred)
pred_img = pred_img.resize(input_size)
depth_pred = np.asarray(pred_img)
# Save as 16-bit uint png
bw_path = "/tmp/depth_bw.png"
# scale prediction to [0, 1]
min_d = np.min(depth_pred)
max_d = np.max(depth_pred)
depth_to_save = (depth_pred - min_d) / (max_d - min_d)
depth_to_save = (depth_to_save * 65535.0).astype(np.uint16)
Image.fromarray(depth_to_save).save(bw_path, mode="I;16")
# Colorize
percentile = 0.03
min_depth_pct = np.percentile(depth_pred, percentile)
max_depth_pct = np.percentile(depth_pred, 100 - percentile)
color_path = "/tmp/depth_colored.png"
# [3, H, W] - values in (0, 1) | depth_colored = colorize_depth_maps( | 5 | 2023-12-15 07:19:14+00:00 | 8k |
CoolPointerException/Amigo | main.py | [
{
"identifier": "ProjectsTab",
"path": "gui/tab_projects.py",
"snippet": "class ProjectsTab:\n def __init__(self, root, frame):\n self.frame = frame\n self.root = root\n\n # Select Directory\n ttk.Label(frame, text=\"Project Directory:\", style='W.Label').pack(fill=tk.X, p... | import tkinter as tk
import sv_ttk
from tkinter import ttk
from tkinter.ttk import Style
from gui.tab_projects import ProjectsTab
from gui.settings import load_settings, save_settings
from gui.tab_settings import SettingsTab
from gui.tab_task import TaskTab | 6,721 |
class Application(tk.Tk):
def __init__(self):
super().__init__()
self.title("Amigo")
self.geometry("900x1100")
self.style = Style()
self.isLlamaInitialized = False
sv_ttk.set_theme("dark")
self.messages = []
self.style.configure('W.TButton', font=('calibri', 18, 'bold', 'underline'), borderwidth='4')
self.style.configure('W.Label', font=('calibri', 13, 'bold'))
# Create the tab control
self.tab_control = ttk.Notebook(self)
# Create tabs
self.settings_frame = ttk.Frame(self.tab_control)
self.task_frame = ttk.Frame(self.tab_control)
self.projects_frame = ttk.Frame(self.tab_control)
# Add tabs to notebook
self.tab_control.add(self.task_frame, text='Task')
self.tab_control.add(self.projects_frame, text='Projects')
self.tab_control.add(self.settings_frame, text='Settings')
# Init UI
|
class Application(tk.Tk):
def __init__(self):
super().__init__()
self.title("Amigo")
self.geometry("900x1100")
self.style = Style()
self.isLlamaInitialized = False
sv_ttk.set_theme("dark")
self.messages = []
self.style.configure('W.TButton', font=('calibri', 18, 'bold', 'underline'), borderwidth='4')
self.style.configure('W.Label', font=('calibri', 13, 'bold'))
# Create the tab control
self.tab_control = ttk.Notebook(self)
# Create tabs
self.settings_frame = ttk.Frame(self.tab_control)
self.task_frame = ttk.Frame(self.tab_control)
self.projects_frame = ttk.Frame(self.tab_control)
# Add tabs to notebook
self.tab_control.add(self.task_frame, text='Task')
self.tab_control.add(self.projects_frame, text='Projects')
self.tab_control.add(self.settings_frame, text='Settings')
# Init UI | self.settings_tab = SettingsTab(self, self.settings_frame) | 3 | 2023-12-15 14:06:38+00:00 | 8k |
quocanh34/magic-animate-modified | magicanimate/models/unet_3d_blocks.py | [
{
"identifier": "Transformer3DModel",
"path": "magicanimate/models/attention.py",
"snippet": "class Transformer3DModel(ModelMixin, ConfigMixin):\n @register_to_config\n def __init__(\n self,\n num_attention_heads: int = 16,\n attention_head_dim: int = 88,\n in_channels:... | import torch
from torch import nn
from .attention import Transformer3DModel
from .resnet import Downsample3D, ResnetBlock3D, Upsample3D
from .motion_module import get_motion_module | 4,617 | attn_num_head_channels,
resnet_groups=None,
cross_attention_dim=None,
dual_cross_attention=False,
use_linear_projection=False,
only_cross_attention=False,
upcast_attention=False,
resnet_time_scale_shift="default",
unet_use_cross_frame_attention=None,
unet_use_temporal_attention=None,
use_motion_module=None,
motion_module_type=None,
motion_module_kwargs=None,
):
up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
if up_block_type == "UpBlock3D":
return UpBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel,
temb_channels=temb_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
resnet_time_scale_shift=resnet_time_scale_shift,
use_motion_module=use_motion_module,
motion_module_type=motion_module_type,
motion_module_kwargs=motion_module_kwargs,
)
elif up_block_type == "CrossAttnUpBlock3D":
if cross_attention_dim is None:
raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock3D")
return CrossAttnUpBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel,
temb_channels=temb_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
cross_attention_dim=cross_attention_dim,
attn_num_head_channels=attn_num_head_channels,
dual_cross_attention=dual_cross_attention,
use_linear_projection=use_linear_projection,
only_cross_attention=only_cross_attention,
upcast_attention=upcast_attention,
resnet_time_scale_shift=resnet_time_scale_shift,
unet_use_cross_frame_attention=unet_use_cross_frame_attention,
unet_use_temporal_attention=unet_use_temporal_attention,
use_motion_module=use_motion_module,
motion_module_type=motion_module_type,
motion_module_kwargs=motion_module_kwargs,
)
raise ValueError(f"{up_block_type} does not exist.")
class UNetMidBlock3DCrossAttn(nn.Module):
def __init__(
self,
in_channels: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_shift: str = "default",
resnet_act_fn: str = "swish",
resnet_groups: int = 32,
resnet_pre_norm: bool = True,
attn_num_head_channels=1,
output_scale_factor=1.0,
cross_attention_dim=1280,
dual_cross_attention=False,
use_linear_projection=False,
upcast_attention=False,
unet_use_cross_frame_attention=None,
unet_use_temporal_attention=None,
use_motion_module=None,
motion_module_type=None,
motion_module_kwargs=None,
):
super().__init__()
self.has_cross_attention = True
self.attn_num_head_channels = attn_num_head_channels
resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
# there is always at least one resnet
resnets = [
ResnetBlock3D(
in_channels=in_channels,
out_channels=in_channels,
temb_channels=temb_channels,
eps=resnet_eps,
groups=resnet_groups,
dropout=dropout,
time_embedding_norm=resnet_time_scale_shift,
non_linearity=resnet_act_fn,
output_scale_factor=output_scale_factor,
pre_norm=resnet_pre_norm,
)
]
attentions = []
motion_modules = []
for _ in range(num_layers):
if dual_cross_attention:
raise NotImplementedError
attentions.append(
| # *************************************************************************
# This file may have been modified by Bytedance Inc. (“Bytedance Inc.'s Mo-
# difications”). All Bytedance Inc.'s Modifications are Copyright (2023) B-
# ytedance Inc..
# *************************************************************************
# Adapted from https://github.com/guoyww/AnimateDiff
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def get_down_block(
down_block_type,
num_layers,
in_channels,
out_channels,
temb_channels,
add_downsample,
resnet_eps,
resnet_act_fn,
attn_num_head_channels,
resnet_groups=None,
cross_attention_dim=None,
downsample_padding=None,
dual_cross_attention=False,
use_linear_projection=False,
only_cross_attention=False,
upcast_attention=False,
resnet_time_scale_shift="default",
unet_use_cross_frame_attention=None,
unet_use_temporal_attention=None,
use_motion_module=None,
motion_module_type=None,
motion_module_kwargs=None,
):
down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_type
if down_block_type == "DownBlock3D":
return DownBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
add_downsample=add_downsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
downsample_padding=downsample_padding,
resnet_time_scale_shift=resnet_time_scale_shift,
use_motion_module=use_motion_module,
motion_module_type=motion_module_type,
motion_module_kwargs=motion_module_kwargs,
)
elif down_block_type == "CrossAttnDownBlock3D":
if cross_attention_dim is None:
raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock3D")
return CrossAttnDownBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
temb_channels=temb_channels,
add_downsample=add_downsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
downsample_padding=downsample_padding,
cross_attention_dim=cross_attention_dim,
attn_num_head_channels=attn_num_head_channels,
dual_cross_attention=dual_cross_attention,
use_linear_projection=use_linear_projection,
only_cross_attention=only_cross_attention,
upcast_attention=upcast_attention,
resnet_time_scale_shift=resnet_time_scale_shift,
unet_use_cross_frame_attention=unet_use_cross_frame_attention,
unet_use_temporal_attention=unet_use_temporal_attention,
use_motion_module=use_motion_module,
motion_module_type=motion_module_type,
motion_module_kwargs=motion_module_kwargs,
)
raise ValueError(f"{down_block_type} does not exist.")
def get_up_block(
up_block_type,
num_layers,
in_channels,
out_channels,
prev_output_channel,
temb_channels,
add_upsample,
resnet_eps,
resnet_act_fn,
attn_num_head_channels,
resnet_groups=None,
cross_attention_dim=None,
dual_cross_attention=False,
use_linear_projection=False,
only_cross_attention=False,
upcast_attention=False,
resnet_time_scale_shift="default",
unet_use_cross_frame_attention=None,
unet_use_temporal_attention=None,
use_motion_module=None,
motion_module_type=None,
motion_module_kwargs=None,
):
up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
if up_block_type == "UpBlock3D":
return UpBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel,
temb_channels=temb_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
resnet_time_scale_shift=resnet_time_scale_shift,
use_motion_module=use_motion_module,
motion_module_type=motion_module_type,
motion_module_kwargs=motion_module_kwargs,
)
elif up_block_type == "CrossAttnUpBlock3D":
if cross_attention_dim is None:
raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock3D")
return CrossAttnUpBlock3D(
num_layers=num_layers,
in_channels=in_channels,
out_channels=out_channels,
prev_output_channel=prev_output_channel,
temb_channels=temb_channels,
add_upsample=add_upsample,
resnet_eps=resnet_eps,
resnet_act_fn=resnet_act_fn,
resnet_groups=resnet_groups,
cross_attention_dim=cross_attention_dim,
attn_num_head_channels=attn_num_head_channels,
dual_cross_attention=dual_cross_attention,
use_linear_projection=use_linear_projection,
only_cross_attention=only_cross_attention,
upcast_attention=upcast_attention,
resnet_time_scale_shift=resnet_time_scale_shift,
unet_use_cross_frame_attention=unet_use_cross_frame_attention,
unet_use_temporal_attention=unet_use_temporal_attention,
use_motion_module=use_motion_module,
motion_module_type=motion_module_type,
motion_module_kwargs=motion_module_kwargs,
)
raise ValueError(f"{up_block_type} does not exist.")
class UNetMidBlock3DCrossAttn(nn.Module):
def __init__(
self,
in_channels: int,
temb_channels: int,
dropout: float = 0.0,
num_layers: int = 1,
resnet_eps: float = 1e-6,
resnet_time_scale_shift: str = "default",
resnet_act_fn: str = "swish",
resnet_groups: int = 32,
resnet_pre_norm: bool = True,
attn_num_head_channels=1,
output_scale_factor=1.0,
cross_attention_dim=1280,
dual_cross_attention=False,
use_linear_projection=False,
upcast_attention=False,
unet_use_cross_frame_attention=None,
unet_use_temporal_attention=None,
use_motion_module=None,
motion_module_type=None,
motion_module_kwargs=None,
):
super().__init__()
self.has_cross_attention = True
self.attn_num_head_channels = attn_num_head_channels
resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
# there is always at least one resnet
resnets = [
ResnetBlock3D(
in_channels=in_channels,
out_channels=in_channels,
temb_channels=temb_channels,
eps=resnet_eps,
groups=resnet_groups,
dropout=dropout,
time_embedding_norm=resnet_time_scale_shift,
non_linearity=resnet_act_fn,
output_scale_factor=output_scale_factor,
pre_norm=resnet_pre_norm,
)
]
attentions = []
motion_modules = []
for _ in range(num_layers):
if dual_cross_attention:
raise NotImplementedError
attentions.append( | Transformer3DModel( | 0 | 2023-12-15 01:22:37+00:00 | 8k |
morikeli/persona | main.py | [
{
"identifier": "facial_expression",
"path": "features/person/faces/expressions/facial_expression.py",
"snippet": "FACIAL_EXPRESSIONS = [\n 'DEFAULT',\n 'ANGRY',\n 'ANGRY_NATURAL',\n 'DEFAULT_NATURAL',\n 'FLAT_NATURAL',\n 'FROWN_NATURAL',\n 'RAISED_EXCITED',\n 'RAISED_EXCITED_NAT... | from features.person.faces.expressions import facial_expression as fe
from features.fashion.accessories import add_ons
from features.fashion.clothing import clothes, hats
from features.fashion.hairstyles import beard, hair
from features.person.complexion import skins
from features.person.faces import face
from avatar.avatar import random_avatar, custom_avatar
from animations.utils import christmas_festive_animation
from images.image import download_avatar
import streamlit as st | 3,773 | # download_avatar()
st.balloons()
if cols_btn[0].button('Generate random avatar', use_container_width=True):
features_indices = random_avatar()
with tabs[0]:
st.caption('Add beard, hairstyle or hair cut')
avatar_hair = st.selectbox(
label=':haircut: Hair',
options=hair.HAIR_STYLES,
index=features_indices["hair"] if features_indices else 0,
)
avatar_beard = st.selectbox(
label=':bearded_person: Beard',
options=beard.BEARD,
index=features_indices["beard"] if features_indices else 0,
)
with tabs[1]:
st.caption('Add eyes or facial expression.')
avatar_eyes = st.selectbox(
label=':eyes: Eyes',
options=face.EYES,
index=features_indices["eyes"] if features_indices else 0,
)
avatar_facial_expr = st.selectbox(
label=':smiley: Facial expression',
options=fe.FACIAL_EXPRESSIONS,
index=features_indices["face_expression"] if features_indices else 0,
)
avatar_mouth = st.selectbox(
label=':lips: Mouth',
options=fe.FACIAL_EXPRESSIONS_MOUTH,
index=features_indices["mouth"] if features_indices else 0,
)
with tabs[2]:
st.caption("What are your favorite fashion trends?")
tabs_cols = st.columns([6, 6])
avatar_addons = tabs_cols[0].selectbox(
label=':sunglasses: Accessories',
options=add_ons.FASHION_ACCESSORIES,
index=features_indices["accessories"] if features_indices else 0,
)
avatar_clothe = tabs_cols[0].selectbox(
label=':tshirt: Clothes',
options=clothes.CLOTHES_CATEGORIES,
index=features_indices["clothing"] if features_indices else 0,
)
avatar_clothe_pattern = tabs_cols[1].selectbox(
label=':art: Clothe pattern',
options=clothes.CLOTHES_GRAPHICS,
index=features_indices["clothes_art"] if features_indices else 0,
)
avatar_hat = tabs_cols[1].selectbox(
label=':face_with_cowboy_hat: Headwear',
options=hats.HEADWEAR,
index=features_indices["headwear"] if features_indices else 0,
)
with tabs[3]:
st.caption('Play with colors')
tabs_cols = st.columns([6, 6])
avatar_skin_color = st.selectbox(
label='Skin complexion',
options=skins.SKIN_COLOR,
index=features_indices["skin"] if features_indices else 0,
)
avatar_hair_color = tabs_cols[0].selectbox(
label='Dye/Hair color',
options=hair.HAIR_COLOR,
index=features_indices["hair_color"] if features_indices else 0,
)
avatar_beard_color = tabs_cols[0].selectbox(
label='Beard color',
options=beard.BEARD_COLOR,
index=features_indices["beard_color"] if features_indices else 0,
)
avatar_clothes_color = tabs_cols[1].selectbox(
label='Clothes color',
options=clothes.CLOTHES_COLOR,
index=features_indices["clothes_color"] if features_indices else 0,
)
avatar_hat_color = tabs_cols[1].selectbox(
label='Hat color',
options=hats.HAT_COLOR,
index=features_indices["hat_color"] if features_indices else 0,
)
with tabs[4]:
st.caption('Add or remove background color in your avatar')
avatar_bg = st.selectbox(
label='Background',
options=('CIRCLE', 'TRANSPARENT'),
index=features_indices["background"] if features_indices else 0,
)
# selected avatar features
avatar_features = {
'accessories': avatar_addons,
'bg': avatar_bg,
'beard': avatar_beard,
'beard_color': avatar_beard_color,
'clothing': avatar_clothe,
'clothes_color': avatar_clothes_color,
'clothes_art': avatar_clothe_pattern,
'eyes': avatar_eyes,
'face_expression': avatar_facial_expr,
'hair_and_headwear': avatar_hair if avatar_hair != 'NO_HAIR' else avatar_hat, # display a hat if avatar_hair is "NO_HAIR"
'hair_color': avatar_hair_color,
'hat_color': avatar_hat_color,
'mouth': avatar_mouth,
'skin': avatar_skin_color,
}
|
# webpage configuration
st.set_page_config(page_title='Persona', page_icon=':busts_in_silhouette:', layout='centered')
with open('static/css/styles.css') as stylesheet:
st.markdown(f'<style>{stylesheet.read()}</style>', unsafe_allow_html=True)
def main(features_indices: dict = None):
""" This is the main function that uses streamlit to create a dynamic web page. """
# navigation tabs
tabs = st.tabs(['Beard & Hair', 'Facial features', 'Fashion trends', 'Color', 'Background style'])
st.divider()
# "Generate random avatar" & "Download button" buttons column
cols_btn = st.columns([6, 6])
with cols_btn[1]:
download_btn = download_avatar()
if download_btn: # display download button by default
# download_avatar()
st.balloons()
if cols_btn[0].button('Generate random avatar', use_container_width=True):
features_indices = random_avatar()
with tabs[0]:
st.caption('Add beard, hairstyle or hair cut')
avatar_hair = st.selectbox(
label=':haircut: Hair',
options=hair.HAIR_STYLES,
index=features_indices["hair"] if features_indices else 0,
)
avatar_beard = st.selectbox(
label=':bearded_person: Beard',
options=beard.BEARD,
index=features_indices["beard"] if features_indices else 0,
)
with tabs[1]:
st.caption('Add eyes or facial expression.')
avatar_eyes = st.selectbox(
label=':eyes: Eyes',
options=face.EYES,
index=features_indices["eyes"] if features_indices else 0,
)
avatar_facial_expr = st.selectbox(
label=':smiley: Facial expression',
options=fe.FACIAL_EXPRESSIONS,
index=features_indices["face_expression"] if features_indices else 0,
)
avatar_mouth = st.selectbox(
label=':lips: Mouth',
options=fe.FACIAL_EXPRESSIONS_MOUTH,
index=features_indices["mouth"] if features_indices else 0,
)
with tabs[2]:
st.caption("What are your favorite fashion trends?")
tabs_cols = st.columns([6, 6])
avatar_addons = tabs_cols[0].selectbox(
label=':sunglasses: Accessories',
options=add_ons.FASHION_ACCESSORIES,
index=features_indices["accessories"] if features_indices else 0,
)
avatar_clothe = tabs_cols[0].selectbox(
label=':tshirt: Clothes',
options=clothes.CLOTHES_CATEGORIES,
index=features_indices["clothing"] if features_indices else 0,
)
avatar_clothe_pattern = tabs_cols[1].selectbox(
label=':art: Clothe pattern',
options=clothes.CLOTHES_GRAPHICS,
index=features_indices["clothes_art"] if features_indices else 0,
)
avatar_hat = tabs_cols[1].selectbox(
label=':face_with_cowboy_hat: Headwear',
options=hats.HEADWEAR,
index=features_indices["headwear"] if features_indices else 0,
)
with tabs[3]:
st.caption('Play with colors')
tabs_cols = st.columns([6, 6])
avatar_skin_color = st.selectbox(
label='Skin complexion',
options=skins.SKIN_COLOR,
index=features_indices["skin"] if features_indices else 0,
)
avatar_hair_color = tabs_cols[0].selectbox(
label='Dye/Hair color',
options=hair.HAIR_COLOR,
index=features_indices["hair_color"] if features_indices else 0,
)
avatar_beard_color = tabs_cols[0].selectbox(
label='Beard color',
options=beard.BEARD_COLOR,
index=features_indices["beard_color"] if features_indices else 0,
)
avatar_clothes_color = tabs_cols[1].selectbox(
label='Clothes color',
options=clothes.CLOTHES_COLOR,
index=features_indices["clothes_color"] if features_indices else 0,
)
avatar_hat_color = tabs_cols[1].selectbox(
label='Hat color',
options=hats.HAT_COLOR,
index=features_indices["hat_color"] if features_indices else 0,
)
with tabs[4]:
st.caption('Add or remove background color in your avatar')
avatar_bg = st.selectbox(
label='Background',
options=('CIRCLE', 'TRANSPARENT'),
index=features_indices["background"] if features_indices else 0,
)
# selected avatar features
avatar_features = {
'accessories': avatar_addons,
'bg': avatar_bg,
'beard': avatar_beard,
'beard_color': avatar_beard_color,
'clothing': avatar_clothe,
'clothes_color': avatar_clothes_color,
'clothes_art': avatar_clothe_pattern,
'eyes': avatar_eyes,
'face_expression': avatar_facial_expr,
'hair_and_headwear': avatar_hair if avatar_hair != 'NO_HAIR' else avatar_hat, # display a hat if avatar_hair is "NO_HAIR"
'hair_color': avatar_hair_color,
'hat_color': avatar_hat_color,
'mouth': avatar_mouth,
'skin': avatar_skin_color,
}
| return custom_avatar(avatar_features) | 9 | 2023-12-19 09:39:04+00:00 | 8k |
JonatanNevo/better-iptables | iptables/iptables.py | [
{
"identifier": "ConnbytesDirection",
"path": "iptables/enums.py",
"snippet": "class ConnbytesDirection(str, Enum):\n ORIGINAL = \"original\"\n REPLY = \"reply\"\n BOTH = \"both\""
},
{
"identifier": "ConnbytesMode",
"path": "iptables/enums.py",
"snippet": "class ConnbytesMode(s... | import dataclasses
import re
from enum import Enum
from typing import Optional, Union, List, Tuple
from typing_extensions import Self
from iptables.enums import ConnbytesDirection, ConnbytesMode, ConntrackStates, ConntrackStatus, ConntrackDirection, \
LimitUnits, State, TcpFlags, Targets, Protocols, Tables, Chains, Actions, RejectType
from iptables.exceptions import IPTablesError, IPVersionError, ConnbytesError, ConnlimitAddrError, \
MultiportSourceAndDestinationError, MultiportPortsAndOtherError, MultiportFormatError | 4,255 | # owner, physdev, pkttype, policty, qouta, rateest, realm, recent, rpfilter, rt, sctp, set, socket, statistics,
# tcpmss, time, tos, ttl, u32
def comment(self, comment: str) -> Self:
self._modules.append(Module(module="comment", parameters=[("comment", f'"{comment}"')]))
return self
def connbytes(self, connbytes: str, mode: ConnbytesMode, direction: ConnbytesDirection) -> Self:
if not re.match("\d*:\d*", connbytes):
raise ConnbytesError
self._modules.append(Module(module="connbytes", parameters=[("connbytes", connbytes), ("connbytes-mode", mode),
("connbytes-dir", direction)]))
return self
def connlimit(
self,
upto: Optional[int] = None,
above: Optional[int] = None,
mask: Optional[int] = None,
sadder: bool = True,
daddr: bool = False
) -> Self:
if sadder and daddr:
raise ConnlimitAddrError
parameters = []
if upto:
parameters.append(("connlimit-upto", str(upto)))
if above:
parameters.append(("connlimit-above", str(above)))
if mask:
parameters.append(("connlimit-mask", str(mask)))
if sadder:
parameters.append(("connlimit-saddr", None))
if daddr:
parameters.append(("connlimit-daddr", None))
self._modules.append(Module(module="connlimit", parameters=parameters))
return self
def connmark(self, mark: int, mask: Optional[int] = None) -> Self:
if mask:
parameters = [("mark", f"{mark}/{mask}")]
else:
parameters = [("mark", mark)]
self._modules.append(Module(module="connmark", parameters=parameters))
return self
def conntrack(
self,
*,
state: Optional[List[ConntrackStates]] = None,
status: Optional[List[ConntrackStatus]] = None,
protocol: Optional[Protocols] = None,
original_source: Optional[str] = None,
original_source_port: Optional[int] = None,
original_destination: Optional[str] = None,
original_destination_port: Optional[int] = None,
reply_source: Optional[str] = None,
reply_source_port: Optional[int] = None,
reply_destination: Optional[str] = None,
reply_destination_port: Optional[int] = None,
expire: Optional[int] = None,
direction: Optional[ConntrackDirection] = None,
) -> Self:
parameters = []
if state:
parameters.append(("ctstate", ",".join(state)))
if status:
parameters.append(("ctstatus", ",".join(status)))
if protocol:
parameters.append(("ctproto", protocol))
if original_source:
parameters.append(("ctorigsrc", original_source))
if original_source_port:
parameters.append(("ctorigsrcport", original_source_port))
if original_destination:
parameters.append(("ctorigdst", original_destination))
if original_destination_port:
parameters.append(("ctorigdstport", original_destination_port))
if reply_source:
parameters.append(("ctreplsrc", reply_source))
if reply_source_port:
parameters.append(("ctreplsrcport", reply_source_port))
if reply_destination:
parameters.append(("ctrepldst", reply_destination))
if reply_destination_port:
parameters.append(("ctrepldstport", reply_destination_port))
if expire:
parameters.append(("ctexpire", expire))
if direction:
parameters.append(("ctdir", direction))
self._modules.append(Module(module="conntrack", parameters=parameters))
return self
def cpu(self, cpu: int) -> Self:
self._modules.append(Module(module="cpu", parameters=[("cpu", str(cpu))]))
return self
def limit(self, rate: int = 3, units: LimitUnits = LimitUnits.HOUR, burst: int = 5) -> Self:
self._modules.append(Module(module="limit", parameters=[("limit", f"{rate}/{units}"), ("limit-burst", burst)]))
return self
def mac(self, mac: str) -> Self:
self._modules.append(Module(module="mac", parameters=[("mac-source", mac)]))
return self
def mark(self, mark: int, mask: Optional[int] = None) -> Self:
if mask:
parameters = [("mark", f"{mark}/{mask}")]
else:
parameters = [("mark", mark)]
self._modules.append(Module(module="mark", parameters=parameters))
return self
def multiport(
self,
source_ports: Optional[List[Union[int, str]]] = None,
destination_ports: Optional[List[Union[int, str]]] = None,
ports: Optional[List[Union[int, str]]] = None
) -> Self:
if source_ports and destination_ports:
|
@dataclasses.dataclass(frozen=True)
class Module:
module: str
parameters: List[Tuple[str, str]] = dataclasses.field(default_factory=list)
def build(self) -> str:
parameters = []
for argument, value in self.parameters:
if value:
parameters.append(f"--{argument} {value}")
else:
parameters.append(f"--{argument}")
return f"-m {self.module} {' '.join(parameters)}"
@dataclasses.dataclass(frozen=True)
class Flags:
ipv4: bool = True
ipv6: bool = False
fragment: bool = False
lock: bool = False # same as --wait
verbose: bool = False
resolve: bool = True # same as --numeric
exact: bool = False
def __post_init__(self) -> None:
if self.ipv4 and self.ipv6:
raise IPVersionError
def build(self) -> str:
flags = []
if self.fragment:
flags.append("-f")
if self.ipv4:
flags.append("-4")
elif self.ipv6:
flags.append("-6")
if self.lock:
flags.append("-w")
if self.verbose:
flags.append("-v")
if not self.resolve:
flags.append("-n")
if self.exact:
flags.append("-x")
return " ".join(flags)
def __str__(self) -> str:
return self.build()
@dataclasses.dataclass(frozen=True)
class Matches:
# TODO: add set-counters
protocol: Optional[Protocols] = None
source_host: Optional[str] = None
source_port: Optional[int] = None
destination_host: Optional[str] = None
destination_port: Optional[int] = None
in_interface: Optional[str] = None
out_interface: Optional[str] = None
def build(self) -> str:
matches = []
if self.protocol:
matches.append(f"-p {self.protocol}")
if self.source_host:
matches.append(f"-s {self.source_host}")
if self.source_port:
matches.append(f"--sport {self.source_port}")
if self.destination_host:
matches.append(f"-d {self.destination_host}")
if self.destination_port:
matches.append(f"--dport {self.destination_port}")
if self.in_interface:
matches.append(f"-i {self.in_interface}")
if self.out_interface:
matches.append(f"-o {self.out_interface}")
return " ".join(matches)
def __str__(self) -> str:
return self.build()
def __bool__(self) -> bool:
return any([self.protocol, self.source_host, self.source_port, self.destination_host, self.destination_port,
self.in_interface, self.out_interface])
@dataclasses.dataclass(frozen=True)
class Target:
target: Targets
parameters: List[Tuple[str, str]] = dataclasses.field(default_factory=list)
def build(self) -> str:
parameters = []
for argument, value in self.parameters:
if value:
parameters.append(f"--{argument} {value}")
else:
parameters.append(f"--{argument}")
if parameters:
return f"-j {self.target} {' '.join(parameters)}"
else:
return f"-j {self.target}"
def __str__(self) -> str:
return self.build()
def _get_value(value: Union[Enum, str]) -> str:
if isinstance(value, Enum):
return value.value
else:
return value
class IPTablesRule:
def __init__(
self,
*,
table: Tables = Tables.FILTER,
chain: Optional[Union[str, Chains]] = None,
action: Optional[Actions] = None,
target: Optional[Target] = None,
flags: Flags = Flags(),
matches: Matches = Matches(),
) -> None:
self._table = table
self._chain = chain
self._action = action
self._target = target
self._flags = flags
self._matches = matches
self._modules = []
# region base
def table(self, table: Tables) -> Self:
self._table = table
return self
def chain(self, chain: Union[str, Chains]) -> Self:
self._chain = chain
return self
def action(self, action: Actions) -> Self:
self._action = action
return self
def target(self, target: Target) -> Self:
self._target = target
return self
# endregion
# region actions
def append(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.APPEND
if chain:
self._chain = chain
return self
def delete(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.DELETE
if chain:
self._chain = chain
return self
def insert(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.INSERT
if chain:
self._chain = chain
return self
def replace(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.REPLACE
if chain:
self._chain = chain
return self
def check(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.CHECK
if chain:
self._chain = chain
return self
def list(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.LIST
if chain:
self._chain = chain
return self
def flush(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.FLUSH
if chain:
self._chain = chain
return self
def zero(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.ZERO
if chain:
self._chain = chain
return self
def new_chain(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.NEW_CHAIN
if chain:
self._chain = chain
return self
def delete_chain(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.DELETE_CHAIN
if chain:
self._chain = chain
return self
def rename_chain(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.RENAME_CHAIN
if chain:
self._chain = chain
return self
def policy(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.POLICY
if chain:
self._chain = chain
return self
def list_rules(self, chain: Optional[Union[str, Chains]]) -> Self:
self._action = Actions.LIST_RULES
if chain:
self._chain = chain
return self
# endregion
# region flags
def ipv4(self, enable: bool = True) -> Self:
self._flags = dataclasses.replace(self._flags, ipv4=enable, ipv6=not enable)
return self
def ipv6(self, enable: bool = True) -> Self:
self._flags = dataclasses.replace(self._flags, ipv6=enable, ipv4=not enable)
return self
def fragment(self, enable: bool = True) -> Self:
self._flags = dataclasses.replace(self._flags, fragment=enable)
return self
def lock(self, enable: bool = True) -> Self:
self._flags = dataclasses.replace(self._flags, lock=enable)
return self
def verbose(self, enable: bool = True) -> Self:
self._flags = dataclasses.replace(self._flags, verbose=enable)
return self
def resolve(self, enable: bool = True) -> Self:
self._flags = dataclasses.replace(self._flags, resolve=enable)
return self
def exact(self, enable: bool = True) -> Self:
self._flags = dataclasses.replace(self._flags, exact=enable)
return self
# endregion
# region matches
def protocol(self, protocol: Protocols) -> Self:
self._matches = dataclasses.replace(self._matches, protocol=protocol)
return self
def p(self, protocol: Protocols) -> Self:
return self.protocol(protocol)
def source(self, host: str, port: int) -> Self:
self.source_host(host).source_port(port)
return self
def source_host(self, source_host: str) -> Self:
self._matches = dataclasses.replace(self._matches, source_host=source_host)
return self
def src(self, source_host: str) -> Self:
return self.source_host(source_host)
def s(self, source_host: str) -> Self:
return self.source_host(source_host)
def source_port(self, source_port: int) -> Self:
self._matches = dataclasses.replace(self._matches, source_port=source_port)
return self
def sport(self, source_port: int) -> Self:
return self.source_port(source_port)
def destination(self, host: str, port: int) -> Self:
self.destination_host(host).destination_port(port)
return self
def destination_host(self, destination_host: str) -> Self:
self._matches = dataclasses.replace(self._matches, destination_host=destination_host)
return self
def dst(self, destination_host: str) -> Self:
return self.destination_host(destination_host)
def d(self, destination_host: str) -> Self:
return self.destination_host(destination_host)
def destination_port(self, destination_port: int) -> Self:
self._matches = dataclasses.replace(self._matches, destination_port=destination_port)
return self
def dport(self, destination_port: int) -> Self:
return self.destination_port(destination_port)
def in_interface(self, in_interface: str) -> Self:
self._matches = dataclasses.replace(self._matches, in_interface=in_interface)
return self
def i(self, in_interface: str) -> Self:
return self.in_interface(in_interface)
def out_interface(self, out_interface: str) -> Self:
self._matches = dataclasses.replace(self._matches, out_interface=out_interface)
return self
def o(self, out_interface: str) -> Self:
return self.out_interface(out_interface)
# endregion
# region modules
# TODO: missing: dccp, addrtype, ah, bpf, cgroup, cluster, devgroup, dscp, dst, ecn,
# esp, eui64, frag, hashlimit, hbh, helper, hl, icmp, icmp6, iprange, ipv6header, ipvs, length, mh, nfacct, osf,
# owner, physdev, pkttype, policty, qouta, rateest, realm, recent, rpfilter, rt, sctp, set, socket, statistics,
# tcpmss, time, tos, ttl, u32
def comment(self, comment: str) -> Self:
self._modules.append(Module(module="comment", parameters=[("comment", f'"{comment}"')]))
return self
def connbytes(self, connbytes: str, mode: ConnbytesMode, direction: ConnbytesDirection) -> Self:
if not re.match("\d*:\d*", connbytes):
raise ConnbytesError
self._modules.append(Module(module="connbytes", parameters=[("connbytes", connbytes), ("connbytes-mode", mode),
("connbytes-dir", direction)]))
return self
def connlimit(
self,
upto: Optional[int] = None,
above: Optional[int] = None,
mask: Optional[int] = None,
sadder: bool = True,
daddr: bool = False
) -> Self:
if sadder and daddr:
raise ConnlimitAddrError
parameters = []
if upto:
parameters.append(("connlimit-upto", str(upto)))
if above:
parameters.append(("connlimit-above", str(above)))
if mask:
parameters.append(("connlimit-mask", str(mask)))
if sadder:
parameters.append(("connlimit-saddr", None))
if daddr:
parameters.append(("connlimit-daddr", None))
self._modules.append(Module(module="connlimit", parameters=parameters))
return self
def connmark(self, mark: int, mask: Optional[int] = None) -> Self:
if mask:
parameters = [("mark", f"{mark}/{mask}")]
else:
parameters = [("mark", mark)]
self._modules.append(Module(module="connmark", parameters=parameters))
return self
def conntrack(
self,
*,
state: Optional[List[ConntrackStates]] = None,
status: Optional[List[ConntrackStatus]] = None,
protocol: Optional[Protocols] = None,
original_source: Optional[str] = None,
original_source_port: Optional[int] = None,
original_destination: Optional[str] = None,
original_destination_port: Optional[int] = None,
reply_source: Optional[str] = None,
reply_source_port: Optional[int] = None,
reply_destination: Optional[str] = None,
reply_destination_port: Optional[int] = None,
expire: Optional[int] = None,
direction: Optional[ConntrackDirection] = None,
) -> Self:
parameters = []
if state:
parameters.append(("ctstate", ",".join(state)))
if status:
parameters.append(("ctstatus", ",".join(status)))
if protocol:
parameters.append(("ctproto", protocol))
if original_source:
parameters.append(("ctorigsrc", original_source))
if original_source_port:
parameters.append(("ctorigsrcport", original_source_port))
if original_destination:
parameters.append(("ctorigdst", original_destination))
if original_destination_port:
parameters.append(("ctorigdstport", original_destination_port))
if reply_source:
parameters.append(("ctreplsrc", reply_source))
if reply_source_port:
parameters.append(("ctreplsrcport", reply_source_port))
if reply_destination:
parameters.append(("ctrepldst", reply_destination))
if reply_destination_port:
parameters.append(("ctrepldstport", reply_destination_port))
if expire:
parameters.append(("ctexpire", expire))
if direction:
parameters.append(("ctdir", direction))
self._modules.append(Module(module="conntrack", parameters=parameters))
return self
def cpu(self, cpu: int) -> Self:
self._modules.append(Module(module="cpu", parameters=[("cpu", str(cpu))]))
return self
def limit(self, rate: int = 3, units: LimitUnits = LimitUnits.HOUR, burst: int = 5) -> Self:
self._modules.append(Module(module="limit", parameters=[("limit", f"{rate}/{units}"), ("limit-burst", burst)]))
return self
def mac(self, mac: str) -> Self:
self._modules.append(Module(module="mac", parameters=[("mac-source", mac)]))
return self
def mark(self, mark: int, mask: Optional[int] = None) -> Self:
if mask:
parameters = [("mark", f"{mark}/{mask}")]
else:
parameters = [("mark", mark)]
self._modules.append(Module(module="mark", parameters=parameters))
return self
def multiport(
self,
source_ports: Optional[List[Union[int, str]]] = None,
destination_ports: Optional[List[Union[int, str]]] = None,
ports: Optional[List[Union[int, str]]] = None
) -> Self:
if source_ports and destination_ports: | raise MultiportSourceAndDestinationError | 18 | 2023-12-17 17:00:49+00:00 | 8k |
daihaojun554/biliscrapy | biliscrapy/views.py | [
{
"identifier": "BiliDanmu",
"path": "biliscrapy/models.py",
"snippet": "class BiliDanmu(models.Model):\n _id = models.CharField(max_length=255)\n cid = models.CharField(max_length=255)\n content = models.TextField()\n color = models.CharField(max_length=255)\n fontsize = models.IntegerFi... | import time
from django.core.paginator import Paginator
from django.shortcuts import render, redirect
from django.utils.timezone import make_aware
from .models import BiliDanmu, BiliComment, BiliVideo, Card
from .network.bilibili_danmu import *
from .network.bilibili_comment import Comments
from .network.bilibili_utils import bili_utils
from .network.bilibili_video import Video
from django.utils import timezone
from django.http import JsonResponse, HttpResponse | 6,062 | context = {
'result': 'error',
'data': [],
'message': '请输入正确的链接地址或BV号!'
}
if bv.startswith("https://www.bilibili.com/video/BV") or bv.startswith("BV") or bv.startswith("bv"):
danmu = Danmu()
vv = BiliVideo.objects.filter(bvid=bvid).values()
cid = vv[0]['oid'] if vv else danmu.bv2cid(bv)
bvid_exists = BiliDanmu.objects.filter(cid=cid).exists()
if not bvid_exists:
logger.info("bvid_exists,不存在!!!")
dates = danmu.get_available_dates(cid) # 获取视频的所有日期列表
danmu.down_so_files(cid, dates) # 下载所有弹ci幕文件
unique_danmakus = danmu.parse_so_to_json(cid, dates) # 解析并保存为 JSON 文件
if unique_danmakus is None:
return render(request, 'danmaku.html',
context.update({'message': '解析弹幕失败,请检查BV号是否正确!'}))
danmu_objects = [
BiliDanmu(
_id=danmaku['_id'],
cid=cid,
content=danmaku['content'],
color=danmaku['color'],
fontsize=danmaku['fontsize'],
midHash=danmaku['midHash'],
mode=danmaku['mode'],
progress=danmaku['progress'],
ctime=make_aware(datetime.fromtimestamp(danmaku['ctime']))
)
for danmaku in unique_danmakus
]
BiliDanmu.objects.bulk_create(danmu_objects)
# 不存在 弹幕信息
danmaku_count = BiliDanmu.objects.filter(cid=cid).count()
print(danmaku_count)
try:
logger.info("try.....")
# 尝试更新视频的抓取弹幕的状态
logger.info(bvid)
video = BiliVideo.objects.get(bvid=bvid)
video.danmu_fetched = True
video.danmaku_count = danmaku_count
video.save()
except Exception as e:
logger.error("error~~~~~~~~~")
logger.error(e)
# 如果视频记录不存在,则创建新的视频记录
info = utils.get_info_by_bv(bvid)
logger.info("info---->{}".format(info))
if info is None:
return render(request, 'danmaku.html', context)
cid = utils.bv2cid(bvid)
logger.info(f'{cid}, cid')
video = BiliVideo(bvid=bvid,
avid=info['aid'],
oid=cid,
title=info['title'],
author=info['owner']['name'],
tag=info['tname'],
pubdate=make_aware(datetime.fromtimestamp(info['pubdate'])),
pic=info['pic'],
desc=info['desc'],
danmu_fetched=True,
danmaku_count=danmaku_count
) # 设置弹幕抓取状态
video.save()
logger.info("新视频信息已添加")
# 查询数据库并返回结果
# 查询数据库并返回结果
danmakus = BiliDanmu.objects.filter(cid=cid).values().order_by('ctime')
paginator = Paginator(danmakus, 15) # 每页显示10条记录
page_number = request.POST.get('page') if request.POST.get('page') else 1 # 获取页码参数
page_obj = paginator.get_page(page_number) # 获取对应页码的数据
print(paginator.count)
context = {
"url": url,
'result': 'error',
'bvid': bv,
'total': paginator.count,
'data': page_obj,
'new_request': not bvid_exists,
}
if len(danmakus) > 0:
context['result'] = 'success'
return render(request, 'danmaku.html', context)
return render(request, 'danmaku.html')
def comment(request):
if request.method == 'POST':
bv = request.POST.get('bv') # 获取用户输入的 BV 号或链接
url = bv
context = {
'result': 'error',
'data': [],
'message': '请输入正确的链接地址或BV号!',
'cid': ''
}
c = Comments()
bv_ = utils.bv_get(bv) if bv.startswith("https://www.bilibili.com/video/BV") or bv.startswith(
"BV") or bv.startswith("bv") else bv
logger.info(f'bv_====>{bv_}')
vv = BiliVideo.objects.filter(bvid=bv_).values()
# logger.info(vv[0]['avid'], 'sadjkaskjadssajasjdsjkaaashhakads')
av = utils.bv2av(bv_)
av_count = 1
while av is None:
logger.info(f"av is None, retrying...{av_count}")
av_count += 1
av = utils.bv2av(bv_)
avid = vv[0]['avid'] if vv else av
logger.info(f"avid=====>{avid}")
if avid is None:
context = {
'result': 'error',
'data': [],
'message': 'b站服务器返回错误,请重新尝试'
}
return render(request, 'comment.html', context)
|
# Create your views here.
utils = bili_utils()
bili_video = Video()
logger = logging.getLogger('log')
base_url = 'https://www.bilibili.com/video/'
def danmaku(request):
if request.method == 'POST':
bv = request.POST.get('bv') # 获取用户输入的 BV 号或链接
bvid = utils.bv_get(bv)
url = bv
context = {
'result': 'error',
'data': [],
'message': '请输入正确的链接地址或BV号!'
}
if bv.startswith("https://www.bilibili.com/video/BV") or bv.startswith("BV") or bv.startswith("bv"):
danmu = Danmu()
vv = BiliVideo.objects.filter(bvid=bvid).values()
cid = vv[0]['oid'] if vv else danmu.bv2cid(bv)
bvid_exists = BiliDanmu.objects.filter(cid=cid).exists()
if not bvid_exists:
logger.info("bvid_exists,不存在!!!")
dates = danmu.get_available_dates(cid) # 获取视频的所有日期列表
danmu.down_so_files(cid, dates) # 下载所有弹ci幕文件
unique_danmakus = danmu.parse_so_to_json(cid, dates) # 解析并保存为 JSON 文件
if unique_danmakus is None:
return render(request, 'danmaku.html',
context.update({'message': '解析弹幕失败,请检查BV号是否正确!'}))
danmu_objects = [
BiliDanmu(
_id=danmaku['_id'],
cid=cid,
content=danmaku['content'],
color=danmaku['color'],
fontsize=danmaku['fontsize'],
midHash=danmaku['midHash'],
mode=danmaku['mode'],
progress=danmaku['progress'],
ctime=make_aware(datetime.fromtimestamp(danmaku['ctime']))
)
for danmaku in unique_danmakus
]
BiliDanmu.objects.bulk_create(danmu_objects)
# 不存在 弹幕信息
danmaku_count = BiliDanmu.objects.filter(cid=cid).count()
print(danmaku_count)
try:
logger.info("try.....")
# 尝试更新视频的抓取弹幕的状态
logger.info(bvid)
video = BiliVideo.objects.get(bvid=bvid)
video.danmu_fetched = True
video.danmaku_count = danmaku_count
video.save()
except Exception as e:
logger.error("error~~~~~~~~~")
logger.error(e)
# 如果视频记录不存在,则创建新的视频记录
info = utils.get_info_by_bv(bvid)
logger.info("info---->{}".format(info))
if info is None:
return render(request, 'danmaku.html', context)
cid = utils.bv2cid(bvid)
logger.info(f'{cid}, cid')
video = BiliVideo(bvid=bvid,
avid=info['aid'],
oid=cid,
title=info['title'],
author=info['owner']['name'],
tag=info['tname'],
pubdate=make_aware(datetime.fromtimestamp(info['pubdate'])),
pic=info['pic'],
desc=info['desc'],
danmu_fetched=True,
danmaku_count=danmaku_count
) # 设置弹幕抓取状态
video.save()
logger.info("新视频信息已添加")
# 查询数据库并返回结果
# 查询数据库并返回结果
danmakus = BiliDanmu.objects.filter(cid=cid).values().order_by('ctime')
paginator = Paginator(danmakus, 15) # 每页显示10条记录
page_number = request.POST.get('page') if request.POST.get('page') else 1 # 获取页码参数
page_obj = paginator.get_page(page_number) # 获取对应页码的数据
print(paginator.count)
context = {
"url": url,
'result': 'error',
'bvid': bv,
'total': paginator.count,
'data': page_obj,
'new_request': not bvid_exists,
}
if len(danmakus) > 0:
context['result'] = 'success'
return render(request, 'danmaku.html', context)
return render(request, 'danmaku.html')
def comment(request):
if request.method == 'POST':
bv = request.POST.get('bv') # 获取用户输入的 BV 号或链接
url = bv
context = {
'result': 'error',
'data': [],
'message': '请输入正确的链接地址或BV号!',
'cid': ''
}
c = Comments()
bv_ = utils.bv_get(bv) if bv.startswith("https://www.bilibili.com/video/BV") or bv.startswith(
"BV") or bv.startswith("bv") else bv
logger.info(f'bv_====>{bv_}')
vv = BiliVideo.objects.filter(bvid=bv_).values()
# logger.info(vv[0]['avid'], 'sadjkaskjadssajasjdsjkaaashhakads')
av = utils.bv2av(bv_)
av_count = 1
while av is None:
logger.info(f"av is None, retrying...{av_count}")
av_count += 1
av = utils.bv2av(bv_)
avid = vv[0]['avid'] if vv else av
logger.info(f"avid=====>{avid}")
if avid is None:
context = {
'result': 'error',
'data': [],
'message': 'b站服务器返回错误,请重新尝试'
}
return render(request, 'comment.html', context) | comments_exist = BiliComment.objects.filter(avid=avid).exists() | 1 | 2023-12-14 10:14:24+00:00 | 8k |
mjavadpur/Sadtalker_LongVideos | src/facerender/modules/generator.py | [
{
"identifier": "ResBlock2d",
"path": "src/facerender/modules/util.py",
"snippet": "class ResBlock2d(nn.Module):\n \"\"\"\n Res block, preserve spatial resolution.\n \"\"\"\n\n def __init__(self, in_features, kernel_size, padding):\n super(ResBlock2d, self).__init__()\n self.co... | import torch
import torch.nn.functional as F
from torch import nn
from src.facerender.modules.util import ResBlock2d, SameBlock2d, UpBlock2d, DownBlock2d, ResBlock3d, SPADEResnetBlock
from src.facerender.modules.dense_motion import DenseMotionNetwork | 4,623 | """
Generator follows NVIDIA architecture.
"""
def __init__(self, image_channel, feature_channel, num_kp, block_expansion, max_features, num_down_blocks, reshape_channel, reshape_depth,
num_resblocks, estimate_occlusion_map=False, dense_motion_params=None, estimate_jacobian=False):
super(OcclusionAwareGenerator, self).__init__()
if dense_motion_params is not None:
self.dense_motion_network = DenseMotionNetwork(num_kp=num_kp, feature_channel=feature_channel,
estimate_occlusion_map=estimate_occlusion_map,
**dense_motion_params)
else:
self.dense_motion_network = None
self.first = SameBlock2d(image_channel, block_expansion, kernel_size=(7, 7), padding=(3, 3))
down_blocks = []
for i in range(num_down_blocks):
in_features = min(max_features, block_expansion * (2 ** i))
out_features = min(max_features, block_expansion * (2 ** (i + 1)))
down_blocks.append(DownBlock2d(in_features, out_features, kernel_size=(3, 3), padding=(1, 1)))
self.down_blocks = nn.ModuleList(down_blocks)
self.second = nn.Conv2d(in_channels=out_features, out_channels=max_features, kernel_size=1, stride=1)
self.reshape_channel = reshape_channel
self.reshape_depth = reshape_depth
self.resblocks_3d = torch.nn.Sequential()
for i in range(num_resblocks):
self.resblocks_3d.add_module('3dr' + str(i), ResBlock3d(reshape_channel, kernel_size=3, padding=1))
out_features = block_expansion * (2 ** (num_down_blocks))
self.third = SameBlock2d(max_features, out_features, kernel_size=(3, 3), padding=(1, 1), lrelu=True)
self.fourth = nn.Conv2d(in_channels=out_features, out_channels=out_features, kernel_size=1, stride=1)
self.resblocks_2d = torch.nn.Sequential()
for i in range(num_resblocks):
self.resblocks_2d.add_module('2dr' + str(i), ResBlock2d(out_features, kernel_size=3, padding=1))
up_blocks = []
for i in range(num_down_blocks):
in_features = max(block_expansion, block_expansion * (2 ** (num_down_blocks - i)))
out_features = max(block_expansion, block_expansion * (2 ** (num_down_blocks - i - 1)))
up_blocks.append(UpBlock2d(in_features, out_features, kernel_size=(3, 3), padding=(1, 1)))
self.up_blocks = nn.ModuleList(up_blocks)
self.final = nn.Conv2d(block_expansion, image_channel, kernel_size=(7, 7), padding=(3, 3))
self.estimate_occlusion_map = estimate_occlusion_map
self.image_channel = image_channel
def deform_input(self, inp, deformation):
_, d_old, h_old, w_old, _ = deformation.shape
_, _, d, h, w = inp.shape
if d_old != d or h_old != h or w_old != w:
deformation = deformation.permute(0, 4, 1, 2, 3)
deformation = F.interpolate(deformation, size=(d, h, w), mode='trilinear')
deformation = deformation.permute(0, 2, 3, 4, 1)
return F.grid_sample(inp, deformation)
def forward(self, source_image, kp_driving, kp_source):
# Encoding (downsampling) part
out = self.first(source_image)
for i in range(len(self.down_blocks)):
out = self.down_blocks[i](out)
out = self.second(out)
bs, c, h, w = out.shape
# print(out.shape)
feature_3d = out.view(bs, self.reshape_channel, self.reshape_depth, h ,w)
feature_3d = self.resblocks_3d(feature_3d)
# Transforming feature representation according to deformation and occlusion
output_dict = {}
if self.dense_motion_network is not None:
dense_motion = self.dense_motion_network(feature=feature_3d, kp_driving=kp_driving,
kp_source=kp_source)
output_dict['mask'] = dense_motion['mask']
if 'occlusion_map' in dense_motion:
occlusion_map = dense_motion['occlusion_map']
output_dict['occlusion_map'] = occlusion_map
else:
occlusion_map = None
deformation = dense_motion['deformation']
out = self.deform_input(feature_3d, deformation)
bs, c, d, h, w = out.shape
out = out.view(bs, c*d, h, w)
out = self.third(out)
out = self.fourth(out)
if occlusion_map is not None:
if out.shape[2] != occlusion_map.shape[2] or out.shape[3] != occlusion_map.shape[3]:
occlusion_map = F.interpolate(occlusion_map, size=out.shape[2:], mode='bilinear')
out = out * occlusion_map
# output_dict["deformed"] = self.deform_input(source_image, deformation) # 3d deformation cannot deform 2d image
# Decoding part
out = self.resblocks_2d(out)
for i in range(len(self.up_blocks)):
out = self.up_blocks[i](out)
out = self.final(out)
out = F.sigmoid(out)
output_dict["prediction"] = out
return output_dict
class SPADEDecoder(nn.Module):
def __init__(self):
super().__init__()
ic = 256
oc = 64
norm_G = 'spadespectralinstance'
label_nc = 256
self.fc = nn.Conv2d(ic, 2 * ic, 3, padding=1)
|
class OcclusionAwareGenerator(nn.Module):
"""
Generator follows NVIDIA architecture.
"""
def __init__(self, image_channel, feature_channel, num_kp, block_expansion, max_features, num_down_blocks, reshape_channel, reshape_depth,
num_resblocks, estimate_occlusion_map=False, dense_motion_params=None, estimate_jacobian=False):
super(OcclusionAwareGenerator, self).__init__()
if dense_motion_params is not None:
self.dense_motion_network = DenseMotionNetwork(num_kp=num_kp, feature_channel=feature_channel,
estimate_occlusion_map=estimate_occlusion_map,
**dense_motion_params)
else:
self.dense_motion_network = None
self.first = SameBlock2d(image_channel, block_expansion, kernel_size=(7, 7), padding=(3, 3))
down_blocks = []
for i in range(num_down_blocks):
in_features = min(max_features, block_expansion * (2 ** i))
out_features = min(max_features, block_expansion * (2 ** (i + 1)))
down_blocks.append(DownBlock2d(in_features, out_features, kernel_size=(3, 3), padding=(1, 1)))
self.down_blocks = nn.ModuleList(down_blocks)
self.second = nn.Conv2d(in_channels=out_features, out_channels=max_features, kernel_size=1, stride=1)
self.reshape_channel = reshape_channel
self.reshape_depth = reshape_depth
self.resblocks_3d = torch.nn.Sequential()
for i in range(num_resblocks):
self.resblocks_3d.add_module('3dr' + str(i), ResBlock3d(reshape_channel, kernel_size=3, padding=1))
out_features = block_expansion * (2 ** (num_down_blocks))
self.third = SameBlock2d(max_features, out_features, kernel_size=(3, 3), padding=(1, 1), lrelu=True)
self.fourth = nn.Conv2d(in_channels=out_features, out_channels=out_features, kernel_size=1, stride=1)
self.resblocks_2d = torch.nn.Sequential()
for i in range(num_resblocks):
self.resblocks_2d.add_module('2dr' + str(i), ResBlock2d(out_features, kernel_size=3, padding=1))
up_blocks = []
for i in range(num_down_blocks):
in_features = max(block_expansion, block_expansion * (2 ** (num_down_blocks - i)))
out_features = max(block_expansion, block_expansion * (2 ** (num_down_blocks - i - 1)))
up_blocks.append(UpBlock2d(in_features, out_features, kernel_size=(3, 3), padding=(1, 1)))
self.up_blocks = nn.ModuleList(up_blocks)
self.final = nn.Conv2d(block_expansion, image_channel, kernel_size=(7, 7), padding=(3, 3))
self.estimate_occlusion_map = estimate_occlusion_map
self.image_channel = image_channel
def deform_input(self, inp, deformation):
_, d_old, h_old, w_old, _ = deformation.shape
_, _, d, h, w = inp.shape
if d_old != d or h_old != h or w_old != w:
deformation = deformation.permute(0, 4, 1, 2, 3)
deformation = F.interpolate(deformation, size=(d, h, w), mode='trilinear')
deformation = deformation.permute(0, 2, 3, 4, 1)
return F.grid_sample(inp, deformation)
def forward(self, source_image, kp_driving, kp_source):
# Encoding (downsampling) part
out = self.first(source_image)
for i in range(len(self.down_blocks)):
out = self.down_blocks[i](out)
out = self.second(out)
bs, c, h, w = out.shape
# print(out.shape)
feature_3d = out.view(bs, self.reshape_channel, self.reshape_depth, h ,w)
feature_3d = self.resblocks_3d(feature_3d)
# Transforming feature representation according to deformation and occlusion
output_dict = {}
if self.dense_motion_network is not None:
dense_motion = self.dense_motion_network(feature=feature_3d, kp_driving=kp_driving,
kp_source=kp_source)
output_dict['mask'] = dense_motion['mask']
if 'occlusion_map' in dense_motion:
occlusion_map = dense_motion['occlusion_map']
output_dict['occlusion_map'] = occlusion_map
else:
occlusion_map = None
deformation = dense_motion['deformation']
out = self.deform_input(feature_3d, deformation)
bs, c, d, h, w = out.shape
out = out.view(bs, c*d, h, w)
out = self.third(out)
out = self.fourth(out)
if occlusion_map is not None:
if out.shape[2] != occlusion_map.shape[2] or out.shape[3] != occlusion_map.shape[3]:
occlusion_map = F.interpolate(occlusion_map, size=out.shape[2:], mode='bilinear')
out = out * occlusion_map
# output_dict["deformed"] = self.deform_input(source_image, deformation) # 3d deformation cannot deform 2d image
# Decoding part
out = self.resblocks_2d(out)
for i in range(len(self.up_blocks)):
out = self.up_blocks[i](out)
out = self.final(out)
out = F.sigmoid(out)
output_dict["prediction"] = out
return output_dict
class SPADEDecoder(nn.Module):
def __init__(self):
super().__init__()
ic = 256
oc = 64
norm_G = 'spadespectralinstance'
label_nc = 256
self.fc = nn.Conv2d(ic, 2 * ic, 3, padding=1) | self.G_middle_0 = SPADEResnetBlock(2 * ic, 2 * ic, norm_G, label_nc) | 5 | 2023-12-19 11:01:35+00:00 | 8k |
Westlake-geeks/bilibili-livestream-slicer | main.py | [
{
"identifier": "is_live",
"path": "api.py",
"snippet": "def is_live(uid):\n live_api = \"https://api.live.bilibili.com/room/v1/Room/room_init?id=%s\" % str(\n uid)\n rtn = my_request(live_api)\n data_dict = json.loads(rtn)\n\n data_value = data_dict.get('data')\n live_status_value... | import os
import json
import traceback
import sys
import re
import streamlink
import threading
import requests
import time
import datetime
import urllib
import socket
from api import is_live, get_stream_url, get_name, my_request
from urllib import request
| 3,682 |
socket.setdefaulttimeout(5.0)
def record(real_url, file_name, headers):
if not real_url:
return
res = None
try:
with urllib.request.urlopen(urllib.request.Request(real_url, headers=headers)) as response:
size = 0
with open(file_name, 'wb') as f:
print('starting download from:\n%s\nto:\n%s' %
(real_url, file_name))
chunk_size = 64*1024
while True:
chunk = response.read(chunk_size)
if not chunk:
print('连接中断')
break
f.write(chunk)
#size += len(chunk)
#print('{:<4.2f} MB downloaded'.format(
# size/1024/1024), datetime.datetime.now(), end="\r")
except Exception as e:
print("=============================")
print(e)
print("=============================")
finally:
print("finnally")
if res:
res.close()
print("res.close()")
if os.path.isfile(file_name) and os.path.getsize(file_name) == 0:
os.remove(file_name)
print("os.remove(file_name)")
def __main__(id,filename):
#conf = json.load(open("_config.json"))
_id = id
_name = get_name(int(_id))
_path = "videos/"
if not os.path.exists(_path):
raise "path not exists"
while 1:
try:
live_status = is_live(int(_id))
print('live_status:', live_status)
except Exception as e:
print(e)
continue
if live_status == False:
print("[%s]未开播" % _id, datetime.datetime.now(), end="\r")
time.sleep(5)
pass
else:
# send_wechat_notification(_name+' '+'标题占位', '直播链接占位00000')
try:
|
socket.setdefaulttimeout(5.0)
def record(real_url, file_name, headers):
if not real_url:
return
res = None
try:
with urllib.request.urlopen(urllib.request.Request(real_url, headers=headers)) as response:
size = 0
with open(file_name, 'wb') as f:
print('starting download from:\n%s\nto:\n%s' %
(real_url, file_name))
chunk_size = 64*1024
while True:
chunk = response.read(chunk_size)
if not chunk:
print('连接中断')
break
f.write(chunk)
#size += len(chunk)
#print('{:<4.2f} MB downloaded'.format(
# size/1024/1024), datetime.datetime.now(), end="\r")
except Exception as e:
print("=============================")
print(e)
print("=============================")
finally:
print("finnally")
if res:
res.close()
print("res.close()")
if os.path.isfile(file_name) and os.path.getsize(file_name) == 0:
os.remove(file_name)
print("os.remove(file_name)")
def __main__(id,filename):
#conf = json.load(open("_config.json"))
_id = id
_name = get_name(int(_id))
_path = "videos/"
if not os.path.exists(_path):
raise "path not exists"
while 1:
try:
live_status = is_live(int(_id))
print('live_status:', live_status)
except Exception as e:
print(e)
continue
if live_status == False:
print("[%s]未开播" % _id, datetime.datetime.now(), end="\r")
time.sleep(5)
pass
else:
# send_wechat_notification(_name+' '+'标题占位', '直播链接占位00000')
try:
| stream_url, headers = get_stream_url(_id)
| 1 | 2023-12-16 17:08:02+00:00 | 8k |
Angryrou/udao | udao/optimization/moo/progressive_frontier/parallel_progressive_frontier.py | [
{
"identifier": "logger",
"path": "udao/utils/logging.py",
"snippet": "def _get_logger(name: str = \"udao\", level: int = logging.DEBUG) -> logging.Logger:"
},
{
"identifier": "Objective",
"path": "udao/optimization/concepts/objective.py",
"snippet": "class Objective(Constraint):\n \"... | import itertools
import numpy as np
import torch as th
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
from torch.multiprocessing import Pool
from ....utils.logging import logger
from ...concepts import MOProblem, Objective, SOProblem
from ...soo.so_solver import SOSolver
from ...utils import moo_utils as moo_ut
from ...utils.exceptions import NoSolutionError
from ...utils.moo_utils import Point, Rectangle
from .base_progressive_frontier import BaseProgressiveFrontier | 3,922 |
class ParallelProgressiveFrontier(BaseProgressiveFrontier):
@dataclass
class Params(BaseProgressiveFrontier.Params):
processes: int = 1
"""Processes to use for parallel processing"""
n_grids: int = 2
"""Number of splits per objective"""
max_iters: int = 10
"""Number of iterations to explore the space"""
def __init__(
self,
|
class ParallelProgressiveFrontier(BaseProgressiveFrontier):
@dataclass
class Params(BaseProgressiveFrontier.Params):
processes: int = 1
"""Processes to use for parallel processing"""
n_grids: int = 2
"""Number of splits per objective"""
max_iters: int = 10
"""Number of iterations to explore the space"""
def __init__(
self, | solver: SOSolver, | 4 | 2023-12-20 09:10:42+00:00 | 8k |
XLearning-SCU/2023-TPAMI-SMILE | _Utils/VisualQ2.py | [
{
"identifier": "Queue",
"path": "_MainLauncher.py",
"snippet": "def get_settings():\r\ndef clear_gpu_fail(root):\r\ndef run():\r\ndef main():\r"
},
{
"identifier": "get_nearest_k",
"path": "_Utils/Calculator.py",
"snippet": "def get_nearest_k(h0, h1, k=1, sp_size=1000):\r\n hh0 = h0.... | import numpy as np
import pandas as pd
import torch
from matplotlib import pyplot as plt
from sklearn.manifold import TSNE
from _MainLauncher import Queue
from _Utils.Calculator import get_nearest_k
from _Utils.Scatter import visualize_scatter, visualize2
from _Utils.Visualize import plot_heat_map, visualize_plot
| 5,037 | # plt.text(j, i, z[i, j], ha="center", va="center")
plt.imshow(z, interpolation='nearest', aspect='auto')
# plt.colorbar()
plt.axis('off')
# plt.subplots_adjust(top=0.957, bottom=0.081, left=0.108, right=0.977, hspace=0.2, wspace=0.2)
# plt.show()
plt.tight_layout()
plt.savefig(
figp,
transparent=True)
print()
if use_mx:
break
# def scatter():
# mx = False
# if mx:
# np_pth = 'D:/VirtualMachine/CheckPoints/MultiClustering/Repro/SURE/NoisyMNISTBoth.npz'
# data_f = np.load(np_pth, allow_pickle=False)
# feature_vec = data_f['feature_vec']
# type_vec = data_f['type_vec']
# group_vec = np.concatenate((np.zeros(30000), np.ones(30000)))
# else:
# np_pth = 'D:/Pengxin/Workplace/Codes/MultimodalityClustering/Np099.npz'
# data_f = np.load(np_pth, allow_pickle=False)
# feature_vec = data_f['feature_vec']
# type_vec = data_f['type_vec']
# group_vec = data_f['group_vec']
#
# sub_sample = 3000
# if len(feature_vec) > sub_sample * 2:
# ind = np.arange(int(len(feature_vec) // 2))
# np.random.shuffle(ind)
# ind = ind[:sub_sample]
# ind = np.concatenate((ind, ind + 30000))
# feature_vec = feature_vec[ind]
# group_vec = group_vec[ind]
# type_vec = type_vec[ind]
# # fv = feature_vec.reshape((len(feature_vec), -1))
# prefix = 'D:/Pengxin/Temp/mxF/'
# visualize2(feature_vec, type_vec, group_vec, None, prefix, )
#
# # for perplexity in [15,30]:
# # prefix = 'D:/Pengxin/Temp/mxF/P{}N{}'.format(perplexity, sub_sample)
# # vis_fea_multi = TSNE(perplexity=perplexity).fit_transform(
# # np.concatenate((fv[group_vec == 0], fv[group_vec == 1]), axis=1)
# # )
# # visualize_scatter(vis_fea_multi,
# # fig_path='{}Multi.{}'.format(prefix, post),
# # label_color=type_vec[group_vec == 0],
# # )
# #
# # vis_fea = TSNE(perplexity=perplexity).fit_transform(fv)
# #
# # visualize_scatter(vis_fea,
# # fig_path='{}Type.{}'.format(prefix, post),
# # label_color=type_vec,
# #
# # )
# # # visualize_scatter(vis_fea,
# # # fig_path='{}Cluster.svg'.format(prefix),
# # # label_color=pred_vec,
# # # label_shape=type_vec,
# # #
# # # )
# # visualize_scatter(vis_fea,
# # fig_path='{}Group.{}'.format(prefix, post),
# # label_color=group_vec,
# #
# # )
def plot_nrmse():
rs = pd.read_csv('D:/VirtualMachine/CheckPoints/MultiClustering/Repro/SMAIL/Recover/_Table_NRMSE_AVG_FuEp.csv')
# rs = pd.read_csv('/xlearning/pengxin/Codes/230318/IMvC_RunSet0405/_Table_NRMSE_AVG_FuEp.csv')
xx = []
yy = []
labels = []
spls = []
colors = []
for i, rec in enumerate(np.unique(rs.loc[:, 'Reconstruction'])):
if rec > 1:
continue
label = '$\mathcal{L}_{IsIL}@\lambda_{IsIL}$' + '={}'.format(rec)
rd = rs.loc[rs.loc[:, 'Reconstruction'] == rec]
x = rd.loc[:, 'Epoch']
y = rd.loc[:, 'loss_reconstruction_epoch']
xx.append(x)
yy.append(y)
labels.append(label)
spls.append('-')
colors.append('C{}'.format(i))
for i, rec in enumerate(np.unique(rs.loc[:, 'Reconstruction'])):
if rec > 1:
continue
label = '$NRMSE@\lambda_{IsIL}$' + '={}'.format(rec)
rd = rs.loc[rs.loc[:, 'Reconstruction'] == rec]
ind = pd.isna(rd.loc[:, 'rnmse0']).values != True
rd2 = rd.loc[ind]
ind = rd2.loc[:, 'Epoch'].values > 0
rd2 = rd2.loc[ind]
x = rd2.loc[:, 'Epoch']
y = rd2.loc[:, 'rnmse0']
xx.append(x)
yy.append(y)
labels.append(label)
spls.append('--')
colors.append('C{}'.format(i))
# np_pth = 'D:/VirtualMachine/CheckPoints/MultiClustering/Repro/SURE/nrmse_list.npz'
# data_f = np.load(np_pth, allow_pickle=True)
# data0 = np.asarray([it.cpu().numpy() for it in data_f['data0']])
# data1 = np.asarray([it.cpu().numpy() for it in data_f['data1']])
# y = (data1 + data0)/2
# x = np.arange(len(y))
# xx.append(x)
# yy.append(y)
# labels.append('SURE')
# spls.append('-.')
# colors.append('C{}'.format(6))
|
def confusion_matrix():
np_pth = 'D:/VirtualMachine/CheckPoints/MultiClustering/Repro/SMAIL/RaAlign/Base.npz'
data_mask_ispair = np.load(np_pth, allow_pickle=False)
mask = data_mask_ispair['mask']
use_mx = False
for ep in [59, 89, 119, 149]:
# for ep in [59, 89, 119]:
for tem in [50] if use_mx else [0.5]:
if not use_mx:
# 50A
# np_pth = 'D:/VirtualMachine/CheckPoints/MultiClustering/Repro/SMAIL/RaAlign/Np{:03d}.npz'.format(ep)
# is_pair = data_mask_ispair['is_pair_all']
# to_realign = np.logical_and(is_pair == 0, np.logical_and(mask[:, 1], mask[:, 0]))
# 100A
np_pth = 'D:/VirtualMachine/CheckPoints/MultiClustering/1014/RunSet1025_BenchSotaCI22/ --QuickConfig A100 --Rev 1 --dataset NoisyMNIST30000 --normalize_type sample_wise --seed 9116/NpPoints/Np{:03d}.npz'.format(
ep)
to_realign = np.ones_like(data_mask_ispair['is_pair_all'], dtype=bool)
data_f = np.load(np_pth, allow_pickle=False)
feature_vec = data_f['feature_vec']
type_vec = data_f['type_vec']
group_vec = data_f['group_vec']
pred_vec = data_f['pred_vec']
epoch = data_f['epoch']
type_vec = type_vec[group_vec == 0]
h1 = feature_vec[group_vec == 1]
h0 = feature_vec[group_vec == 0]
ha0 = h0[to_realign]
ha1 = h1[to_realign]
gt = type_vec[to_realign]
# ind = np.argsort(gt)
# ha0 = ha0[ind]
# ha1 = ha1[ind]
# gt = gt[ind]
# ha0[np.sum(ha0 ** 2, axis=1) == 0] = 1e-8
# ha1[np.sum(ha1 ** 2, axis=1) == 0] = 1e-8
# ha0 = ha0 / np.sqrt(np.sum(ha0 ** 2, axis=1, keepdims=True))
# ha1 = ha1 / np.sqrt(np.sum(ha1 ** 2, axis=1, keepdims=True))
sim = torch.from_numpy(ha0 @ ha1.T)
# ind_score = np.zeros(len(ha0))
# for y in np.unique(gt):
# cy = conf[y == gt][:, y == gt]
# cy = (cy + cy.T) / 2
# ind_score[y == gt] = np.mean(cy, axis=1) - 10 * y
# ind = np.argsort(ind_score)[::-1]
# tem = 0.2
else:
# np_pth = 'D:/VirtualMachine/CheckPoints/MultiClustering/Repro/SURE/NoisyMNIST50align.npz'
# data_f = np.load(np_pth, allow_pickle=False)
np_pth = 'D:/VirtualMachine/CheckPoints/MultiClustering/Repro/SURE/NoisyMNIST50align.npz'
data_f = np.load(np_pth, allow_pickle=False)
feature_vec = data_f['feature_vec']
is_pair = data_f['is_pair']
h0 = feature_vec[:30000]
h1 = feature_vec[30000:]
type_vec0 = data_f['type_vec'][:30000]
type_vec1 = data_f['type_vec'][30000:]
to_realign = is_pair == 0
epoch = 0
ha0 = h0[to_realign]
ha1 = h1[to_realign]
gt0 = type_vec0[to_realign]
gt1 = type_vec1[to_realign]
ind = np.argsort(gt0)
ha0 = ha0[ind]
gt0 = gt0[ind]
ind = np.argsort(gt1)
ha1 = ha1[ind]
gt1 = gt1[ind]
assert np.sum(gt0 != gt1) == 0
gt = gt1
sim = -torch.cdist(torch.from_numpy(ha0), torch.from_numpy(ha1))
# tem = 1
figp = 'D:/Pengxin/Temp/AlignConfusionE{:03d}T{:05.01f}{:}.svg'.format(epoch, tem, 'M' if use_mx else '')
print(figp)
# feature_vec = torch.from_numpy(feature_vec)
# # fv = torch.cat([fv[:30000], fv[30000:]], dim=1)
# prefix = 'D:/Pengxin/Temp/mxv/'
# group_vec = np.concatenate([np.zeros(30000, dtype=int), np.ones(30000, dtype=int)])
# type_vec = data_f['type_vec']
# sub_sample = 3000
# if len(feature_vec) > sub_sample * 2:
# ind = np.arange(int(len(feature_vec) // 2))
# np.random.shuffle(ind)
# ind = ind[:sub_sample]
# ind += 30000
# # ind = np.concatenate((ind, ind + int(len(feature_vec) // 2)))
# feature_vec = feature_vec[ind]
# group_vec = group_vec[ind]
# type_vec = type_vec[ind]
# visualize2(feature_vec, type_vec,
# group_vec,
# None,
# prefix,
# )
sas01 = torch.softmax(sim / tem, dim=1)
sas10 = torch.softmax(sim / tem, dim=0)
sas = ((sas01 + sas10) / 2).numpy()
realign_y = gt[torch.argmax(sas01, dim=1)]
realign_gt = gt
acc = np.round(np.sum(realign_y == realign_gt) / len(realign_y) * 100, decimals=1)
print(acc)
continue
# break
# ind_score = np.zeros(len(ha0))
# for y in np.unique(gt):
# cy = sas[y == gt][:, y == gt]
# ind_score[y == gt] = np.mean(cy, axis=1) - 10 * y
# ind = np.argsort(ind_score)[::-1]
# conf = sas[ind][:, ind]
ind_score = np.zeros(len(ha0))
for y in np.unique(gt):
cy = sas[y == gt][:, y == gt]
ind_score[y == gt] = np.mean(cy, axis=1) - 10 * y
ind = np.argsort(ind_score)[::-1]
sas = sas[ind]
ind_score = np.zeros(len(ha0))
for y in np.unique(gt):
cy = sas[y == gt][:, y == gt]
ind_score[y == gt] = np.mean(cy, axis=0) - 10 * y
ind = np.argsort(ind_score)[::-1]
conf = sas[:, ind]
# conf = np.round(conf, decimals=2)
z = conf
# plot_heat_map(conf, show=True,
# fig_path='/D:/VirtualMachine/CheckPoints/MultiClustering/1014/FigNP/AlignConfusion.svg')
plt.figure()
# for i in range(z.shape[0]):
# for j in range(z.shape[1]):
# # plt.text(j, i, accs[i, j].round(2), ha="center", va="center", color="b", fontsize=12,
# # fontname='Times New Roman')
# plt.text(j, i, z[i, j], ha="center", va="center")
plt.imshow(z, interpolation='nearest', aspect='auto')
# plt.colorbar()
plt.axis('off')
# plt.subplots_adjust(top=0.957, bottom=0.081, left=0.108, right=0.977, hspace=0.2, wspace=0.2)
# plt.show()
plt.tight_layout()
plt.savefig(
figp,
transparent=True)
print()
if use_mx:
break
# def scatter():
# mx = False
# if mx:
# np_pth = 'D:/VirtualMachine/CheckPoints/MultiClustering/Repro/SURE/NoisyMNISTBoth.npz'
# data_f = np.load(np_pth, allow_pickle=False)
# feature_vec = data_f['feature_vec']
# type_vec = data_f['type_vec']
# group_vec = np.concatenate((np.zeros(30000), np.ones(30000)))
# else:
# np_pth = 'D:/Pengxin/Workplace/Codes/MultimodalityClustering/Np099.npz'
# data_f = np.load(np_pth, allow_pickle=False)
# feature_vec = data_f['feature_vec']
# type_vec = data_f['type_vec']
# group_vec = data_f['group_vec']
#
# sub_sample = 3000
# if len(feature_vec) > sub_sample * 2:
# ind = np.arange(int(len(feature_vec) // 2))
# np.random.shuffle(ind)
# ind = ind[:sub_sample]
# ind = np.concatenate((ind, ind + 30000))
# feature_vec = feature_vec[ind]
# group_vec = group_vec[ind]
# type_vec = type_vec[ind]
# # fv = feature_vec.reshape((len(feature_vec), -1))
# prefix = 'D:/Pengxin/Temp/mxF/'
# visualize2(feature_vec, type_vec, group_vec, None, prefix, )
#
# # for perplexity in [15,30]:
# # prefix = 'D:/Pengxin/Temp/mxF/P{}N{}'.format(perplexity, sub_sample)
# # vis_fea_multi = TSNE(perplexity=perplexity).fit_transform(
# # np.concatenate((fv[group_vec == 0], fv[group_vec == 1]), axis=1)
# # )
# # visualize_scatter(vis_fea_multi,
# # fig_path='{}Multi.{}'.format(prefix, post),
# # label_color=type_vec[group_vec == 0],
# # )
# #
# # vis_fea = TSNE(perplexity=perplexity).fit_transform(fv)
# #
# # visualize_scatter(vis_fea,
# # fig_path='{}Type.{}'.format(prefix, post),
# # label_color=type_vec,
# #
# # )
# # # visualize_scatter(vis_fea,
# # # fig_path='{}Cluster.svg'.format(prefix),
# # # label_color=pred_vec,
# # # label_shape=type_vec,
# # #
# # # )
# # visualize_scatter(vis_fea,
# # fig_path='{}Group.{}'.format(prefix, post),
# # label_color=group_vec,
# #
# # )
def plot_nrmse():
rs = pd.read_csv('D:/VirtualMachine/CheckPoints/MultiClustering/Repro/SMAIL/Recover/_Table_NRMSE_AVG_FuEp.csv')
# rs = pd.read_csv('/xlearning/pengxin/Codes/230318/IMvC_RunSet0405/_Table_NRMSE_AVG_FuEp.csv')
xx = []
yy = []
labels = []
spls = []
colors = []
for i, rec in enumerate(np.unique(rs.loc[:, 'Reconstruction'])):
if rec > 1:
continue
label = '$\mathcal{L}_{IsIL}@\lambda_{IsIL}$' + '={}'.format(rec)
rd = rs.loc[rs.loc[:, 'Reconstruction'] == rec]
x = rd.loc[:, 'Epoch']
y = rd.loc[:, 'loss_reconstruction_epoch']
xx.append(x)
yy.append(y)
labels.append(label)
spls.append('-')
colors.append('C{}'.format(i))
for i, rec in enumerate(np.unique(rs.loc[:, 'Reconstruction'])):
if rec > 1:
continue
label = '$NRMSE@\lambda_{IsIL}$' + '={}'.format(rec)
rd = rs.loc[rs.loc[:, 'Reconstruction'] == rec]
ind = pd.isna(rd.loc[:, 'rnmse0']).values != True
rd2 = rd.loc[ind]
ind = rd2.loc[:, 'Epoch'].values > 0
rd2 = rd2.loc[ind]
x = rd2.loc[:, 'Epoch']
y = rd2.loc[:, 'rnmse0']
xx.append(x)
yy.append(y)
labels.append(label)
spls.append('--')
colors.append('C{}'.format(i))
# np_pth = 'D:/VirtualMachine/CheckPoints/MultiClustering/Repro/SURE/nrmse_list.npz'
# data_f = np.load(np_pth, allow_pickle=True)
# data0 = np.asarray([it.cpu().numpy() for it in data_f['data0']])
# data1 = np.asarray([it.cpu().numpy() for it in data_f['data1']])
# y = (data1 + data0)/2
# x = np.arange(len(y))
# xx.append(x)
# yy.append(y)
# labels.append('SURE')
# spls.append('-.')
# colors.append('C{}'.format(6))
| visualize_plot(xx, yy, labels=labels, show=True,
| 5 | 2023-12-21 08:50:36+00:00 | 8k |
botcs/wolfson-scheduler | tests/test_solver.py | [
{
"identifier": "unravel_indices",
"path": "solver.py",
"snippet": "def unravel_indices(indices, shape):\n coord = []\n\n for dim in reversed(shape):\n coord.append(indices % dim)\n indices = indices // dim\n\n coord = torch.stack(coord[::-1], dim=-1)\n\n return coord"
},
{... | import torch
import unittest
import math
from unittest.mock import patch
from solver import (
unravel_indices,
generalized_outer_addition,
compute_variances,
get_max_numel,
check_matrix_fit_and_num_chunks,
convert_property_to_categorical,
extract_best_assignment,
get_no_overlap_inds,
generate_binary_matrices,
eliminate_invalid_boats,
generate_valid_assignments,
evaluate_skill_variance,
evaluate_num_preferred_outings,
evaluate_assignments_per_week,
permute_top_assignments,
) | 5,894 |
class TestUnravelIndices(unittest.TestCase):
def test_simple_case(self):
indices = torch.tensor([0, 1, 2, 3, 4, 5])
shape = (2, 3)
expected_result = torch.tensor([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]])
|
class TestUnravelIndices(unittest.TestCase):
def test_simple_case(self):
indices = torch.tensor([0, 1, 2, 3, 4, 5])
shape = (2, 3)
expected_result = torch.tensor([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2]]) | result = unravel_indices(indices, shape) | 0 | 2023-12-18 05:12:36+00:00 | 8k |
Azure-Samples/functions-python-web-crawler | .venv/Lib/site-packages/azure/functions/decorators/function_app.py | [
{
"identifier": "GenericInputBinding",
"path": ".venv/Lib/site-packages/azure/functions/decorators/generic.py",
"snippet": "class GenericInputBinding(InputBinding):\n\n @staticmethod\n def get_binding_name():\n pass\n\n def __init__(self,\n name: str,\n ty... | import abc
import json
import logging
from abc import ABC
from datetime import time
from typing import Any, Callable, Dict, List, Optional, Union, \
Iterable
from azure.functions.decorators.blob import BlobTrigger, BlobInput, BlobOutput
from azure.functions.decorators.core import Binding, Trigger, DataType, \
AuthLevel, SCRIPT_FILE_NAME, Cardinality, AccessRights
from azure.functions.decorators.cosmosdb import CosmosDBTrigger, \
CosmosDBOutput, CosmosDBInput, CosmosDBTriggerV3, CosmosDBInputV3, \
CosmosDBOutputV3
from azure.functions.decorators.eventgrid import EventGridTrigger, \
EventGridOutput
from azure.functions.decorators.eventhub import EventHubTrigger, EventHubOutput
from azure.functions.decorators.http import HttpTrigger, HttpOutput, \
HttpMethod
from azure.functions.decorators.queue import QueueTrigger, QueueOutput
from azure.functions.decorators.servicebus import ServiceBusQueueTrigger, \
ServiceBusQueueOutput, ServiceBusTopicTrigger, \
ServiceBusTopicOutput
from azure.functions.decorators.table import TableInput, TableOutput
from azure.functions.decorators.timer import TimerTrigger
from azure.functions.decorators.utils import parse_singular_param_to_enum, \
parse_iterable_param_to_enums, StringifyEnumJsonEncoder
from azure.functions.http import HttpRequest
from .generic import GenericInputBinding, GenericTrigger, GenericOutputBinding
from .warmup import WarmUpTrigger
from .._http_asgi import AsgiMiddleware
from .._http_wsgi import WsgiMiddleware, Context | 3,850 | The generic_output_binding decorator adds :class:`GenericOutputBinding`
to the :class:`FunctionBuilder` object for building :class:`Function`
object used in worker function indexing model.
This is equivalent to defining a generic output binding in the
function.json which enables function to write data from a
custom defined output source.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-custom
:param arg_name: The name of output parameter in the function code.
:param type: The type of binding.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=GenericOutputBinding(
name=arg_name,
type=type,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
class FunctionRegister(DecoratorApi, HttpFunctionsAuthLevelMixin, ABC):
def __init__(self, auth_level: Union[AuthLevel, str], *args, **kwargs):
"""Interface for declaring top level function app class which will
be directly indexed by Python Function runtime.
:param auth_level: Determines what keys, if any, need to be present
on the request in order to invoke the function.
:param args: Variable length argument list.
:param kwargs: Arbitrary keyword arguments.
"""
DecoratorApi.__init__(self, *args, **kwargs)
HttpFunctionsAuthLevelMixin.__init__(self, auth_level, *args, **kwargs)
self._require_auth_level: Optional[bool] = None
def get_functions(self) -> List[Function]:
"""Get the function objects in the function app.
:return: List of functions in the function app.
"""
functions = [function_builder.build(self.auth_level)
for function_builder in self._function_builders]
if not self._require_auth_level:
self._require_auth_level = any(
function.is_http_function() for function in functions)
if not self._require_auth_level:
logging.warning(
'Auth level is not applied to non http '
'function app. Ref: '
'https://docs.microsoft.com/azure/azure-functions/functions'
'-bindings-http-webhook-trigger?tabs=in-process'
'%2Cfunctionsv2&pivots=programming-language-python#http-auth')
return functions
def register_functions(self, function_container: DecoratorApi) -> None:
"""Register a list of functions in the function app.
:param function_container: Instance extending :class:`DecoratorApi`
which contains a list of functions.
"""
if isinstance(function_container, FunctionRegister):
raise TypeError('functions can not be type of FunctionRegister!')
self._function_builders.extend(function_container._function_builders)
register_blueprint = register_functions
class FunctionApp(FunctionRegister, TriggerApi, BindingApi):
"""FunctionApp object used by worker function indexing model captures
user defined functions and metadata.
Ref: https://aka.ms/azure-function-ref
"""
def __init__(self,
http_auth_level: Union[AuthLevel, str] = AuthLevel.FUNCTION):
"""Constructor of :class:`FunctionApp` object.
:param http_auth_level: Determines what keys, if any, need to be
present
on the request in order to invoke the function.
"""
super().__init__(auth_level=http_auth_level)
class Blueprint(TriggerApi, BindingApi):
"""Functions container class where all the functions
loaded in it can be registered in :class:`FunctionRegister` subclasses
but itself can not be indexed directly. The class contains all existing
supported trigger and binding decorator functions.
"""
pass
class ExternalHttpFunctionApp(FunctionRegister, TriggerApi, ABC):
"""Interface to extend for building third party http function apps."""
@abc.abstractmethod
def _add_http_app(self,
http_middleware: Union[
| # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class Function(object):
"""The function object represents a function in Function App. It
encapsulates function metadata and callable and used in the worker
function indexing model. Ref: https://aka.ms/azure-function-ref
"""
def __init__(self, func: Callable[..., Any], script_file: str):
"""Constructor of :class:`FunctionBuilder` object.
:param func: User defined python function instance.
:param script_file: File name indexed by worker to find function.
"""
self._name: str = func.__name__
self._func = func
self._trigger: Optional[Trigger] = None
self._bindings: List[Binding] = []
self.function_script_file = script_file
self.http_type = 'function'
self._is_http_function = False
def add_binding(self, binding: Binding) -> None:
"""Add a binding instance to the function.
:param binding: The binding object to add.
"""
self._bindings.append(binding)
def add_trigger(self, trigger: Trigger) -> None:
"""Add a trigger instance to the function.
:param trigger: The trigger object to add.
:raises ValueError: Raises trigger already exists error if a trigger is
being added to a function which has trigger attached.
"""
if self._trigger:
raise ValueError("A trigger was already registered to this "
"function. Adding another trigger is not the "
"correct behavior as a function can only have one"
" trigger. Existing registered trigger "
f"is {self._trigger.get_dict_repr()} and New "
f"trigger "
f"being added is {trigger.get_dict_repr()}")
self._trigger = trigger
# We still add the trigger info to the bindings to ensure that
# function.json is complete
self._bindings.append(trigger)
def set_function_name(self, function_name: Optional[str] = None) -> None:
"""Set or update the name for the function if :param:`function_name`
is not None. If not set, function name will default to python
function name.
:param function_name: Name the function set to.
"""
if function_name:
self._name = function_name
def set_http_type(self, http_type: str) -> None:
"""Set or update the http type for the function if :param:`http_type`
.
:param http_type: Http function type.
"""
self.http_type = http_type
def is_http_function(self) -> bool:
return self._is_http_function
def get_trigger(self) -> Optional[Trigger]:
"""Get attached trigger instance of the function.
:return: Trigger instance or None.
"""
return self._trigger
def get_bindings(self) -> List[Binding]:
"""Get all the bindings attached to the function.
:return: Bindings attached to the function.
"""
return self._bindings
def get_raw_bindings(self) -> List[str]:
return [json.dumps(b.get_dict_repr(), cls=StringifyEnumJsonEncoder)
for b in self._bindings]
def get_bindings_dict(self) -> Dict:
"""Get dictionary representation of the bindings of the function.
:return: Dictionary representation of the bindings.
"""
return {"bindings": [b.get_dict_repr() for b in self._bindings]}
def get_dict_repr(self) -> Dict:
"""Get the dictionary representation of the function.
:return: The dictionary representation of the function.
"""
stub_f_json = {
"scriptFile": self.function_script_file
}
stub_f_json.update(self.get_bindings_dict()) # NoQA
return stub_f_json
def get_user_function(self) -> Callable[..., Any]:
"""Get the python function customer defined.
:return: The python function customer defined.
"""
return self._func
def get_function_name(self) -> str:
"""Get the function name.
:return: Function name.
"""
return self._name
def get_function_json(self) -> str:
"""Get the json stringified form of function.
:return: The json stringified form of function.
"""
return json.dumps(self.get_dict_repr(), cls=StringifyEnumJsonEncoder)
def __str__(self):
return self.get_function_json()
class FunctionBuilder(object):
def __init__(self, func, function_script_file):
self._function = Function(func, function_script_file)
def __call__(self, *args, **kwargs):
pass
def configure_function_name(self, function_name: str) -> 'FunctionBuilder':
self._function.set_function_name(function_name)
return self
def configure_http_type(self, http_type: str) -> 'FunctionBuilder':
self._function.set_http_type(http_type)
return self
def add_trigger(self, trigger: Trigger) -> 'FunctionBuilder':
self._function.add_trigger(trigger=trigger)
return self
def add_binding(self, binding: Binding) -> 'FunctionBuilder':
self._function.add_binding(binding=binding)
return self
def _validate_function(self,
auth_level: Optional[AuthLevel] = None) -> None:
"""
Validates the function information before building the function.
:param auth_level: Http auth level that will be set if http
trigger function auth level is None.
"""
function_name = self._function.get_function_name()
trigger = self._function.get_trigger()
if trigger is None:
raise ValueError(
f"Function {function_name} does not have a trigger. A valid "
f"function must have one and only one trigger registered.")
bindings = self._function.get_bindings()
if trigger not in bindings:
raise ValueError(
f"Function {function_name} trigger {trigger} not present"
f" in bindings {bindings}")
# Set route to function name if unspecified in the http trigger
# Set auth level to function app auth level if unspecified in the
# http trigger
if Trigger.is_supported_trigger_type(trigger, HttpTrigger):
if getattr(trigger, 'route', None) is None:
getattr(trigger, 'init_params').append('route')
setattr(trigger, 'route', function_name)
if getattr(trigger, 'auth_level',
None) is None and auth_level is not None:
getattr(trigger, 'init_params').append('auth_level')
setattr(trigger, 'auth_level',
parse_singular_param_to_enum(auth_level, AuthLevel))
self._function._is_http_function = True
def build(self, auth_level: Optional[AuthLevel] = None) -> Function:
"""
Validates and builds the function object.
:param auth_level: Http auth level that will be set if http
trigger function auth level is None.
"""
self._validate_function(auth_level)
return self._function
class DecoratorApi(ABC):
"""Interface which contains essential decorator function building blocks
to extend for creating new function app or blueprint classes.
"""
def __init__(self, *args, **kwargs):
self._function_builders: List[FunctionBuilder] = []
self._app_script_file: str = SCRIPT_FILE_NAME
@property
def app_script_file(self) -> str:
"""Name of function app script file in which all the functions
are defined. \n
Script file defined here is for placeholder purpose, please refer to
worker defined script file path as the single point of truth.
:return: Script file name.
"""
return self._app_script_file
def _validate_type(self,
func: Union[Callable[..., Any], FunctionBuilder]) \
-> FunctionBuilder:
"""Validate the type of the function object and return the created
:class:`FunctionBuilder` object.
:param func: Function object passed to
:meth:`_configure_function_builder`
:raises ValueError: Raise error when func param is neither
:class:`Callable` nor :class:`FunctionBuilder`.
:return: :class:`FunctionBuilder` object.
"""
if isinstance(func, FunctionBuilder):
fb = self._function_builders.pop()
elif callable(func):
fb = FunctionBuilder(func, self._app_script_file)
else:
raise ValueError(
"Unsupported type for function app decorator found.")
return fb
def _configure_function_builder(self, wrap) -> Callable[..., Any]:
"""Decorator function on user defined function to create and return
:class:`FunctionBuilder` object from :class:`Callable` func.
"""
def decorator(func):
fb = self._validate_type(func)
self._function_builders.append(fb)
return wrap(fb)
return decorator
def function_name(self, name: str) -> Callable[..., Any]:
"""Set name of the :class:`Function` object.
:param name: Name of the function.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.configure_function_name(name)
return fb
return decorator()
return wrap
def http_type(self, http_type: str) -> Callable[..., Any]:
"""Set http type of the :class:`Function` object.
:param http_type: Http type of the function.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.configure_http_type(http_type)
return fb
return decorator()
return wrap
class HttpFunctionsAuthLevelMixin(ABC):
"""Interface to extend for enabling function app level http
authorization level setting"""
def __init__(self, auth_level: Union[AuthLevel, str], *args, **kwargs):
self._auth_level = AuthLevel[auth_level] \
if isinstance(auth_level, str) else auth_level
@property
def auth_level(self) -> AuthLevel:
"""Authorization level of the function app. Will be applied to the http
trigger functions which do not have authorization level specified.
:return: Authorization level of the function app.
"""
return self._auth_level
class TriggerApi(DecoratorApi, ABC):
"""Interface to extend for using existing trigger decorator functions."""
def route(self,
route: Optional[str] = None,
trigger_arg_name: str = 'req',
binding_arg_name: str = '$return',
methods: Optional[
Union[Iterable[str], Iterable[HttpMethod]]] = None,
auth_level: Optional[Union[AuthLevel, str]] = None,
trigger_extra_fields: Dict[str, Any] = {},
binding_extra_fields: Dict[str, Any] = {}
) -> Callable[..., Any]:
"""The route decorator adds :class:`HttpTrigger` and
:class:`HttpOutput` binding to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining HttpTrigger
and HttpOutput binding in the function.json which enables your
function be triggered when http requests hit the specified route.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-http
:param route: Route for the http endpoint, if None, it will be set
to function name if present or user defined python function name.
:param trigger_arg_name: Argument name for :class:`HttpRequest`,
defaults to 'req'.
:param binding_arg_name: Argument name for :class:`HttpResponse`,
defaults to '$return'.
:param methods: A tuple of the HTTP methods to which the function
responds.
:param auth_level: Determines what keys, if any, need to be present
on the request in order to invoke the function.
:return: Decorator function.
:param trigger_extra_fields: Additional fields to include in trigger
json. For example,
>>> data_type='STRING' # 'dataType': 'STRING' in trigger json
:param binding_extra_fields: Additional fields to include in binding
json. For example,
>>> data_type='STRING' # 'dataType': 'STRING' in binding json
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_trigger(trigger=HttpTrigger(
name=trigger_arg_name,
methods=parse_iterable_param_to_enums(methods, HttpMethod),
auth_level=parse_singular_param_to_enum(auth_level,
AuthLevel),
route=route, **trigger_extra_fields))
fb.add_binding(binding=HttpOutput(
name=binding_arg_name, **binding_extra_fields))
return fb
return decorator()
return wrap
def timer_trigger(self,
arg_name: str,
schedule: str,
run_on_startup: Optional[bool] = None,
use_monitor: Optional[bool] = None,
data_type: Optional[Union[DataType, str]] = None,
**kwargs: Any) -> Callable[..., Any]:
"""The schedule or timer decorator adds :class:`TimerTrigger` to the
:class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining TimerTrigger
in the function.json which enables your function be triggered on the
specified schedule.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-timer
:param arg_name: The name of the variable that represents the
:class:`TimerRequest` object in function code.
:param schedule: A string representing a CRON expression that will
be used to schedule a function to run.
:param run_on_startup: If true, the function is invoked when the
runtime starts.
:param use_monitor: Set to true or false to indicate whether the
schedule should be monitored.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_trigger(
trigger=TimerTrigger(
name=arg_name,
schedule=schedule,
run_on_startup=run_on_startup,
use_monitor=use_monitor,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
schedule = timer_trigger
def warm_up_trigger(self,
arg_name: str,
data_type: Optional[Union[DataType, str]] = None,
**kwargs) -> Callable:
"""The warm up decorator adds :class:`WarmUpTrigger` to the
:class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining WarmUpTrigger
in the function.json which enables your function be triggered on the
specified schedule.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-warmup
:param arg_name: The name of the variable that represents the
:class:`TimerRequest` object in function code.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_trigger(
trigger=WarmUpTrigger(
name=arg_name,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def service_bus_queue_trigger(
self,
arg_name: str,
connection: str,
queue_name: str,
data_type: Optional[Union[DataType, str]] = None,
access_rights: Optional[Union[AccessRights, str]] = None,
is_sessions_enabled: Optional[bool] = None,
cardinality: Optional[Union[Cardinality, str]] = None,
**kwargs: Any) -> Callable[..., Any]:
"""The on_service_bus_queue_change decorator adds
:class:`ServiceBusQueueTrigger` to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining ServiceBusQueueTrigger
in the function.json which enables your function be triggered when
new message(s) are sent to the service bus queue.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-service-bus
:param arg_name: The name of the variable that represents the
:class:`ServiceBusMessage` object in function code.
:param connection: The name of an app setting or setting collection
that specifies how to connect to Service Bus.
:param queue_name: Name of the queue to monitor.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param access_rights: Access rights for the connection string.
:param is_sessions_enabled: True if connecting to a session-aware
queue or subscription.
:param cardinality: Set to many in order to enable batching.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_trigger(
trigger=ServiceBusQueueTrigger(
name=arg_name,
connection=connection,
queue_name=queue_name,
data_type=parse_singular_param_to_enum(data_type,
DataType),
access_rights=parse_singular_param_to_enum(
access_rights,
AccessRights),
is_sessions_enabled=is_sessions_enabled,
cardinality=parse_singular_param_to_enum(cardinality,
Cardinality),
**kwargs))
return fb
return decorator()
return wrap
def service_bus_topic_trigger(
self,
arg_name: str,
connection: str,
topic_name: str,
subscription_name: str,
data_type: Optional[Union[DataType, str]] = None,
access_rights: Optional[Union[AccessRights, str]] = None,
is_sessions_enabled: Optional[bool] = None,
cardinality: Optional[Union[Cardinality, str]] = None,
**kwargs: Any) -> Callable[..., Any]:
"""The on_service_bus_topic_change decorator adds
:class:`ServiceBusTopicTrigger` to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining ServiceBusTopicTrigger
in the function.json which enables function to be triggered when new
message(s) are sent to the service bus topic.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-service-bus
:param arg_name: The name of the variable that represents the
:class:`ServiceBusMessage` object in function code.
:param connection: The name of an app setting or setting collection
that specifies how to connect to Service Bus.
:param topic_name: Name of the topic to monitor.
:param subscription_name: Name of the subscription to monitor.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param access_rights: Access rights for the connection string.
:param is_sessions_enabled: True if connecting to a session-aware
queue or subscription.
:param cardinality: Set to many in order to enable batching.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_trigger(
trigger=ServiceBusTopicTrigger(
name=arg_name,
connection=connection,
topic_name=topic_name,
subscription_name=subscription_name,
data_type=parse_singular_param_to_enum(data_type,
DataType),
access_rights=parse_singular_param_to_enum(
access_rights,
AccessRights),
is_sessions_enabled=is_sessions_enabled,
cardinality=parse_singular_param_to_enum(cardinality,
Cardinality),
**kwargs))
return fb
return decorator()
return wrap
def queue_trigger(self,
arg_name: str,
queue_name: str,
connection: str,
data_type: Optional[DataType] = None,
**kwargs) -> Callable[..., Any]:
"""The queue_trigger decorator adds :class:`QueueTrigger` to the
:class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining QueueTrigger
in the function.json which enables function to be triggered when new
message(s) are sent to the storage queue.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-queue
:param arg_name: The name of the variable that represents the
:class:`QueueMessage` object in function code.
:param queue_name: The name of the queue to poll.
:param connection: The name of an app setting or setting collection
that specifies how to connect to Azure Queues.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_trigger(
trigger=QueueTrigger(
name=arg_name,
queue_name=queue_name,
connection=connection,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def event_hub_message_trigger(self,
arg_name: str,
connection: str,
event_hub_name: str,
data_type: Optional[
Union[DataType, str]] = None,
cardinality: Optional[
Union[Cardinality, str]] = None,
consumer_group: Optional[
str] = None,
**kwargs: Any) -> Callable[..., Any]:
"""The event_hub_message_trigger decorator adds
:class:`EventHubTrigger`
to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining EventHubTrigger
in the function.json which enables function to be triggered when new
message(s) are sent to the event hub.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-event-hubs
:param arg_name: The name of the variable that represents
:class:`EventHubEvent` object in function code.
:param connection: The name of an app setting or setting collection
that specifies how to connect to Event Hubs.
:param event_hub_name: The name of the event hub.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param cardinality: Set to many in order to enable batching.
:param consumer_group: An optional property that sets the consumer
group used to subscribe to events in the hub.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_trigger(
trigger=EventHubTrigger(
name=arg_name,
connection=connection,
event_hub_name=event_hub_name,
data_type=parse_singular_param_to_enum(data_type,
DataType),
cardinality=parse_singular_param_to_enum(cardinality,
Cardinality),
consumer_group=consumer_group,
**kwargs))
return fb
return decorator()
return wrap
def cosmos_db_trigger_v3(self,
arg_name: str,
database_name: str,
collection_name: str,
connection_string_setting: str,
lease_collection_name: Optional[str] = None,
lease_connection_string_setting: Optional[
str] = None,
lease_database_name: Optional[str] = None,
create_lease_collection_if_not_exists: Optional[
bool] = None,
leases_collection_throughput: Optional[int] =
None,
lease_collection_prefix: Optional[str] = None,
checkpoint_interval: Optional[int] = None,
checkpoint_document_count: Optional[int] = None,
feed_poll_delay: Optional[int] = None,
lease_renew_interval: Optional[int] = None,
lease_acquire_interval: Optional[int] = None,
lease_expiration_interval: Optional[int] = None,
max_items_per_invocation: Optional[int] = None,
start_from_beginning: Optional[bool] = None,
preferred_locations: Optional[str] = None,
data_type: Optional[
Union[DataType, str]] = None,
**kwargs: Any) -> \
Callable[..., Any]:
"""The cosmos_db_trigger_v3 decorator adds :class:`CosmosDBTrigger`
to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This decorator will work only with extension bundle 2.x
or 3.x. For additional details, please refer
https://aka.ms/cosmosdb-v4-update.
This is equivalent to defining CosmosDBTrigger in the function.json
which enables function to be triggered when CosmosDB data is changed.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-cosmosdb-v2
:param arg_name: The name of the variable that represents
:class:`DocumentList` object in function code.
:param database_name: The name of the Azure Cosmos DB database with
the collection being monitored.
:param collection_name: The name of the collection being monitored.
:param connection_string_setting: The name of an app setting or
setting collection that specifies how to connect to the Azure Cosmos
DB account being monitored.
:param lease_collection_name: The name of the collection used to
store leases.
:param lease_connection_string_setting: The name of an app setting
or setting collection that specifies how to connect to the Azure
Cosmos DB account that holds the lease collection.
:param lease_database_name: The name of the database that holds the
collection used to store leases.
:param create_lease_collection_if_not_exists: When set to true,
the leases collection is automatically created when it doesn't
already exist.
:param leases_collection_throughput: Defines the number of Request
Units to assign when the leases collection is created.
:param lease_collection_prefix: When set, the value is added as a
prefix to the leases created in the Lease collection for this
Function.
:param checkpoint_interval: When set, it defines, in milliseconds,
the interval between lease checkpoints. Default is always after a
Function call.
:param checkpoint_document_count: Customizes the amount of documents
between lease checkpoints. Default is always after a Function call.
:param feed_poll_delay: The time (in milliseconds) for the delay
between polling a partition for new changes on the feed, after all
current changes are drained.
:param lease_renew_interval: When set, it defines, in milliseconds,
the renew interval for all leases for partitions currently held by
an instance.
:param lease_acquire_interval: When set, it defines,
in milliseconds, the interval to kick off a task to compute if
partitions are distributed evenly among known host instances.
:param lease_expiration_interval: When set, it defines,
in milliseconds, the interval for which the lease is taken on a
lease representing a partition.
:param max_items_per_invocation: When set, this property sets the
maximum number of items received per Function call.
:param start_from_beginning: This option tells the Trigger to read
changes from the beginning of the collection's change history
instead of starting at the current time.
:param preferred_locations: Defines preferred locations (regions)
for geo-replicated database accounts in the Azure Cosmos DB service.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
trigger = CosmosDBTriggerV3(
name=arg_name,
database_name=database_name,
collection_name=collection_name,
connection_string_setting=connection_string_setting,
lease_collection_name=lease_collection_name,
lease_connection_string_setting=lease_connection_string_setting,
lease_database_name=lease_database_name,
create_lease_collection_if_not_exists=create_lease_collection_if_not_exists, # NoQA
leases_collection_throughput=leases_collection_throughput,
lease_collection_prefix=lease_collection_prefix,
checkpoint_interval=checkpoint_interval,
checkpoint_document_count=checkpoint_document_count,
feed_poll_delay=feed_poll_delay,
lease_renew_interval=lease_renew_interval,
lease_acquire_interval=lease_acquire_interval,
lease_expiration_interval=lease_expiration_interval,
max_items_per_invocation=max_items_per_invocation,
start_from_beginning=start_from_beginning,
preferred_locations=preferred_locations,
data_type=parse_singular_param_to_enum(data_type, DataType),
**kwargs)
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_trigger(trigger=trigger)
return fb
return decorator()
return wrap
def cosmos_db_trigger(self,
arg_name: str,
connection: str,
database_name: str,
container_name: str,
lease_connection: Optional[str] = None,
lease_database_name: Optional[str] = None,
lease_container_name: Optional[str] = None,
create_lease_container_if_not_exists: Optional[
bool] = None,
leases_container_throughput: Optional[int] = None,
lease_container_prefix: Optional[str] = None,
feed_poll_delay: Optional[int] = None,
lease_acquire_interval: Optional[int] = None,
lease_expiration_interval: Optional[int] = None,
lease_renew_interval: Optional[int] = None,
max_items_per_invocation: Optional[int] = None,
start_from_beginning: Optional[time] = None,
start_from_time: Optional[time] = None,
preferred_locations: Optional[str] = None,
data_type: Optional[
Union[DataType, str]] = None,
**kwargs: Any) -> \
Callable[..., Any]:
"""The cosmos_db_trigger decorator adds :class:`CosmosDBTrigger`
to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This decorator will work only with extension bundle 4.x
and above. For additional details, please refer
https://aka.ms/cosmosdb-v4-update.
This is equivalent to defining CosmosDBTrigger in the function.json
which enables function to be triggered when CosmosDB data is changed.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-cosmosdb-v4
:param arg_name: The name of the variable that represents
:class:`DocumentList` object in function code
:param connection: The name of an app setting or setting collection
that specifies how to connect to the Azure Cosmos DB account being
monitored.
:param database_name: The name of the Azure Cosmos DB database with
the collection being monitored
:param container_name: The name of the container being monitored
:param lease_connection: (Optional) The name of an app setting or
setting container that specifies how to connect to the Azure Cosmos
DB account that holds the lease container
:param lease_database_name: The name of the database that holds the
collection used to store leases
:param lease_container_name: (Optional) The name of the container used
to store leases. When not set, the value leases is used
:param create_lease_container_if_not_exists: (Optional) When set to
true, the leases container is automatically created when it doesn't
already exist. The default value is false. When using Azure AD
identities if you set the value to true, creating containers is not an
allowed operation and your Function won't be able to start
:param leases_container_throughput: (Optional) Defines the number of
Request Units to assign when the leases container is created. This
setting is only used when createLeaseContainerIfNotExists is set to
true. This parameter is automatically set when the binding is created
using the portal
:param lease_container_prefix: (Optional) When set, the value is added
as a prefix to the leases created in the Lease container for this
function. Using a prefix allows two separate Azure Functions to share
the same Lease container by using different prefixes
:param feed_poll_delay: The time (in milliseconds) for the delay
between polling a partition for new changes on the feed, after all
current changes are drained
:param lease_acquire_interval: When set, it defines,
in milliseconds, the interval to kick off a task to compute if
partitions are distributed evenly among known host instances
:param lease_expiration_interval: When set, it defines,
in milliseconds, the interval for which the lease is taken on a
lease representing a partition
:param lease_renew_interval: When set, it defines, in milliseconds,
the renew interval for all leases for partitions currently held by
an instance
:param max_items_per_invocation: When set, this property sets the
maximum number of items received per Function call
:param start_from_beginning: This option tells the Trigger to read
changes from the beginning of the collection's change history
instead of starting at the current time
:param start_from_time: (Optional) Gets or sets the date and time from
which to initialize the change feed read operation. The recommended
format is ISO 8601 with the UTC designator, such as
2021-02-16T14:19:29Z. This is only used to set the initial trigger
state. After the trigger has a lease state, changing this value has
no effect
:param preferred_locations: Defines preferred locations (regions)
for geo-replicated database accounts in the Azure Cosmos DB service
:param data_type: Defines how Functions runtime should treat the
parameter value
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json
:return: Decorator function.
"""
trigger = CosmosDBTrigger(
name=arg_name,
connection=connection,
database_name=database_name,
container_name=container_name,
lease_connection=lease_connection,
lease_database_name=lease_database_name,
lease_container_name=lease_container_name,
create_lease_container_if_not_exists=create_lease_container_if_not_exists, # NoQA
leases_container_throughput=leases_container_throughput,
lease_container_prefix=lease_container_prefix,
feed_poll_delay=feed_poll_delay,
lease_acquire_interval=lease_acquire_interval,
lease_expiration_interval=lease_expiration_interval,
lease_renew_interval=lease_renew_interval,
max_items_per_invocation=max_items_per_invocation,
start_from_beginning=start_from_beginning,
start_from_time=start_from_time,
preferred_locations=preferred_locations,
data_type=parse_singular_param_to_enum(data_type, DataType),
**kwargs)
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_trigger(trigger=trigger)
return fb
return decorator()
return wrap
def blob_trigger(self,
arg_name: str,
path: str,
connection: str,
data_type: Optional[DataType] = None,
**kwargs) -> Callable[..., Any]:
"""
The blob_change_trigger decorator adds :class:`BlobTrigger` to the
:class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining BlobTrigger
in the function.json which enables function to be triggered when new
message(s) are sent to the storage blobs.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-storage-blob
:param arg_name: The name of the variable that represents the
:class:`InputStream` object in function code.
:param path: The path to the blob.
:param connection: The name of an app setting or setting collection
that specifies how to connect to Azure Blobs.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_trigger(
trigger=BlobTrigger(
name=arg_name,
path=path,
connection=connection,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def event_grid_trigger(self,
arg_name: str,
data_type: Optional[
Union[DataType, str]] = None,
**kwargs) -> Callable[..., Any]:
"""
The event_grid_trigger decorator adds
:class:`EventGridTrigger`
to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining event grid trigger
in the function.json which enables function to be triggered to
respond to an event sent to an event grid topic.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/eventgridtrigger
:param arg_name: the variable name used in function code for the
parameter that receives the event data.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_trigger(
trigger=EventGridTrigger(
name=arg_name,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def generic_trigger(self,
arg_name: str,
type: str,
data_type: Optional[Union[DataType, str]] = None,
**kwargs
) -> Callable[..., Any]:
"""
The generic_trigger decorator adds :class:`GenericTrigger`
to the :class:`FunctionBuilder` object for building :class:`Function`
object used in worker function indexing model.
This is equivalent to defining a generic trigger in the
function.json which triggers function to execute when generic trigger
events are received by host.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-custom
:param arg_name: The name of trigger parameter in the function code.
:param type: The type of binding.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_trigger(
trigger=GenericTrigger(
name=arg_name,
type=type,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
class BindingApi(DecoratorApi, ABC):
"""Interface to extend for using existing binding decorator functions."""
def service_bus_queue_output(self,
arg_name: str,
connection: str,
queue_name: str,
data_type: Optional[
Union[DataType, str]] = None,
access_rights: Optional[Union[
AccessRights, str]] = None,
**kwargs) -> \
Callable[..., Any]:
"""The service_bus_queue_output decorator adds
:class:`ServiceBusQueueOutput` to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining ServiceBusQueueOutput
in the function.json which enables function to write message(s) to
the service bus queue.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-service-bus
:param arg_name: The name of the variable that represents service
bus queue output object in function code.
:param connection: The name of an app setting or setting collection
that specifies how to connect to Service Bus.
:param queue_name: Name of the queue to monitor.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param access_rights: Access rights for the connection string.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=ServiceBusQueueOutput(
name=arg_name,
connection=connection,
queue_name=queue_name,
data_type=parse_singular_param_to_enum(data_type,
DataType),
access_rights=parse_singular_param_to_enum(
access_rights, AccessRights),
**kwargs))
return fb
return decorator()
return wrap
def service_bus_topic_output(self,
arg_name: str,
connection: str,
topic_name: str,
subscription_name: Optional[str] = None,
data_type: Optional[
Union[DataType, str]] = None,
access_rights: Optional[Union[
AccessRights, str]] = None,
**kwargs) -> \
Callable[..., Any]:
"""The service_bus_topic_output decorator adds
:class:`ServiceBusTopicOutput` to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining ServiceBusTopicOutput
in the function.json which enables function to write message(s) to
the service bus topic.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-service-bus
:param arg_name: The name of the variable that represents service
bus topic output object in function code.
:param connection: The name of an app setting or setting collection
that specifies how to connect to Service Bus.
:param topic_name: Name of the topic to monitor.
:param subscription_name: Name of the subscription to monitor.
:param data_type: Defines how Functions runtime should treat the
parameter value, defaults to DataType.UNDEFINED.
:param access_rights: Access rights for the connection string.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=ServiceBusTopicOutput(
name=arg_name,
connection=connection,
topic_name=topic_name,
subscription_name=subscription_name,
data_type=parse_singular_param_to_enum(data_type,
DataType),
access_rights=parse_singular_param_to_enum(
access_rights,
AccessRights),
**kwargs))
return fb
return decorator()
return wrap
def queue_output(self,
arg_name: str,
queue_name: str,
connection: str,
data_type: Optional[DataType] = None,
**kwargs) -> Callable[..., Any]:
"""The queue_output decorator adds :class:`QueueOutput` to the
:class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining QueueOutput
in the function.json which enables function to write message(s) to
the storage queue.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-queue
:param arg_name: The name of the variable that represents storage
queue output object in function code.
:param queue_name: The name of the queue to poll.
:param connection: The name of an app setting or setting collection
that specifies how to connect to Azure Queues.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=QueueOutput(name=arg_name,
queue_name=queue_name,
connection=connection,
data_type=parse_singular_param_to_enum(
data_type, DataType),
**kwargs))
return fb
return decorator()
return wrap
def event_hub_output(self,
arg_name: str,
connection: str,
event_hub_name: str,
data_type: Optional[
Union[DataType, str]] = None,
**kwargs) -> \
Callable[..., Any]:
"""The event_hub_output decorator adds
:class:`EventHubOutput` to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining EventHubOutput
in the function.json which enables function to write message(s) to
the event hub.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-event-hubs
:param arg_name: The name of the variable that represents event hub
output object in function code.
:param connection: The name of an app setting or setting collection
that specifies how to connect to Event Hub.
:param event_hub_name: The name of the event hub.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=EventHubOutput(
name=arg_name,
connection=connection,
event_hub_name=event_hub_name,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def cosmos_db_output_v3(self,
arg_name: str,
database_name: str,
collection_name: str,
connection_string_setting: str,
create_if_not_exists: Optional[bool] = None,
partition_key: Optional[str] = None,
collection_throughput: Optional[int] = None,
use_multiple_write_locations: Optional[
bool] = None,
preferred_locations: Optional[str] = None,
data_type: Optional[
Union[DataType, str]] = None,
**kwargs) \
-> Callable[..., Any]:
"""The cosmos_db_output_v3 decorator adds
:class:`CosmosDBOutput` to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This decorator will work only with extension bundle 2.x
or 3.x. For additional details, please refer
https://aka.ms/cosmosdb-v4-update.
This is equivalent to defining CosmosDBOutput
in the function.json which enables function to write to the CosmosDB.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-cosmosdb-v2
:param arg_name: The name of the variable that represents CosmosDB
output object in function code.
:param database_name: The name of the Azure Cosmos DB database with
the collection being monitored.
:param collection_name: The name of the collection being monitored.
:param connection_string_setting: The name of an app setting or
setting collection that specifies how to connect to the Azure Cosmos
DB account being monitored.
:param create_if_not_exists: A boolean value to indicate whether the
collection is created when it doesn't exist.
:param partition_key: When CreateIfNotExists is true, it defines the
partition key path for the created collection.
:param collection_throughput: When CreateIfNotExists is true,
it defines the throughput of the created collection.
:param use_multiple_write_locations: When set to true along with
PreferredLocations, it can leverage multi-region writes in the Azure
Cosmos DB service.
:param preferred_locations: Defines preferred locations (regions)
for geo-replicated database accounts in the Azure Cosmos DB service.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=CosmosDBOutputV3(
name=arg_name,
database_name=database_name,
collection_name=collection_name,
connection_string_setting=connection_string_setting,
create_if_not_exists=create_if_not_exists,
partition_key=partition_key,
collection_throughput=collection_throughput,
use_multiple_write_locations=use_multiple_write_locations, # NoQA
preferred_locations=preferred_locations,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def cosmos_db_output(self,
arg_name: str,
connection: str,
database_name: str,
container_name: str,
create_if_not_exists: Optional[bool] = None,
partition_key: Optional[str] = None,
container_throughput: Optional[int] = None,
preferred_locations: Optional[str] = None,
data_type: Optional[
Union[DataType, str]] = None,
**kwargs) \
-> Callable[..., Any]:
"""The cosmos_db_output decorator adds
:class:`CosmosDBOutput` to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This decorator will work only with extension bundle 4.x
and above. For additional details, please refer
https://aka.ms/cosmosdb-v4-update.
This is equivalent to defining CosmosDBOutput
in the function.json which enables function to write to the CosmosDB.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-cosmosdb-v4
:param arg_name: The name of the variable that represents CosmosDB
output object in function code.
:param connection: The name of an app setting or
setting collection that specifies how to connect to the Azure Cosmos
DB account being monitored
:param database_name: The name of the Azure Cosmos DB database with
the collection being monitored
:param container_name: The name of the container being monitored
:param create_if_not_exists: A boolean value to indicate whether the
collection is created when it doesn't exist
:param partition_key: When CreateIfNotExists is true, it defines the
partition key path for the created collection
:param container_throughput: When createIfNotExists is true, it defines
the throughput of the created container
PreferredLocations, it can leverage multi-region writes in the Azure
Cosmos DB service
:param preferred_locations: Defines preferred locations (regions)
for geo-replicated database accounts in the Azure Cosmos DB service
:param data_type: Defines how Functions runtime should treat the
parameter value
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=CosmosDBOutput(
name=arg_name,
connection=connection,
database_name=database_name,
container_name=container_name,
create_if_not_exists=create_if_not_exists,
partition_key=partition_key,
container_throughput=container_throughput,
preferred_locations=preferred_locations,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def cosmos_db_input_v3(self,
arg_name: str,
database_name: str,
collection_name: str,
connection_string_setting: str,
id: Optional[str] = None,
sql_query: Optional[str] = None,
partition_key: Optional[str] = None,
data_type: Optional[
Union[DataType, str]] = None,
**kwargs) \
-> Callable[..., Any]:
"""The cosmos_db_input_v3 decorator adds
:class:`CosmosDBInput` to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This decorator will work only with extension bundle 2.x
or 3.x. For additional details, please refer
https://aka.ms/cosmosdb-v4-update.
This is equivalent to defining CosmosDBInput
in the function.json which enables function to read from CosmosDB.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-cosmosdb-v2
:param arg_name: The name of the variable that represents
:class:`DocumentList` input object in function code.
:param database_name: The database containing the document.
:param collection_name: The name of the collection that contains the
document.
:param connection_string_setting: The name of the app setting
containing your Azure Cosmos DB connection string.
:param id: The ID of the document to retrieve.
:param sql_query: An Azure Cosmos DB SQL query used for retrieving
multiple documents.
:param partition_key: Specifies the partition key value for the
lookup.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=CosmosDBInputV3(
name=arg_name,
database_name=database_name,
collection_name=collection_name,
connection_string_setting=connection_string_setting,
id=id,
sql_query=sql_query,
partition_key=partition_key,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def cosmos_db_input(self,
arg_name: str,
connection: str,
database_name: str,
container_name: str,
partition_key: Optional[str] = None,
id: Optional[str] = None,
sql_query: Optional[str] = None,
preferred_locations: Optional[str] = None,
data_type: Optional[
Union[DataType, str]] = None,
**kwargs) \
-> Callable[..., Any]:
"""The cosmos_db_input decorator adds
:class:`CosmosDBInput` to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This decorator will work only with extension bundle 4.x
and above. For additional details, please refer
https://aka.ms/cosmosdb-v4-update.
This is equivalent to defining CosmosDBInput in the function.json which
enables function to read from CosmosDB.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-cosmosdb-v4
:param arg_name: The name of the variable that represents
:class:`DocumentList` input object in function code
:param connection: The name of an app setting or setting container that
specifies how to connect to the Azure Cosmos DB account being
monitored containing your Azure Cosmos DB connection string
:param database_name: The database containing the document
:param container_name: The name of the container that contains the
document
:param partition_key: Specifies the partition key value for the
lookup
:param id: The ID of the document to retrieve
:param sql_query: An Azure Cosmos DB SQL query used for retrieving
multiple documents
:param preferred_locations: (Optional) Defines preferred locations
(regions) for geo-replicated database accounts in the Azure Cosmos DB
service. Values should be comma-separated. For example, East US,South
Central US,North Europe
:param data_type: Defines how Functions runtime should treat the
parameter value
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=CosmosDBInput(
name=arg_name,
connection=connection,
database_name=database_name,
container_name=container_name,
partition_key=partition_key,
id=id,
sql_query=sql_query,
preferred_locations=preferred_locations,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def blob_input(self,
arg_name: str,
path: str,
connection: str,
data_type: Optional[DataType] = None,
**kwargs) -> Callable[..., Any]:
"""
The blob_input decorator adds :class:`BlobInput` to the
:class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining BlobInput
in the function.json which enables function to write message(s) to
the storage blobs.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-storage-blob
:param arg_name: The name of the variable that represents the blob in
function code.
:param path: The path to the blob.
:param connection: The name of an app setting or setting collection
that specifies how to connect to Azure Blobs.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=BlobInput(
name=arg_name,
path=path,
connection=connection,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def blob_output(self,
arg_name: str,
path: str,
connection: str,
data_type: Optional[DataType] = None,
**kwargs) -> Callable[..., Any]:
"""
The blob_output decorator adds :class:`BlobOutput` to the
:class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining BlobOutput
in the function.json which enables function to write message(s) to
the storage blobs.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-storage-blob
:param arg_name: The name of the variable that represents the blob in
function code.
:param path: The path to the blob.
:param connection: The name of an app setting or setting collection
that specifies how to connect to Azure Blobs.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=BlobOutput(
name=arg_name,
path=path,
connection=connection,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def event_grid_output(self,
arg_name: str,
topic_endpoint_uri: str,
topic_key_setting: str,
data_type: Optional[
Union[DataType, str]] = None,
**kwargs) -> Callable[..., Any]:
"""
The event_grid_output decorator adds
:class:`EventGridOutput`
to the :class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining output binding
in the function.json which enables function to
write events to a custom topic.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/eventgridtrigger
:param arg_name: The variable name used in function code that
represents the event.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param topic_endpoint_uri: The name of an app setting that
contains the URI for the custom topic.
:param topic_key_setting: The name of an app setting that
contains an access key for the custom topic.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=EventGridOutput(
name=arg_name,
topic_endpoint_uri=topic_endpoint_uri,
topic_key_setting=topic_key_setting,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def table_input(self,
arg_name: str,
connection: str,
table_name: str,
row_key: Optional[str] = None,
partition_key: Optional[str] = None,
take: Optional[int] = None,
filter: Optional[str] = None,
data_type: Optional[
Union[DataType, str]] = None) -> Callable[..., Any]:
"""
The table_input decorator adds :class:`TableInput` to the
:class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining TableInput
in the function.json which enables function to read a table in
an Azure Storage or Cosmos DB account
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/tablesbindings
:param arg_name: The name of the variable that represents
the table or entity in function code.
:param connection: The name of an app setting or setting collection
that specifies how to connect to the table service.
:param table_name: The Name of the table
:param row_key: The row key of the table entity to read.
:param partition_key: The partition key of the table entity to read.
:param take: The maximum number of entities to return
:param filter: An OData filter expression for the entities to return
from the table.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=TableInput(
name=arg_name,
connection=connection,
table_name=table_name,
row_key=row_key,
partition_key=partition_key,
take=take,
filter=filter,
data_type=parse_singular_param_to_enum(data_type,
DataType)))
return fb
return decorator()
return wrap
def table_output(self,
arg_name: str,
connection: str,
table_name: str,
row_key: Optional[str] = None,
partition_key: Optional[str] = None,
data_type: Optional[
Union[DataType, str]] = None) -> Callable[..., Any]:
"""
The table_output decorator adds :class:`TableOutput` to the
:class:`FunctionBuilder` object
for building :class:`Function` object used in worker function
indexing model. This is equivalent to defining TableOutput
in the function.json which enables function to write entities
to a table in an Azure Storage
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/tablesbindings
:param arg_name: The name of the variable that represents
the table or entity in function code.
:param connection: The name of an app setting or setting collection
that specifies how to connect to the table service.
:param table_name: The Name of the table
:param row_key: The row key of the table entity to read.
:param partition_key: The partition key of the table entity to read.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=TableOutput(
name=arg_name,
connection=connection,
table_name=table_name,
row_key=row_key,
partition_key=partition_key,
data_type=parse_singular_param_to_enum(data_type,
DataType)))
return fb
return decorator()
return wrap
def generic_input_binding(self,
arg_name: str,
type: str,
data_type: Optional[Union[DataType, str]] = None,
**kwargs
) -> Callable[..., Any]:
"""
The generic_input_binding decorator adds :class:`GenericInputBinding`
to the :class:`FunctionBuilder` object for building :class:`Function`
object used in worker function indexing model.
This is equivalent to defining a generic input binding in the
function.json which enables function to read data from a
custom defined input source.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-custom
:param arg_name: The name of input parameter in the function code.
:param type: The type of binding.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=GenericInputBinding(
name=arg_name,
type=type,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
def generic_output_binding(self,
arg_name: str,
type: str,
data_type: Optional[
Union[DataType, str]] = None,
**kwargs
) -> Callable[..., Any]:
"""
The generic_output_binding decorator adds :class:`GenericOutputBinding`
to the :class:`FunctionBuilder` object for building :class:`Function`
object used in worker function indexing model.
This is equivalent to defining a generic output binding in the
function.json which enables function to write data from a
custom defined output source.
All optional fields will be given default value by function host when
they are parsed by function host.
Ref: https://aka.ms/azure-function-binding-custom
:param arg_name: The name of output parameter in the function code.
:param type: The type of binding.
:param data_type: Defines how Functions runtime should treat the
parameter value.
:param kwargs: Keyword arguments for specifying additional binding
fields to include in the binding json.
:return: Decorator function.
"""
@self._configure_function_builder
def wrap(fb):
def decorator():
fb.add_binding(
binding=GenericOutputBinding(
name=arg_name,
type=type,
data_type=parse_singular_param_to_enum(data_type,
DataType),
**kwargs))
return fb
return decorator()
return wrap
class FunctionRegister(DecoratorApi, HttpFunctionsAuthLevelMixin, ABC):
def __init__(self, auth_level: Union[AuthLevel, str], *args, **kwargs):
"""Interface for declaring top level function app class which will
be directly indexed by Python Function runtime.
:param auth_level: Determines what keys, if any, need to be present
on the request in order to invoke the function.
:param args: Variable length argument list.
:param kwargs: Arbitrary keyword arguments.
"""
DecoratorApi.__init__(self, *args, **kwargs)
HttpFunctionsAuthLevelMixin.__init__(self, auth_level, *args, **kwargs)
self._require_auth_level: Optional[bool] = None
def get_functions(self) -> List[Function]:
"""Get the function objects in the function app.
:return: List of functions in the function app.
"""
functions = [function_builder.build(self.auth_level)
for function_builder in self._function_builders]
if not self._require_auth_level:
self._require_auth_level = any(
function.is_http_function() for function in functions)
if not self._require_auth_level:
logging.warning(
'Auth level is not applied to non http '
'function app. Ref: '
'https://docs.microsoft.com/azure/azure-functions/functions'
'-bindings-http-webhook-trigger?tabs=in-process'
'%2Cfunctionsv2&pivots=programming-language-python#http-auth')
return functions
def register_functions(self, function_container: DecoratorApi) -> None:
"""Register a list of functions in the function app.
:param function_container: Instance extending :class:`DecoratorApi`
which contains a list of functions.
"""
if isinstance(function_container, FunctionRegister):
raise TypeError('functions can not be type of FunctionRegister!')
self._function_builders.extend(function_container._function_builders)
register_blueprint = register_functions
class FunctionApp(FunctionRegister, TriggerApi, BindingApi):
"""FunctionApp object used by worker function indexing model captures
user defined functions and metadata.
Ref: https://aka.ms/azure-function-ref
"""
def __init__(self,
http_auth_level: Union[AuthLevel, str] = AuthLevel.FUNCTION):
"""Constructor of :class:`FunctionApp` object.
:param http_auth_level: Determines what keys, if any, need to be
present
on the request in order to invoke the function.
"""
super().__init__(auth_level=http_auth_level)
class Blueprint(TriggerApi, BindingApi):
"""Functions container class where all the functions
loaded in it can be registered in :class:`FunctionRegister` subclasses
but itself can not be indexed directly. The class contains all existing
supported trigger and binding decorator functions.
"""
pass
class ExternalHttpFunctionApp(FunctionRegister, TriggerApi, ABC):
"""Interface to extend for building third party http function apps."""
@abc.abstractmethod
def _add_http_app(self,
http_middleware: Union[ | AsgiMiddleware, WsgiMiddleware]) -> None: | 4 | 2023-12-16 04:12:01+00:00 | 8k |
ict-bigdatalab/RIGHT | data_preprocess.py | [
{
"identifier": "MySimCSE",
"path": "dense_retrieval.py",
"snippet": "class MySimCSE(SimCSE):\n\n def encode(self, sentence: Union[str, List[str]],\n device: str = None,\n return_numpy: bool = False,\n normalize_to_unit: bool = True,\n keepdim: ... | import json
import csv
import jieba
import jieba.posseg as pseg
from tqdm import tqdm
from gensim import corpora
from gensim.summarization.bm25 import BM25
from nltk.corpus import stopwords
from transformers import BertModel
from transformers import BertTokenizer
from dense_retrieval import MySimCSE
from get_datasets import get_transformed_io, get_hashtag_list
from eval_utils import f1
from functools import cmp_to_key
from data_augmentation import random_augmentation | 4,067 | with open(val_out_path, 'w', encoding='utf-8') as f:
f.write(json_str)
print("Finish creating val queries result!")
# test query
test_query_result = []
print("Start to create test queries result...")
for i in tqdm(range(len(test_queries))):
query = test_queries[i]
results = model.search(query, device='cuda', threshold=-99, top_k=10)
test_query_item = dict()
test_query_item['index'] = [ind for ind, score in results]
test_query_item['score'] = [score for ind, score in results]
test_query_result.append(test_query_item)
json_str = json.dumps(test_query_result, indent=4)
with open(test_out_path, 'w', encoding='utf-8') as f:
f.write(json_str)
print("Finish creating test queries result!")
def clean_repetition_datasets(str_data_path, dst_data_path):
# completed
str_out_path = str_data_path + "_after_cleaning.txt"
dst_out_path = dst_data_path + "_after_cleaning.txt"
documents = []
dst = []
with open(str_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
documents.append(line)
with open(dst_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
dst.append(line)
print(len(documents))
print(len(dst))
new_doc = []
new_dst = []
for idx in range(len(documents)):
if documents[idx] not in new_doc or dst[idx] not in new_dst:
new_doc.append(documents[idx])
new_dst.append(dst[idx])
else:
print(idx)
print(documents[idx])
print(dst[idx])
print('=' * 30)
print(len(new_doc))
print(len(new_dst))
with open(str_out_path, 'w', encoding='utf-8') as f:
for doc in new_doc:
f.write(doc + '\n')
with open(dst_out_path, 'w', encoding='utf-8') as f:
for d in new_dst:
f.write(d + '\n')
def preprocess_wangyue_data(post_path, conv_path, tag_path, src_path, dst_path):
post_list = []
with open(post_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
post_list.append(line.strip())
conv_list = []
with open(conv_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
conv_list.append(line.strip())
tag_list = []
with open(tag_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
tag_list.append(line.strip())
assert len(post_list) == len(conv_list) and len(conv_list) == len(tag_list)
src_list = []
dst_list = []
for i in range(len(post_list)):
src = post_list[i] + '. ' + conv_list[i]
dst = tag_list[i].replace(';', ' [SEP] ')
src_list.append(src)
dst_list.append(dst)
with open(src_path, 'w', encoding='utf-8') as f:
for src in src_list:
f.write(src + '\n')
with open(dst_path, 'w', encoding='utf-8') as f:
for dst in dst_list:
f.write(dst + '\n')
def compute_hashtag_coverage(labels, hashtags):
total_r = len(labels)
total_p = len(hashtags)
label_list = labels.copy()
hashtag_list = hashtags.copy()
true_num = 0
for lab in label_list:
for hashtag in hashtag_list:
if lab == hashtag:
true_num += 1
hashtag_list.remove(lab)
break
p = true_num / total_p
r = true_num / total_r
|
def generate_index_json_file(data_path):
out_path = data_path + "_index.json"
data = []
i = 0
with open(data_path, 'r', encoding='utf-8') as f:
for line in tqdm(f):
line = line.strip("\n")
if not line:
continue
item = {
"id": i,
"contents": line
}
data.append(item)
i += 1
print(i)
jsontext = json.dumps(data, indent=4)
with open(out_path, 'w') as json_file:
json_file.write(jsontext)
def bm25_retrieval_results(train_src_data_path, val_src_data_path, test_src_data_path):
train_out_path = train_src_data_path + "_bm25_index.json"
val_out_path = val_src_data_path + "_bm25_index.json"
test_out_path = test_src_data_path + "_bm25_index.json"
# read training documents
documents = []
with open(train_src_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
documents.append(line)
print("The number of training documents is: ", len(documents))
# read val queries
val_queries = []
with open(val_src_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
val_queries.append(line)
print("The number of val queries is: ", len(val_queries))
# read test queries
test_queries = []
with open(test_src_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
test_queries.append(line)
print("The number of test queries is: ", len(test_queries))
# build document index
# split word
texts = [doc.split() for doc in documents]
# remove stopwords
for i in range(len(texts)):
texts[i] = [word for word in texts[i] if word not in stopwords.words('english')]
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
bm25_obj = BM25(corpus)
# training query
train_query_result = []
print("Start to create training queries result...")
for i in tqdm(range(len(documents))):
query = texts[i]
query_doc = dictionary.doc2bow(query)
scores = bm25_obj.get_scores(query_doc)
best_docs = sorted(range(len(scores)), key=lambda j: scores[j])[-11:][::-1]
if i in best_docs:
best_docs.remove(i)
else:
best_docs = best_docs[:10]
print(documents[i])
train_query_result.append(best_docs)
json_str = json.dumps(train_query_result, indent=4)
with open(train_out_path, 'w', encoding='utf-8') as f:
f.write(json_str)
print("Finish creating training queries result!")
# val query
val_query_result = []
print("Start to create val queries result...")
val_texts = [vq.split() for vq in val_queries]
for i in tqdm(range(len(val_texts))):
query = [word for word in val_texts[i] if word not in stopwords.words('english')]
query_doc = dictionary.doc2bow(query)
scores = bm25_obj.get_scores(query_doc)
best_docs = sorted(range(len(scores)), key=lambda j: scores[j])[-10:][::-1]
val_query_result.append(best_docs)
json_str = json.dumps(val_query_result, indent=4)
with open(val_out_path, 'w', encoding='utf-8') as f:
f.write(json_str)
print("Finish creating val queries result!")
# test query
test_query_result = []
print("Start to create test queries result...")
test_texts = [tq.split() for tq in test_queries]
for i in tqdm(range(len(test_texts))):
query = [word for word in test_texts[i] if word not in stopwords.words('english')]
query_doc = dictionary.doc2bow(query)
scores = bm25_obj.get_scores(query_doc)
best_docs = sorted(range(len(scores)), key=lambda j: scores[j])[-10:][::-1]
test_query_result.append(best_docs)
json_str = json.dumps(test_query_result, indent=4)
with open(test_out_path, 'w', encoding='utf-8') as f:
f.write(json_str)
print("Finish creating test queries result!")
def bm25_retrieval_score_results(train_src_data_path, val_src_data_path, test_src_data_path):
train_out_path = train_src_data_path + "_bm25_score.json"
val_out_path = val_src_data_path + "_bm25_score.json"
test_out_path = test_src_data_path + "_bm25_score.json"
# read training documents
documents = []
with open(train_src_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
documents.append(line)
print("The number of training documents is: ", len(documents))
# read val queries
val_queries = []
with open(val_src_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
val_queries.append(line)
print("The number of val queries is: ", len(val_queries))
# read test queries
test_queries = []
with open(test_src_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
test_queries.append(line)
print("The number of test queries is: ", len(test_queries))
# build document index
# split word
texts = [doc.split() for doc in documents]
# remove stopwords
for i in range(len(texts)):
texts[i] = [word for word in texts[i] if word not in stopwords.words('english')]
dictionary = corpora.Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
bm25_obj = BM25(corpus)
# training query
train_query_result = []
print("Start to create training queries result...")
for i in tqdm(range(len(documents))):
query = texts[i]
query_doc = dictionary.doc2bow(query)
scores = bm25_obj.get_scores(query_doc)
best_docs = sorted(range(len(scores)), key=lambda j: scores[j])[-11:][::-1]
if i in best_docs:
best_docs.remove(i)
else:
best_docs = best_docs[:10]
print(documents[i])
train_query_item = dict()
train_query_item['index'] = best_docs
train_query_item['score'] = [scores[doc] for doc in best_docs]
train_query_result.append(train_query_item)
json_str = json.dumps(train_query_result, indent=4)
with open(train_out_path, 'w', encoding='utf-8') as f:
f.write(json_str)
print("Finish creating training queries result!")
# val query
val_query_result = []
print("Start to create val queries result...")
val_texts = [vq.split() for vq in val_queries]
for i in tqdm(range(len(val_texts))):
query = [word for word in val_texts[i] if word not in stopwords.words('english')]
query_doc = dictionary.doc2bow(query)
scores = bm25_obj.get_scores(query_doc)
best_docs = sorted(range(len(scores)), key=lambda j: scores[j])[-10:][::-1]
val_query_item = dict()
val_query_item['index'] = best_docs
val_query_item['score'] = [scores[doc] for doc in best_docs]
val_query_result.append(val_query_item)
json_str = json.dumps(val_query_result, indent=4)
with open(val_out_path, 'w', encoding='utf-8') as f:
f.write(json_str)
print("Finish creating val queries result!")
# test query
test_query_result = []
print("Start to create test queries result...")
test_texts = [tq.split() for tq in test_queries]
for i in tqdm(range(len(test_texts))):
query = [word for word in test_texts[i] if word not in stopwords.words('english')]
query_doc = dictionary.doc2bow(query)
scores = bm25_obj.get_scores(query_doc)
best_docs = sorted(range(len(scores)), key=lambda j: scores[j])[-10:][::-1]
test_query_item = dict()
test_query_item['index'] = best_docs
test_query_item['score'] = [scores[doc] for doc in best_docs]
test_query_result.append(test_query_item)
json_str = json.dumps(test_query_result, indent=4)
with open(test_out_path, 'w', encoding='utf-8') as f:
f.write(json_str)
print("Finish creating test queries result!")
def dense_retrieval_results(train_src_data_path, val_src_data_path, test_src_data_path):
train_out_path = train_src_data_path + "_bert_original_score.json"
val_out_path = val_src_data_path + "_bert_original_score.json"
test_out_path = test_src_data_path + "_bert_original_score.json"
# loading model
# model = MySimCSE("princeton-nlp/sup-simcse-roberta-large", device='cpu')
# model = MySimCSE("/home/qiupeng/frz_project/SimCSE/result/retrieval_bert_chinese_base", device='cuda', pooler='cls')
model = MySimCSE("bert-base-chinese", device='cuda', pooler='cls')
# read training documents
documents = []
with open(train_src_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
documents.append(line)
print("The number of training documents is: ", len(documents))
# read val queries
val_queries = []
with open(val_src_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
val_queries.append(line)
print("The number of val queries is: ", len(val_queries))
# read test queries
test_queries = []
with open(test_src_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
test_queries.append(line)
print("The number of test queries is: ", len(test_queries))
# create index
model.build_index(documents, device='cuda', batch_size=64)
# training query
train_query_result = []
print("Start to create training queries result...")
for i in tqdm(range(len(documents))):
results = model.search(documents[i], device='cuda', threshold=-99, top_k=11)
for k in range(len(results)):
if results[k][0] == i:
results.pop(k)
break
if len(results) > 10:
results = results[:10]
train_query_item = dict()
train_query_item['index'] = [ind for ind, score in results]
train_query_item['score'] = [score for ind, score in results]
train_query_result.append(train_query_item)
json_str = json.dumps(train_query_result, indent=4)
with open(train_out_path, 'w', encoding='utf-8') as f:
f.write(json_str)
print("Finish creating training queries result!")
# val query
val_query_result = []
print("Start to create val queries result...")
for i in tqdm(range(len(val_queries))):
query = val_queries[i]
results = model.search(query, device='cuda', threshold=-99, top_k=10)
val_query_item = dict()
val_query_item['index'] = [ind for ind, score in results]
val_query_item['score'] = [score for ind, score in results]
val_query_result.append(val_query_item)
json_str = json.dumps(val_query_result, indent=4)
with open(val_out_path, 'w', encoding='utf-8') as f:
f.write(json_str)
print("Finish creating val queries result!")
# test query
test_query_result = []
print("Start to create test queries result...")
for i in tqdm(range(len(test_queries))):
query = test_queries[i]
results = model.search(query, device='cuda', threshold=-99, top_k=10)
test_query_item = dict()
test_query_item['index'] = [ind for ind, score in results]
test_query_item['score'] = [score for ind, score in results]
test_query_result.append(test_query_item)
json_str = json.dumps(test_query_result, indent=4)
with open(test_out_path, 'w', encoding='utf-8') as f:
f.write(json_str)
print("Finish creating test queries result!")
def clean_repetition_datasets(str_data_path, dst_data_path):
# completed
str_out_path = str_data_path + "_after_cleaning.txt"
dst_out_path = dst_data_path + "_after_cleaning.txt"
documents = []
dst = []
with open(str_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
documents.append(line)
with open(dst_data_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
dst.append(line)
print(len(documents))
print(len(dst))
new_doc = []
new_dst = []
for idx in range(len(documents)):
if documents[idx] not in new_doc or dst[idx] not in new_dst:
new_doc.append(documents[idx])
new_dst.append(dst[idx])
else:
print(idx)
print(documents[idx])
print(dst[idx])
print('=' * 30)
print(len(new_doc))
print(len(new_dst))
with open(str_out_path, 'w', encoding='utf-8') as f:
for doc in new_doc:
f.write(doc + '\n')
with open(dst_out_path, 'w', encoding='utf-8') as f:
for d in new_dst:
f.write(d + '\n')
def preprocess_wangyue_data(post_path, conv_path, tag_path, src_path, dst_path):
post_list = []
with open(post_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
post_list.append(line.strip())
conv_list = []
with open(conv_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
conv_list.append(line.strip())
tag_list = []
with open(tag_path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip("\n")
if not line:
continue
tag_list.append(line.strip())
assert len(post_list) == len(conv_list) and len(conv_list) == len(tag_list)
src_list = []
dst_list = []
for i in range(len(post_list)):
src = post_list[i] + '. ' + conv_list[i]
dst = tag_list[i].replace(';', ' [SEP] ')
src_list.append(src)
dst_list.append(dst)
with open(src_path, 'w', encoding='utf-8') as f:
for src in src_list:
f.write(src + '\n')
with open(dst_path, 'w', encoding='utf-8') as f:
for dst in dst_list:
f.write(dst + '\n')
def compute_hashtag_coverage(labels, hashtags):
total_r = len(labels)
total_p = len(hashtags)
label_list = labels.copy()
hashtag_list = hashtags.copy()
true_num = 0
for lab in label_list:
for hashtag in hashtag_list:
if lab == hashtag:
true_num += 1
hashtag_list.remove(lab)
break
p = true_num / total_p
r = true_num / total_r | f = f1(p, r) | 3 | 2023-12-16 06:00:53+00:00 | 8k |
ilyamiro/Stewart | GUI/console_gui.py | [
{
"identifier": "Core",
"path": "Core/Core.py",
"snippet": "class Core:\n def __init__(self):\n core_logger.debug(\"Core execution started\")\n\n # Initializing main supportive classes\n self.synthesizer = Synthesizer()\n self.recognition = Voice()\n self.data = Dat... | import random
import sys
import threading
import subprocess
import os
import time
import psutil
from rich import print as rprint
from rich.table import Table
from rich.progress import track
from rich.console import Console
from rich.markdown import Markdown
from rich.prompt import Prompt, Confirm
from rich.panel import Panel, Style
from rich.tree import Tree
from rich.layout import Layout
from Core.Core import Core
from Command_System.CommandTree import CommandTree | 4,581 |
sys.path.append(os.path.abspath(os.path.join(os.getcwd(), os.pardir)))
sys.path.append(os.path.abspath(os.getcwd()))
if sys.platform == "linux":
# required for proper pyautogui and audio workflow
subprocess.Popen("jack_control start", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
subprocess.Popen("xhost +local:$USER", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
class GUI:
def __init__(self):
self.std = Console()
self.input = Prompt.ask
self.print = rprint
self.plugin_nums = {}
self.back = """
Press [strong]Enter[/] to go back [red]<--[/]
"""
|
sys.path.append(os.path.abspath(os.path.join(os.getcwd(), os.pardir)))
sys.path.append(os.path.abspath(os.getcwd()))
if sys.platform == "linux":
# required for proper pyautogui and audio workflow
subprocess.Popen("jack_control start", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
subprocess.Popen("xhost +local:$USER", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
class GUI:
def __init__(self):
self.std = Console()
self.input = Prompt.ask
self.print = rprint
self.plugin_nums = {}
self.back = """
Press [strong]Enter[/] to go back [red]<--[/]
""" | self.core = Core() | 0 | 2023-12-16 12:24:15+00:00 | 8k |
LLM-Evaluation-s-Always-Fatiguing/leaf-playground-hub | who_is_the_spy/who_is_the_spy/scene.py | [
{
"identifier": "Moderator",
"path": "who_is_the_spy/who_is_the_spy/agents/moderator.py",
"snippet": "class Moderator(\n SceneStaticAgent,\n role_definition=ROLE_DEFINITION,\n cls_description=\"An agent who moderate the game: Who is the Spy\"\n):\n config_cls = ModeratorConfig\n config: c... | import asyncio
import random
from typing import List, Optional, Type, Union
from pydantic import Field
from leaf_playground.core.workers import Logger
from leaf_playground.core.scene import Scene
from leaf_playground.core.scene_definition import SceneConfig
from leaf_playground.data.log_body import ActionLogBody
from leaf_playground.data.media import Text
from .agents.moderator import Moderator
from .agents.player import BaseAIPlayer
from .agents.human_player import HumanPlayer
from .scene_definition import * | 5,933 |
Player = Union[BaseAIPlayer, HumanPlayer]
class WhoIsTheSpyLogBody(ActionLogBody):
references: Optional[List[MessageTypes]] = Field(default=None)
response: MessageTypes = Field(default=...)
game_id: int = Field(default=...)
round_id: int = Field(default=...)
WhoIsTheSpySceneConfig = SceneConfig.create_config_model(
SCENE_DEFINITION,
additional_config_fields={
"debug_mode": (bool, Field(default=False, exclude=True))
}
)
class WhoIsTheSpyScene(Scene, scene_definition=SCENE_DEFINITION, log_body_class=WhoIsTheSpyLogBody):
config_cls = WhoIsTheSpySceneConfig
config: config_cls
log_body_class: Type[WhoIsTheSpyLogBody]
def __init__(self, config: config_cls, logger: Logger):
super().__init__(config=config, logger=logger)
|
Player = Union[BaseAIPlayer, HumanPlayer]
class WhoIsTheSpyLogBody(ActionLogBody):
references: Optional[List[MessageTypes]] = Field(default=None)
response: MessageTypes = Field(default=...)
game_id: int = Field(default=...)
round_id: int = Field(default=...)
WhoIsTheSpySceneConfig = SceneConfig.create_config_model(
SCENE_DEFINITION,
additional_config_fields={
"debug_mode": (bool, Field(default=False, exclude=True))
}
)
class WhoIsTheSpyScene(Scene, scene_definition=SCENE_DEFINITION, log_body_class=WhoIsTheSpyLogBody):
config_cls = WhoIsTheSpySceneConfig
config: config_cls
log_body_class: Type[WhoIsTheSpyLogBody]
def __init__(self, config: config_cls, logger: Logger):
super().__init__(config=config, logger=logger)
| self.moderator: Moderator = self.static_agents["moderator"][0] | 0 | 2023-12-21 03:09:08+00:00 | 8k |
djkcyl/ABot-NT | utils/text2image.py | [
{
"identifier": "AdvertisementCategory",
"path": "models/ad.py",
"snippet": "class AdvertisementCategory(str, Enum):\n business = \"商业\"\n public_welfare = \"公益\"\n announcement = \"公告\"\n tips = \"提示\""
},
{
"identifier": "AiohttpClientService",
"path": "services/aiohttp.py",
... | import asyncio
import hashlib
import random
import re
from base64 import b64encode
from datetime import datetime, timedelta
from io import BytesIO
from pathlib import Path
from graiax.text2img.playwright import (
HTMLRenderer,
MarkdownConverter,
PageOption,
ScreenshotOption,
convert_text,
)
from graiax.text2img.playwright.renderer import BuiltinCSS
from jinja2 import Template
from launart import Launart
from loguru import logger
from PIL import Image, ImageDraw, ImageFont
from playwright.async_api._generated import Request
from qrcode.image.styledpil import StyledPilImage
from qrcode.main import QRCode
from models.ad import AdvertisementCategory
from services import AiohttpClientService, S3FileService
from utils.builder import ADBuilder
from utils.datetime import CHINA_TZ
from .fonts_provider import fill_font
from .strings import get_cut_str | 3,800 | qrcode.clear()
qrcode.add_data("https://qun.qq.com/qunpro/robot/qunshare?robot_appid=101985270&robot_uin=2854214511")
invite_group: Image.Image = qrcode.make_image(fill_color="black", back_color="#fafafac0").get_image().resize((200, 200))
bio = BytesIO()
invite_group.save(bio, format="PNG")
group_b64 = b64encode(bio.getvalue()).decode()
footer_css = Path("./static/css/footer.css").read_text()
html_render = HTMLRenderer(
page_option=PageOption(device_scale_factor=1.5),
screenshot_option=ScreenshotOption(type="jpeg", quality=80, full_page=True, scale="device"),
css=(
BuiltinCSS.reset,
BuiltinCSS.github,
BuiltinCSS.one_dark,
BuiltinCSS.container,
"@font-face{font-family:'harmo';font-weight:300;"
"src:url('http://font.static.abot/HarmonyOS_Sans_SC_Light.ttf') format('truetype');}"
"@font-face{font-family:'harmo';font-weight:400;"
"src:url('http://font.static.abot/HarmonyOS_Sans_SC_Regular.ttf') format('truetype');}"
"@font-face{font-family:'harmo';font-weight:500;"
"src:url('http://font.static.abot/HarmonyOS_Sans_SC_Medium.ttf') format('truetype');}"
"@font-face{font-family:'harmo';font-weight:600;"
"src:url('http://font.static.abot/HarmonyOS_Sans_SC_Bold.ttf') format('truetype');}"
"*{font-family:'harmo',sans-serif}",
"body{background-color:#fafafac0;}",
"@media(prefers-color-scheme:light){.markdown-body{--color-canvas-default:#fafafac0;}}",
footer_css,
),
page_modifiers=[
lambda page: page.route(re.compile("^http://font.static.abot/(.+)$"), fill_font),
# lambda page: page.on("requestfailed", network_requestfailed),
],
)
md_converter = MarkdownConverter()
def network_requestfailed(request: Request) -> None:
url = request.url
fail = request.failure
method = request.method
logger.warning(f"[RequestFailed] [{method} {fail}] << {url}")
async def add_footer(
category: AdvertisementCategory = AdvertisementCategory.announcement,
target_audience: list | None = None,
) -> str:
if target_audience is None:
target_audience = []
ad = await ADBuilder.get_ad(category, target_audience=target_audience)
if random.random() > DEFAULT_AD_PROBABILITY and ad:
ad_type = ad.ad_category.value
if ad.content_type == 0:
ad_p = "<p>" + "</p><p>".join(ad.content.splitlines()) + "</p>"
ad_html = (
"<style>.ad-text::before{content: '" + ad_type + "'}</style>"
f'<div class="ad-text"><div class="text-area">{ad_p}</div></div>'
)
else:
s3file = Launart.current().get_component(S3FileService).s3file
ad_image = await s3file.get_object(ad.content)
ad_base64 = b64encode(await ad_image.read()).decode()
ad_html = (
"<style>.ad-img::before{content: '" + ad_type + "'}</style>"
f'<div class="ad-img"><img src="data:image/png;base64,{ad_base64}"/></div>'
)
else:
ad_type = "一言"
session = Launart.current().get_component(AiohttpClientService).session
async with session.get("https://v1.hitokoto.cn/?encode=text") as resp:
yiyan = await resp.text()
ad_html = (
"<style>.ad-text::before{content: '" + ad_type + "'}</style>"
f'<div class="ad-text"><div class="text-area">{yiyan}</div></div>'
)
return f"""
<div style="position:absolute;left:0;width:100%">
<footer>
<section class="left">
<div class="footer-text">
<p style="font-weight: bold">该图片由 ABot 生成</p>
<p style="font-size: 14px">{datetime.now(CHINA_TZ).strftime("%Y/%m/%d %p %I:%M:%S")}</p>
</div>
<section class="ad">{ad_html}</section>
</section>
<section class="right">
<div class="qrcode-area">
<img class="qrcode" src="data:image/png;base64,{group_b64}" />
<img class="qrcode" src="data:image/png;base64,{guild_b64}" />
</div>
<div class="qrcode-text">
<p>扫描二维码将 ABot 添加至你的群聊/频道</p>
</div>
</section>
</footer>
<section class="powered">Powered by Avilla</section>
</div>
"""
async def create_image(text: str, cut: int = 64) -> bytes:
str_hash = hashlib.sha256(text.encode("utf-8")).hexdigest()
cache.joinpath(str_hash[:2]).mkdir(exist_ok=True)
cache_file = cache.joinpath(f"{str_hash}.jpg")
if cache_file.exists():
logger.info(f"T2I Cache hit: {str_hash}")
image_bytes = cache_file.read_bytes()
else:
image_bytes = await asyncio.to_thread(_create_pil_image, text, cut)
cache_file.write_bytes(image_bytes)
return image_bytes
def _create_pil_image(text: str, cut: int) -> bytes:
|
# 广告出现的概率
DEFAULT_AD_PROBABILITY = 0.7
font_file = "./static/font/sarasa-mono-sc-semibold.ttf"
font = ImageFont.truetype(font_file, 22)
cache = Path("cache", "t2i")
cache.mkdir(exist_ok=True, parents=True)
qrcode = QRCode(image_factory=StyledPilImage)
qrcode.add_data("https://qun.qq.com/qunpro/robot/share?robot_appid=101985270")
invite_guild: Image.Image = qrcode.make_image(fill_color="black", back_color="#fafafac0").get_image().resize((200, 200))
bio = BytesIO()
invite_guild.save(bio, format="PNG")
guild_b64 = b64encode(bio.getvalue()).decode()
qrcode.clear()
qrcode.add_data("https://qun.qq.com/qunpro/robot/qunshare?robot_appid=101985270&robot_uin=2854214511")
invite_group: Image.Image = qrcode.make_image(fill_color="black", back_color="#fafafac0").get_image().resize((200, 200))
bio = BytesIO()
invite_group.save(bio, format="PNG")
group_b64 = b64encode(bio.getvalue()).decode()
footer_css = Path("./static/css/footer.css").read_text()
html_render = HTMLRenderer(
page_option=PageOption(device_scale_factor=1.5),
screenshot_option=ScreenshotOption(type="jpeg", quality=80, full_page=True, scale="device"),
css=(
BuiltinCSS.reset,
BuiltinCSS.github,
BuiltinCSS.one_dark,
BuiltinCSS.container,
"@font-face{font-family:'harmo';font-weight:300;"
"src:url('http://font.static.abot/HarmonyOS_Sans_SC_Light.ttf') format('truetype');}"
"@font-face{font-family:'harmo';font-weight:400;"
"src:url('http://font.static.abot/HarmonyOS_Sans_SC_Regular.ttf') format('truetype');}"
"@font-face{font-family:'harmo';font-weight:500;"
"src:url('http://font.static.abot/HarmonyOS_Sans_SC_Medium.ttf') format('truetype');}"
"@font-face{font-family:'harmo';font-weight:600;"
"src:url('http://font.static.abot/HarmonyOS_Sans_SC_Bold.ttf') format('truetype');}"
"*{font-family:'harmo',sans-serif}",
"body{background-color:#fafafac0;}",
"@media(prefers-color-scheme:light){.markdown-body{--color-canvas-default:#fafafac0;}}",
footer_css,
),
page_modifiers=[
lambda page: page.route(re.compile("^http://font.static.abot/(.+)$"), fill_font),
# lambda page: page.on("requestfailed", network_requestfailed),
],
)
md_converter = MarkdownConverter()
def network_requestfailed(request: Request) -> None:
url = request.url
fail = request.failure
method = request.method
logger.warning(f"[RequestFailed] [{method} {fail}] << {url}")
async def add_footer(
category: AdvertisementCategory = AdvertisementCategory.announcement,
target_audience: list | None = None,
) -> str:
if target_audience is None:
target_audience = []
ad = await ADBuilder.get_ad(category, target_audience=target_audience)
if random.random() > DEFAULT_AD_PROBABILITY and ad:
ad_type = ad.ad_category.value
if ad.content_type == 0:
ad_p = "<p>" + "</p><p>".join(ad.content.splitlines()) + "</p>"
ad_html = (
"<style>.ad-text::before{content: '" + ad_type + "'}</style>"
f'<div class="ad-text"><div class="text-area">{ad_p}</div></div>'
)
else:
s3file = Launart.current().get_component(S3FileService).s3file
ad_image = await s3file.get_object(ad.content)
ad_base64 = b64encode(await ad_image.read()).decode()
ad_html = (
"<style>.ad-img::before{content: '" + ad_type + "'}</style>"
f'<div class="ad-img"><img src="data:image/png;base64,{ad_base64}"/></div>'
)
else:
ad_type = "一言"
session = Launart.current().get_component(AiohttpClientService).session
async with session.get("https://v1.hitokoto.cn/?encode=text") as resp:
yiyan = await resp.text()
ad_html = (
"<style>.ad-text::before{content: '" + ad_type + "'}</style>"
f'<div class="ad-text"><div class="text-area">{yiyan}</div></div>'
)
return f"""
<div style="position:absolute;left:0;width:100%">
<footer>
<section class="left">
<div class="footer-text">
<p style="font-weight: bold">该图片由 ABot 生成</p>
<p style="font-size: 14px">{datetime.now(CHINA_TZ).strftime("%Y/%m/%d %p %I:%M:%S")}</p>
</div>
<section class="ad">{ad_html}</section>
</section>
<section class="right">
<div class="qrcode-area">
<img class="qrcode" src="data:image/png;base64,{group_b64}" />
<img class="qrcode" src="data:image/png;base64,{guild_b64}" />
</div>
<div class="qrcode-text">
<p>扫描二维码将 ABot 添加至你的群聊/频道</p>
</div>
</section>
</footer>
<section class="powered">Powered by Avilla</section>
</div>
"""
async def create_image(text: str, cut: int = 64) -> bytes:
str_hash = hashlib.sha256(text.encode("utf-8")).hexdigest()
cache.joinpath(str_hash[:2]).mkdir(exist_ok=True)
cache_file = cache.joinpath(f"{str_hash}.jpg")
if cache_file.exists():
logger.info(f"T2I Cache hit: {str_hash}")
image_bytes = cache_file.read_bytes()
else:
image_bytes = await asyncio.to_thread(_create_pil_image, text, cut)
cache_file.write_bytes(image_bytes)
return image_bytes
def _create_pil_image(text: str, cut: int) -> bytes: | cut_str = "\n".join(get_cut_str(text, cut)) | 6 | 2023-12-16 13:19:56+00:00 | 8k |
Varexa/Gateway | chat_exporter/construct/message.py | [
{
"identifier": "discord",
"path": "chat_exporter/ext/discord_import.py",
"snippet": ""
},
{
"identifier": "Embed",
"path": "chat_exporter/construct/assets/embed.py",
"snippet": "class Embed:\r\n r: str\r\n g: str\r\n b: str\r\n title: str\r\n description: str\r\n autho... | import html
from typing import List, Optional, Union
from pytz import timezone
from datetime import timedelta
from chat_exporter.ext.discord_import import discord
from chat_exporter.construct.assets import Attachment, Component, Embed, Reaction
from chat_exporter.ext.discord_utils import DiscordUtils
from chat_exporter.ext.html_generator import (
fill_out,
bot_tag,
bot_tag_verified,
message_body,
message_pin,
message_thread,
message_content,
message_reference,
message_reference_unknown,
message_interaction,
img_attachment,
start_message,
end_message,
PARSE_MODE_NONE,
PARSE_MODE_MARKDOWN,
PARSE_MODE_REFERENCE,
)
| 6,409 | if isinstance(e, discord.NotFound):
self.message.reference = message_reference_unknown
return
is_bot = _gather_user_bot(message.author)
user_colour = await self._gather_user_colour(message.author)
if not message.content and not message.interaction:
message.content = "Click to see attachment"
elif not message.content and message.interaction:
message.content = "Click to see command"
icon = ""
if not message.interaction and (message.embeds or message.attachments):
icon = DiscordUtils.reference_attachment_icon
elif message.interaction:
icon = DiscordUtils.interaction_command_icon
_, message_edited_at = self.set_time(message)
if message_edited_at:
message_edited_at = _set_edit_at(message_edited_at)
avatar_url = message.author.display_avatar if message.author.display_avatar else DiscordUtils.default_avatar
self.message.reference = await fill_out(self.guild, message_reference, [
("AVATAR_URL", str(avatar_url), PARSE_MODE_NONE),
("BOT_TAG", is_bot, PARSE_MODE_NONE),
("NAME_TAG", "%s#%s" % (message.author.name, message.author.discriminator), PARSE_MODE_NONE),
("NAME", str(html.escape(message.author.display_name))),
("USER_COLOUR", user_colour, PARSE_MODE_NONE),
("CONTENT", message.content, PARSE_MODE_REFERENCE),
("EDIT", message_edited_at, PARSE_MODE_NONE),
("ICON", icon, PARSE_MODE_NONE),
("USER_ID", str(message.author.id), PARSE_MODE_NONE),
("MESSAGE_ID", str(self.message.reference.message_id), PARSE_MODE_NONE),
])
async def build_interaction(self):
if not self.message.interaction:
self.message.interaction = ""
return
user: Union[discord.Member, discord.User] = self.message.interaction.user
is_bot = _gather_user_bot(user)
user_colour = await self._gather_user_colour(user)
avatar_url = user.display_avatar if user.display_avatar else DiscordUtils.default_avatar
self.message.interaction = await fill_out(self.guild, message_interaction, [
("AVATAR_URL", str(avatar_url), PARSE_MODE_NONE),
("BOT_TAG", is_bot, PARSE_MODE_NONE),
("NAME_TAG", "%s#%s" % (user.name, user.discriminator), PARSE_MODE_NONE),
("NAME", str(html.escape(user.display_name))),
("USER_COLOUR", user_colour, PARSE_MODE_NONE),
("FILLER", "used ", PARSE_MODE_NONE),
("COMMAND", "/" + self.message.interaction.name, PARSE_MODE_NONE),
("USER_ID", str(user.id), PARSE_MODE_NONE),
("INTERACTION_ID", str(self.message.interaction.id), PARSE_MODE_NONE),
])
async def build_sticker(self):
if not self.message.stickers or not hasattr(self.message.stickers[0], "url"):
return
sticker_image_url = self.message.stickers[0].url
if sticker_image_url.endswith(".json"):
sticker = await self.message.stickers[0].fetch()
sticker_image_url = (
f"https://cdn.jsdelivr.net/gh/mahtoid/DiscordUtils@master/stickers/{sticker.pack_id}/{sticker.id}.gif"
)
self.message.content = await fill_out(self.guild, img_attachment, [
("ATTACH_URL", str(sticker_image_url), PARSE_MODE_NONE),
("ATTACH_URL_THUMB", str(sticker_image_url), PARSE_MODE_NONE)
])
async def build_assets(self):
for e in self.message.embeds:
self.embeds += await Embed(e, self.guild).flow()
for a in self.message.attachments:
self.attachments += await Attachment(a, self.guild).flow()
for c in self.message.components:
self.components += await Component(c, self.guild).flow()
for r in self.message.reactions:
self.reactions += await Reaction(r, self.guild).flow()
if self.reactions:
self.reactions = f'<div class="chatlog__reactions">{self.reactions}</div>'
async def build_message_template(self):
started = await self.generate_message_divider()
if started:
return self.message_html
self.message_html += await fill_out(self.guild, message_body, [
("MESSAGE_ID", str(self.message.id)),
("MESSAGE_CONTENT", self.message.content, PARSE_MODE_NONE),
("EMBEDS", self.embeds, PARSE_MODE_NONE),
("ATTACHMENTS", self.attachments, PARSE_MODE_NONE),
("COMPONENTS", self.components, PARSE_MODE_NONE),
("EMOJI", self.reactions, PARSE_MODE_NONE),
("TIMESTAMP", self.message_created_at, PARSE_MODE_NONE),
("TIME", self.message_created_at.split()[-1], PARSE_MODE_NONE),
])
return self.message_html
def _generate_message_divider_check(self):
return bool(
self.previous_message is None or self.message.reference != "" or self.message.interaction != "" or
self.previous_message.author.id != self.message.author.id or self.message.webhook_id is not None or
self.message.created_at > (self.previous_message.created_at + timedelta(minutes=4))
)
async def generate_message_divider(self, channel_audit=False):
if channel_audit or self._generate_message_divider_check():
if self.previous_message is not None:
|
def _gather_user_bot(author: discord.Member):
if author.bot and author.public_flags.verified_bot:
return bot_tag_verified
elif author.bot:
return bot_tag
return ""
def _set_edit_at(message_edited_at):
return f'<span class="chatlog__reference-edited-timestamp" title="{message_edited_at}">(edited)</span>'
class MessageConstruct:
message_html: str = ""
# Asset Types
embeds: str = ""
reactions: str = ""
components: str = ""
attachments: str = ""
time_format: str = ""
def __init__(
self,
message: discord.Message,
previous_message: Optional[discord.Message],
pytz_timezone,
military_time: bool,
guild: discord.Guild,
meta_data: dict
):
self.message = message
self.previous_message = previous_message
self.pytz_timezone = pytz_timezone
self.military_time = military_time
self.guild = guild
self.time_format = "%A, %e %B %Y %I:%M %p"
if self.military_time:
self.time_format = "%A, %e %B %Y %H:%M"
self.message_created_at, self.message_edited_at = self.set_time()
self.meta_data = meta_data
async def construct_message(
self,
) -> (str, dict):
if discord.MessageType.pins_add == self.message.type:
await self.build_pin()
elif discord.MessageType.thread_created == self.message.type:
await self.build_thread()
else:
await self.build_message()
return self.message_html, self.meta_data
async def build_message(self):
await self.build_content()
await self.build_reference()
await self.build_interaction()
await self.build_sticker()
await self.build_assets()
await self.build_message_template()
await self.build_meta_data()
async def build_pin(self):
await self.generate_message_divider(channel_audit=True)
await self.build_pin_template()
async def build_thread(self):
await self.generate_message_divider(channel_audit=True)
await self.build_thread_template()
async def build_meta_data(self):
user_id = self.message.author.id
if user_id in self.meta_data:
self.meta_data[user_id][4] += 1
else:
user_name_discriminator = self.message.author.name + "#" + self.message.author.discriminator
user_created_at = self.message.author.created_at
user_bot = _gather_user_bot(self.message.author)
user_avatar = (
self.message.author.display_avatar if self.message.author.display_avatar
else DiscordUtils.default_avatar
)
user_joined_at = self.message.author.joined_at if hasattr(self.message.author, "joined_at") else None
user_display_name = (
f'<div class="meta__display-name">{self.message.author.display_name}</div>'
if self.message.author.display_name != self.message.author.name
else ""
)
self.meta_data[user_id] = [
user_name_discriminator, user_created_at, user_bot, user_avatar, 1, user_joined_at, user_display_name
]
async def build_content(self):
if not self.message.content:
self.message.content = ""
return
if self.message_edited_at:
self.message_edited_at = _set_edit_at(self.message_edited_at)
self.message.content = html.escape(self.message.content)
self.message.content = await fill_out(self.guild, message_content, [
("MESSAGE_CONTENT", self.message.content, PARSE_MODE_MARKDOWN),
("EDIT", self.message_edited_at, PARSE_MODE_NONE)
])
async def build_reference(self):
if not self.message.reference:
self.message.reference = ""
return
try:
message: discord.Message = await self.message.channel.fetch_message(self.message.reference.message_id)
except (discord.NotFound, discord.HTTPException) as e:
self.message.reference = ""
if isinstance(e, discord.NotFound):
self.message.reference = message_reference_unknown
return
is_bot = _gather_user_bot(message.author)
user_colour = await self._gather_user_colour(message.author)
if not message.content and not message.interaction:
message.content = "Click to see attachment"
elif not message.content and message.interaction:
message.content = "Click to see command"
icon = ""
if not message.interaction and (message.embeds or message.attachments):
icon = DiscordUtils.reference_attachment_icon
elif message.interaction:
icon = DiscordUtils.interaction_command_icon
_, message_edited_at = self.set_time(message)
if message_edited_at:
message_edited_at = _set_edit_at(message_edited_at)
avatar_url = message.author.display_avatar if message.author.display_avatar else DiscordUtils.default_avatar
self.message.reference = await fill_out(self.guild, message_reference, [
("AVATAR_URL", str(avatar_url), PARSE_MODE_NONE),
("BOT_TAG", is_bot, PARSE_MODE_NONE),
("NAME_TAG", "%s#%s" % (message.author.name, message.author.discriminator), PARSE_MODE_NONE),
("NAME", str(html.escape(message.author.display_name))),
("USER_COLOUR", user_colour, PARSE_MODE_NONE),
("CONTENT", message.content, PARSE_MODE_REFERENCE),
("EDIT", message_edited_at, PARSE_MODE_NONE),
("ICON", icon, PARSE_MODE_NONE),
("USER_ID", str(message.author.id), PARSE_MODE_NONE),
("MESSAGE_ID", str(self.message.reference.message_id), PARSE_MODE_NONE),
])
async def build_interaction(self):
if not self.message.interaction:
self.message.interaction = ""
return
user: Union[discord.Member, discord.User] = self.message.interaction.user
is_bot = _gather_user_bot(user)
user_colour = await self._gather_user_colour(user)
avatar_url = user.display_avatar if user.display_avatar else DiscordUtils.default_avatar
self.message.interaction = await fill_out(self.guild, message_interaction, [
("AVATAR_URL", str(avatar_url), PARSE_MODE_NONE),
("BOT_TAG", is_bot, PARSE_MODE_NONE),
("NAME_TAG", "%s#%s" % (user.name, user.discriminator), PARSE_MODE_NONE),
("NAME", str(html.escape(user.display_name))),
("USER_COLOUR", user_colour, PARSE_MODE_NONE),
("FILLER", "used ", PARSE_MODE_NONE),
("COMMAND", "/" + self.message.interaction.name, PARSE_MODE_NONE),
("USER_ID", str(user.id), PARSE_MODE_NONE),
("INTERACTION_ID", str(self.message.interaction.id), PARSE_MODE_NONE),
])
async def build_sticker(self):
if not self.message.stickers or not hasattr(self.message.stickers[0], "url"):
return
sticker_image_url = self.message.stickers[0].url
if sticker_image_url.endswith(".json"):
sticker = await self.message.stickers[0].fetch()
sticker_image_url = (
f"https://cdn.jsdelivr.net/gh/mahtoid/DiscordUtils@master/stickers/{sticker.pack_id}/{sticker.id}.gif"
)
self.message.content = await fill_out(self.guild, img_attachment, [
("ATTACH_URL", str(sticker_image_url), PARSE_MODE_NONE),
("ATTACH_URL_THUMB", str(sticker_image_url), PARSE_MODE_NONE)
])
async def build_assets(self):
for e in self.message.embeds:
self.embeds += await Embed(e, self.guild).flow()
for a in self.message.attachments:
self.attachments += await Attachment(a, self.guild).flow()
for c in self.message.components:
self.components += await Component(c, self.guild).flow()
for r in self.message.reactions:
self.reactions += await Reaction(r, self.guild).flow()
if self.reactions:
self.reactions = f'<div class="chatlog__reactions">{self.reactions}</div>'
async def build_message_template(self):
started = await self.generate_message_divider()
if started:
return self.message_html
self.message_html += await fill_out(self.guild, message_body, [
("MESSAGE_ID", str(self.message.id)),
("MESSAGE_CONTENT", self.message.content, PARSE_MODE_NONE),
("EMBEDS", self.embeds, PARSE_MODE_NONE),
("ATTACHMENTS", self.attachments, PARSE_MODE_NONE),
("COMPONENTS", self.components, PARSE_MODE_NONE),
("EMOJI", self.reactions, PARSE_MODE_NONE),
("TIMESTAMP", self.message_created_at, PARSE_MODE_NONE),
("TIME", self.message_created_at.split()[-1], PARSE_MODE_NONE),
])
return self.message_html
def _generate_message_divider_check(self):
return bool(
self.previous_message is None or self.message.reference != "" or self.message.interaction != "" or
self.previous_message.author.id != self.message.author.id or self.message.webhook_id is not None or
self.message.created_at > (self.previous_message.created_at + timedelta(minutes=4))
)
async def generate_message_divider(self, channel_audit=False):
if channel_audit or self._generate_message_divider_check():
if self.previous_message is not None:
| self.message_html += await fill_out(self.guild, end_message, [])
| 6 | 2023-12-18 14:17:31+00:00 | 8k |
mariaalfaroc/a2s-transformer | train.py | [
{
"identifier": "CTCTrainedCRNN",
"path": "networks/crnn/model.py",
"snippet": "class CTCTrainedCRNN(LightningModule):\n def __init__(\n self, w2i, i2w, ytest_i2w=None, max_audio_len=100, frame_multiplier_factor=8\n ):\n super(CTCTrainedCRNN, self).__init__()\n # Save hyperpar... | import gc
import fire
import torch
from lightning.pytorch import Trainer
from lightning.pytorch.callbacks import EarlyStopping, ModelCheckpoint
from lightning.pytorch.loggers.wandb import WandbLogger
from networks.crnn.model import CTCTrainedCRNN
from networks.transformer.model import A2STransformer
from my_utils.ctc_dataset import CTCDataModule
from my_utils.ar_dataset import ARDataModule
from my_utils.seed import seed_everything | 4,405 |
seed_everything(42, benchmark=False)
def train(
ds_name,
model_type: str = "crnn",
attn_window: int = -1,
use_voice_change_token: bool = False,
epochs: int = 1000,
patience: int = 20,
batch_size: int = 16,
):
gc.collect()
torch.cuda.empty_cache()
# Experiment info
print("TRAIN EXPERIMENT")
print(f"\tDataset: {ds_name}")
print(f"\tModel type: {model_type}")
print(f"\tAttention window: {attn_window} (Used if model type is transformer)")
print(f"\tUse voice change token: {use_voice_change_token}")
print(f"\tEpochs: {epochs}")
print(f"\tPatience: {patience}")
print(f"\tBatch size: {batch_size}")
if model_type == "crnn":
# Data module
datamodule = CTCDataModule(
ds_name=ds_name,
use_voice_change_token=use_voice_change_token,
batch_size=batch_size,
)
datamodule.setup(stage="fit")
w2i, i2w = datamodule.get_w2i_and_i2w()
# Model
model = CTCTrainedCRNN(
w2i=w2i,
i2w=i2w,
max_audio_len=datamodule.get_max_audio_len(),
frame_multiplier_factor=datamodule.get_frame_multiplier_factor(),
)
# Override the datamodule width reduction factors with that of the model
datamodule.width_reduction = model.width_reduction
elif model_type == "transformer":
# Data module
|
seed_everything(42, benchmark=False)
def train(
ds_name,
model_type: str = "crnn",
attn_window: int = -1,
use_voice_change_token: bool = False,
epochs: int = 1000,
patience: int = 20,
batch_size: int = 16,
):
gc.collect()
torch.cuda.empty_cache()
# Experiment info
print("TRAIN EXPERIMENT")
print(f"\tDataset: {ds_name}")
print(f"\tModel type: {model_type}")
print(f"\tAttention window: {attn_window} (Used if model type is transformer)")
print(f"\tUse voice change token: {use_voice_change_token}")
print(f"\tEpochs: {epochs}")
print(f"\tPatience: {patience}")
print(f"\tBatch size: {batch_size}")
if model_type == "crnn":
# Data module
datamodule = CTCDataModule(
ds_name=ds_name,
use_voice_change_token=use_voice_change_token,
batch_size=batch_size,
)
datamodule.setup(stage="fit")
w2i, i2w = datamodule.get_w2i_and_i2w()
# Model
model = CTCTrainedCRNN(
w2i=w2i,
i2w=i2w,
max_audio_len=datamodule.get_max_audio_len(),
frame_multiplier_factor=datamodule.get_frame_multiplier_factor(),
)
# Override the datamodule width reduction factors with that of the model
datamodule.width_reduction = model.width_reduction
elif model_type == "transformer":
# Data module | datamodule = ARDataModule( | 3 | 2023-12-18 20:01:00+00:00 | 8k |
yacinxx/dnakey | app.py | [
{
"identifier": "CreateProfile",
"path": "create_profile.py",
"snippet": "class CreateProfile(PrimeKeyConfig):\r\n def new_profile(self):\r\n key_id = \"prime-key-profile\"\r\n self.hash_key = st.text_input(\"Enter Your Prime Key: (:red[Required])\", \r\n ... | import streamlit as st
from create_profile import CreateProfile
from create_password import CreatePassword
from feedbacks.send_feedbacks import Feedbacks
from license.license_manager import CO_FOUNDER, VERSION
| 5,133 |
# Set Streamlit page configuration
st.set_page_config(
page_title="Dnakey",
page_icon="🔐",
layout="centered",
)
|
# Set Streamlit page configuration
st.set_page_config(
page_title="Dnakey",
page_icon="🔐",
layout="centered",
)
| class App(CreateProfile, CreatePassword, Feedbacks):
| 0 | 2023-12-18 22:04:13+00:00 | 8k |
tamnva/hydroecolstm | examples/customLSTM_deleteme.py | [
{
"identifier": "Scaler",
"path": "hydroecolstm/utility/scaler.py",
"snippet": "class Scaler:\n def fit(self, x=None, method=None):\n # concatenat all object_id\n for i, object_id in zip(range(len(x)), x):\n if i == 0:\n cat_x = x[object_id]\n else:\... | import numbers
import warnings
import torch
import torch.jit as jit
import torch.nn as nn
from collections import namedtuple
from typing import List, Tuple, Dict
from torch import Tensor
from torch.nn import Parameter
from hydroecolstm.utility.scaler import Scaler, get_scaler_name
from hydroecolstm.data.read_data import read_train_test_data
from hydroecolstm.data.read_config import read_config
from hydroecolstm.model.lstm_linears import Lstm_Linears
from hydroecolstm.model.ea_lstm import Ea_Lstm_Linears
from hydroecolstm.model.train import Train | 4,335 |
class EALSTMCell(jit.ScriptModule):
def __init__(self, dynamic_input_size, static_input_size, hidden_size):
super().__init__()
self.dynamic_input_size = dynamic_input_size
self.static_input_size = static_input_size
self.hidden_size = hidden_size
self.weight_sh = Parameter(torch.randn(hidden_size, static_input_size))
self.weight_dh = Parameter(torch.randn(3 * hidden_size, dynamic_input_size))
self.weight_hh = Parameter(torch.randn(3 * hidden_size, hidden_size))
self.bias_sh = Parameter(torch.randn(hidden_size))
self.bias_dh = Parameter(torch.randn(3 * hidden_size))
self.bias_hh = Parameter(torch.randn(3 * hidden_size))
@jit.script_method
def forward(self, dynamic_input: Tensor, static_input: Tensor,
state: Tuple[Tensor, Tensor]) -> Tuple[Tensor, Tuple[Tensor, Tensor]]:
# Initial state
hx, cx = state
# Gate input
gates = (torch.mm(dynamic_input, self.weight_dh.t())
+ self.bias_dh
+ torch.mm(hx, self.weight_hh.t())
+ self.bias_hh)
forgetgate, cellgate, outgate = gates.chunk(3, 1)
ingate = torch.mm(static_input, self.weight_sh.t()) + self.bias_sh
# Gate output
ingate = torch.sigmoid(ingate)
forgetgate = torch.sigmoid(forgetgate)
cellgate = torch.tanh(cellgate)
outgate = torch.sigmoid(outgate)
# Update state
cy = (forgetgate * cx) + (ingate * cellgate)
hy = outgate * torch.tanh(cy)
# Return state output
return hy, (hy, cy)
class EALSTMLayer(jit.ScriptModule):
def __init__(self, config):
super().__init__()
self.dynamic_input_size = len(config["input_dynamic_features"])
self.static_input_size = len(config["input_static_features"])
self.hidden_size = config["hidden_size"]
self.cell = EALSTMCell(self.dynamic_input_size, self.static_input_size,
self.hidden_size)
@jit.script_method
def forward(self, dynamic_input,
static_input,
state:Tuple[Tensor, Tensor]):
if state is None:
hx = torch.rand(self.hidden_size)
cx = torch.rand(self.hidden_size)
state = hx, cx
for i in range(len(dynamic_input)):
output, state = self.cell(dynamic_input[i:i+1,:],
static_input, state)
if i == 0:
outputs = output
else:
outputs = torch.cat((outputs, output), 0)
return output, state
#
config_file = "C:/Users/nguyenta/Documents/GitHub/HydroEcoLSTM/examples/experiments/config.yml"
# Load configuration
|
class EALSTMCell(jit.ScriptModule):
def __init__(self, dynamic_input_size, static_input_size, hidden_size):
super().__init__()
self.dynamic_input_size = dynamic_input_size
self.static_input_size = static_input_size
self.hidden_size = hidden_size
self.weight_sh = Parameter(torch.randn(hidden_size, static_input_size))
self.weight_dh = Parameter(torch.randn(3 * hidden_size, dynamic_input_size))
self.weight_hh = Parameter(torch.randn(3 * hidden_size, hidden_size))
self.bias_sh = Parameter(torch.randn(hidden_size))
self.bias_dh = Parameter(torch.randn(3 * hidden_size))
self.bias_hh = Parameter(torch.randn(3 * hidden_size))
@jit.script_method
def forward(self, dynamic_input: Tensor, static_input: Tensor,
state: Tuple[Tensor, Tensor]) -> Tuple[Tensor, Tuple[Tensor, Tensor]]:
# Initial state
hx, cx = state
# Gate input
gates = (torch.mm(dynamic_input, self.weight_dh.t())
+ self.bias_dh
+ torch.mm(hx, self.weight_hh.t())
+ self.bias_hh)
forgetgate, cellgate, outgate = gates.chunk(3, 1)
ingate = torch.mm(static_input, self.weight_sh.t()) + self.bias_sh
# Gate output
ingate = torch.sigmoid(ingate)
forgetgate = torch.sigmoid(forgetgate)
cellgate = torch.tanh(cellgate)
outgate = torch.sigmoid(outgate)
# Update state
cy = (forgetgate * cx) + (ingate * cellgate)
hy = outgate * torch.tanh(cy)
# Return state output
return hy, (hy, cy)
class EALSTMLayer(jit.ScriptModule):
def __init__(self, config):
super().__init__()
self.dynamic_input_size = len(config["input_dynamic_features"])
self.static_input_size = len(config["input_static_features"])
self.hidden_size = config["hidden_size"]
self.cell = EALSTMCell(self.dynamic_input_size, self.static_input_size,
self.hidden_size)
@jit.script_method
def forward(self, dynamic_input,
static_input,
state:Tuple[Tensor, Tensor]):
if state is None:
hx = torch.rand(self.hidden_size)
cx = torch.rand(self.hidden_size)
state = hx, cx
for i in range(len(dynamic_input)):
output, state = self.cell(dynamic_input[i:i+1,:],
static_input, state)
if i == 0:
outputs = output
else:
outputs = torch.cat((outputs, output), 0)
return output, state
#
config_file = "C:/Users/nguyenta/Documents/GitHub/HydroEcoLSTM/examples/experiments/config.yml"
# Load configuration | config = read_config(config_file) | 3 | 2023-12-20 09:11:36+00:00 | 8k |
camenduru/OpenLRM-hf | lrm/models/rendering/synthesizer.py | [
{
"identifier": "ImportanceRenderer",
"path": "lrm/models/rendering/utils/renderer.py",
"snippet": "class ImportanceRenderer(torch.nn.Module):\n \"\"\"\n Modified original version to filter out-of-box samples as TensoRF does.\n \n Reference:\n TensoRF: https://github.com/apchenstu/TensoRF... | import itertools
import torch
import torch.nn as nn
from .utils.renderer import ImportanceRenderer
from .utils.ray_sampler import RaySampler | 4,667 | # ORIGINAL LICENSE
# SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# Modified by Zexin He
# The modifications are subject to the same license as the original.
class OSGDecoder(nn.Module):
"""
Triplane decoder that gives RGB and sigma values from sampled features.
Using ReLU here instead of Softplus in the original implementation.
Reference:
EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112
"""
def __init__(self, n_features: int,
hidden_dim: int = 64, num_layers: int = 4, activation: nn.Module = nn.ReLU):
super().__init__()
self.net = nn.Sequential(
nn.Linear(3 * n_features, hidden_dim),
activation(),
*itertools.chain(*[[
nn.Linear(hidden_dim, hidden_dim),
activation(),
] for _ in range(num_layers - 2)]),
nn.Linear(hidden_dim, 1 + 3),
)
# init all bias to zero
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.zeros_(m.bias)
def forward(self, sampled_features, ray_directions):
# Aggregate features by mean
# sampled_features = sampled_features.mean(1)
# Aggregate features by concatenation
_N, n_planes, _M, _C = sampled_features.shape
sampled_features = sampled_features.permute(0, 2, 1, 3).reshape(_N, _M, n_planes*_C)
x = sampled_features
N, M, C = x.shape
x = x.contiguous().view(N*M, C)
x = self.net(x)
x = x.view(N, M, -1)
rgb = torch.sigmoid(x[..., 1:])*(1 + 2*0.001) - 0.001 # Uses sigmoid clamping from MipNeRF
sigma = x[..., 0:1]
return {'rgb': rgb, 'sigma': sigma}
class TriplaneSynthesizer(nn.Module):
"""
Synthesizer that renders a triplane volume with planes and a camera.
Reference:
EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L19
"""
DEFAULT_RENDERING_KWARGS = {
'ray_start': 'auto',
'ray_end': 'auto',
'box_warp': 2.,
'white_back': True,
'disparity_space_sampling': False,
'clamp_mode': 'softplus',
'sampler_bbox_min': -1.,
'sampler_bbox_max': 1.,
}
def __init__(self, triplane_dim: int, samples_per_ray: int):
super().__init__()
# attributes
self.triplane_dim = triplane_dim
self.rendering_kwargs = {
**self.DEFAULT_RENDERING_KWARGS,
'depth_resolution': samples_per_ray // 2,
'depth_resolution_importance': samples_per_ray // 2,
}
# renderings
self.renderer = ImportanceRenderer()
| # ORIGINAL LICENSE
# SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-NvidiaProprietary
#
# Modified by Zexin He
# The modifications are subject to the same license as the original.
class OSGDecoder(nn.Module):
"""
Triplane decoder that gives RGB and sigma values from sampled features.
Using ReLU here instead of Softplus in the original implementation.
Reference:
EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L112
"""
def __init__(self, n_features: int,
hidden_dim: int = 64, num_layers: int = 4, activation: nn.Module = nn.ReLU):
super().__init__()
self.net = nn.Sequential(
nn.Linear(3 * n_features, hidden_dim),
activation(),
*itertools.chain(*[[
nn.Linear(hidden_dim, hidden_dim),
activation(),
] for _ in range(num_layers - 2)]),
nn.Linear(hidden_dim, 1 + 3),
)
# init all bias to zero
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.zeros_(m.bias)
def forward(self, sampled_features, ray_directions):
# Aggregate features by mean
# sampled_features = sampled_features.mean(1)
# Aggregate features by concatenation
_N, n_planes, _M, _C = sampled_features.shape
sampled_features = sampled_features.permute(0, 2, 1, 3).reshape(_N, _M, n_planes*_C)
x = sampled_features
N, M, C = x.shape
x = x.contiguous().view(N*M, C)
x = self.net(x)
x = x.view(N, M, -1)
rgb = torch.sigmoid(x[..., 1:])*(1 + 2*0.001) - 0.001 # Uses sigmoid clamping from MipNeRF
sigma = x[..., 0:1]
return {'rgb': rgb, 'sigma': sigma}
class TriplaneSynthesizer(nn.Module):
"""
Synthesizer that renders a triplane volume with planes and a camera.
Reference:
EG3D: https://github.com/NVlabs/eg3d/blob/main/eg3d/training/triplane.py#L19
"""
DEFAULT_RENDERING_KWARGS = {
'ray_start': 'auto',
'ray_end': 'auto',
'box_warp': 2.,
'white_back': True,
'disparity_space_sampling': False,
'clamp_mode': 'softplus',
'sampler_bbox_min': -1.,
'sampler_bbox_max': 1.,
}
def __init__(self, triplane_dim: int, samples_per_ray: int):
super().__init__()
# attributes
self.triplane_dim = triplane_dim
self.rendering_kwargs = {
**self.DEFAULT_RENDERING_KWARGS,
'depth_resolution': samples_per_ray // 2,
'depth_resolution_importance': samples_per_ray // 2,
}
# renderings
self.renderer = ImportanceRenderer() | self.ray_sampler = RaySampler() | 1 | 2023-12-21 16:30:19+00:00 | 8k |
garinops/chat-E-AI | ai/openai/tools/tools.py | [
{
"identifier": "ToolTime",
"path": "ai/openai/tools/TOOL_TIME.py",
"snippet": "class ToolTime(object):\n TOOL_MODEL = {\n \"type\": \"function\",\n \"function\": {\n\n # [必填:value可编辑],注意所有Tools中保持唯一,且和下方的静态方法函数保持命名一致。\n \"name\": \"get_time\",\n\n # [必填... | from ai.openai.tools.TOOL_TIME import ToolTime
from ai.openai.tools.WTTR_IN import ToolWttrIn
from ai.openai.tools.WWW_GARINASSET_COM import ToolWwwGarinassetCom
from ai.openai.tools.XUEQIU_COM import ToolXueqiuCom
from config.settings import OPENAI_TOOLS_CONFIG
from models.response import ResponseBase | 5,127 |
class OpenAITools:
@staticmethod
def get_tools() -> list:
tools = []
for tool_config in OPENAI_TOOLS_CONFIG:
if tool_config["enable"]:
tool_class = tool_config["Tool"]
tools.append(tool_class.TOOL_MODEL)
return tools
@staticmethod
def handle(name_tool_call: str, parameter_variables) -> ResponseBase:
"""1、处理路由OpenAI响应的function.name决定。"""
"""2、工具函数参数及变量值也是由OpenAI响应决定,需要具体工具具体相应处理。"""
match name_tool_call:
# 1.宏微观经济数据、行业数据、消费品市场价格数据工具-处理
case ToolWwwGarinassetCom.get_indicator_overview.__name__:
region = parameter_variables.get("region")
name = parameter_variables.get("name")
toolResponse = ToolWwwGarinassetCom.get_indicator_overview(region=region, name=name)
return toolResponse
# 2.天气工具-处理
case ToolWttrIn.get_weather.__name__:
location = parameter_variables.get("location")
|
class OpenAITools:
@staticmethod
def get_tools() -> list:
tools = []
for tool_config in OPENAI_TOOLS_CONFIG:
if tool_config["enable"]:
tool_class = tool_config["Tool"]
tools.append(tool_class.TOOL_MODEL)
return tools
@staticmethod
def handle(name_tool_call: str, parameter_variables) -> ResponseBase:
"""1、处理路由OpenAI响应的function.name决定。"""
"""2、工具函数参数及变量值也是由OpenAI响应决定,需要具体工具具体相应处理。"""
match name_tool_call:
# 1.宏微观经济数据、行业数据、消费品市场价格数据工具-处理
case ToolWwwGarinassetCom.get_indicator_overview.__name__:
region = parameter_variables.get("region")
name = parameter_variables.get("name")
toolResponse = ToolWwwGarinassetCom.get_indicator_overview(region=region, name=name)
return toolResponse
# 2.天气工具-处理
case ToolWttrIn.get_weather.__name__:
location = parameter_variables.get("location") | toolResponse = ToolWttrIn.get_weather(location=location) | 1 | 2023-12-16 17:02:13+00:00 | 8k |
ruudjuffermans/Event-Driven-Backtester | example.py | [
{
"identifier": "Loop",
"path": "backtester/loop.py",
"snippet": "class Loop:\n def __init__(\n self,\n data_handler,\n execution_handler,\n portfolio,\n strategy,\n heartbeat,\n ):\n self.heartbeat = heartbeat\n\n self.data_handler = data_ha... | from datetime import datetime
from backtester.loop import Loop
from backtester.generator import CSVGenerator
from backtester.execution import SimulatedExecutionHandler
from backtester.portfolio import Portfolio
from backtester.strategy import MACrossOverStrategy
from backtester.types import Window | 3,645 |
symbol_list = ["BIG"]
window = Window(
start=datetime(2016, 1, 1, 0, 0, 0),
end=datetime(2021, 1, 1, 0, 0, 0),
interval="1d",
)
generator = CSVGenerator(symbol_list)
portfolio = Portfolio(window, 100000.0)
strategy = MACrossOverStrategy()
execution = SimulatedExecutionHandler()
|
symbol_list = ["BIG"]
window = Window(
start=datetime(2016, 1, 1, 0, 0, 0),
end=datetime(2021, 1, 1, 0, 0, 0),
interval="1d",
)
generator = CSVGenerator(symbol_list)
portfolio = Portfolio(window, 100000.0)
strategy = MACrossOverStrategy()
execution = SimulatedExecutionHandler()
| backtest = Loop(generator, execution, portfolio, strategy, 0.0) | 0 | 2023-12-16 21:09:00+00:00 | 8k |
Subsets and Splits
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have consistent code formatting levels across multiple scales (2k, 4k, 8k, 12k) and reveals the structured formatting patterns within these repositories.
SQL Console for tianyang/repobench_python_v1.1
Compares cross-file and in-file code structure patterns across different complexity levels, revealing how file organization strategies vary with code size and potentially informing better code architecture decisions.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that have complete performance data across all seven code complexity levels, revealing consistent benchmarking patterns across different code sizes.
SQL Console for tianyang/repobench_python_v1.1
Identifies repositories that contain all 7 distinct quality levels (2k through 32k), revealing complete datasets that might be useful for comprehensive analysis.