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 |
|---|---|---|---|---|---|---|---|---|---|---|
DLYuanGod/TinyGPT-V | minigpt4/models/minigpt4.py | [
{
"identifier": "registry",
"path": "minigpt4/common/registry.py",
"snippet": "class Registry:\n def register_builder(cls, name):\n def wrap(builder_cls):\n def register_task(cls, name):\n def wrap(task_cls):\n def register_model(cls, name):\n def wrap(model_cls):\n def ... | import logging
import random
import torch
import torch.nn as nn
from torch.cuda.amp import autocast as autocast
from minigpt4.common.registry import registry
from minigpt4.models.base_model import disabled_train
from minigpt4.models.minigpt_base import MiniGPTBase
from minigpt4.models.Qformer import BertConfig, BertLMHeadModel | 6,834 |
@registry.register_model("minigpt4")
class MiniGPT4(MiniGPTBase):
"""
MiniGPT-4 model
"""
PRETRAINED_MODEL_CONFIG_DICT = {
"pretrain_vicuna0": "configs/models/minigpt4_vicuna0.yaml",
"pretrain_llama2": "configs/models/minigpt4_llama2.yaml",
}
def __init__(
self,
vit_model="eva_clip_g",
q_former_model="https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/blip2_pretrained_flant5xxl.pth",
img_size=224,
drop_path_rate=0,
use_grad_checkpoint=False,
vit_precision="fp16",
freeze_vit=True,
has_qformer=True,
freeze_qformer=True,
num_query_token=32,
llama_model="",
prompt_path="",
prompt_template="",
max_txt_len=32,
end_sym='\n',
low_resource=False, # use 8 bit and put vit in cpu
device_8bit=0, # the device of 8bit model should be set when loading and cannot be changed anymore.
lora_r=64,
lora_target_modules=['query_key_value','dense'],
lora_alpha=16,
lora_dropout=0.05,
):
super().__init__(
vit_model=vit_model,
img_size=img_size,
drop_path_rate=drop_path_rate,
use_grad_checkpoint=use_grad_checkpoint,
vit_precision=vit_precision,
freeze_vit=freeze_vit,
llama_model=llama_model,
max_txt_len=max_txt_len,
end_sym=end_sym,
low_resource=low_resource,
device_8bit=device_8bit,
lora_r=lora_r,
lora_target_modules=lora_target_modules,
lora_alpha=lora_alpha,
lora_dropout=lora_dropout,
)
self.has_qformer = True
if self.has_qformer:
print('Loading Q-Former')
self.Qformer, self.query_tokens = self.init_Qformer(
num_query_token, self.visual_encoder.num_features, freeze_qformer
)
self.load_from_pretrained(url_or_filename=q_former_model) # load q-former weights here
img_f_dim = self.Qformer.config.hidden_size
print('Loading Q-Former Done')
else:
img_f_dim = self.visual_encoder.num_features * 4
print('Do not use Q-Former here.')
print(img_f_dim,self.llama_model.config.hidden_size)
self.llama_proj = nn.Linear(
self.Qformer.config.hidden_size, 4096
)
self.llama_proj2 = nn.Linear(
4096, self.llama_model.config.hidden_size
)
if prompt_path:
with open(prompt_path, 'r') as f:
raw_prompts = f.read().splitlines()
filted_prompts = [raw_prompt for raw_prompt in raw_prompts if "<ImageHere>" in raw_prompt]
self.prompt_list = [prompt_template.format(p) for p in filted_prompts]
print('Load {} training prompts'.format(len(self.prompt_list)))
print('Prompt Example \n{}'.format(random.choice(self.prompt_list)))
else:
self.prompt_list = []
@classmethod
def init_Qformer(cls, num_query_token, vision_width, freeze):
encoder_config = BertConfig.from_pretrained("bert-base-uncased")
encoder_config.encoder_width = vision_width
# insert cross-attention layer every other block
encoder_config.add_cross_attention = True
encoder_config.cross_attention_freq = 2
encoder_config.query_length = num_query_token
Qformer = BertLMHeadModel(config=encoder_config)
query_tokens = nn.Parameter(
torch.zeros(1, num_query_token, encoder_config.hidden_size)
)
query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range)
Qformer.cls = None
Qformer.bert.embeddings.word_embeddings = None
Qformer.bert.embeddings.position_embeddings = None
for layer in Qformer.bert.encoder.layer:
layer.output = None
layer.intermediate = None
if freeze:
for name, param in Qformer.named_parameters():
param.requires_grad = False
Qformer = Qformer.eval()
|
@registry.register_model("minigpt4")
class MiniGPT4(MiniGPTBase):
"""
MiniGPT-4 model
"""
PRETRAINED_MODEL_CONFIG_DICT = {
"pretrain_vicuna0": "configs/models/minigpt4_vicuna0.yaml",
"pretrain_llama2": "configs/models/minigpt4_llama2.yaml",
}
def __init__(
self,
vit_model="eva_clip_g",
q_former_model="https://storage.googleapis.com/sfr-vision-language-research/LAVIS/models/BLIP2/blip2_pretrained_flant5xxl.pth",
img_size=224,
drop_path_rate=0,
use_grad_checkpoint=False,
vit_precision="fp16",
freeze_vit=True,
has_qformer=True,
freeze_qformer=True,
num_query_token=32,
llama_model="",
prompt_path="",
prompt_template="",
max_txt_len=32,
end_sym='\n',
low_resource=False, # use 8 bit and put vit in cpu
device_8bit=0, # the device of 8bit model should be set when loading and cannot be changed anymore.
lora_r=64,
lora_target_modules=['query_key_value','dense'],
lora_alpha=16,
lora_dropout=0.05,
):
super().__init__(
vit_model=vit_model,
img_size=img_size,
drop_path_rate=drop_path_rate,
use_grad_checkpoint=use_grad_checkpoint,
vit_precision=vit_precision,
freeze_vit=freeze_vit,
llama_model=llama_model,
max_txt_len=max_txt_len,
end_sym=end_sym,
low_resource=low_resource,
device_8bit=device_8bit,
lora_r=lora_r,
lora_target_modules=lora_target_modules,
lora_alpha=lora_alpha,
lora_dropout=lora_dropout,
)
self.has_qformer = True
if self.has_qformer:
print('Loading Q-Former')
self.Qformer, self.query_tokens = self.init_Qformer(
num_query_token, self.visual_encoder.num_features, freeze_qformer
)
self.load_from_pretrained(url_or_filename=q_former_model) # load q-former weights here
img_f_dim = self.Qformer.config.hidden_size
print('Loading Q-Former Done')
else:
img_f_dim = self.visual_encoder.num_features * 4
print('Do not use Q-Former here.')
print(img_f_dim,self.llama_model.config.hidden_size)
self.llama_proj = nn.Linear(
self.Qformer.config.hidden_size, 4096
)
self.llama_proj2 = nn.Linear(
4096, self.llama_model.config.hidden_size
)
if prompt_path:
with open(prompt_path, 'r') as f:
raw_prompts = f.read().splitlines()
filted_prompts = [raw_prompt for raw_prompt in raw_prompts if "<ImageHere>" in raw_prompt]
self.prompt_list = [prompt_template.format(p) for p in filted_prompts]
print('Load {} training prompts'.format(len(self.prompt_list)))
print('Prompt Example \n{}'.format(random.choice(self.prompt_list)))
else:
self.prompt_list = []
@classmethod
def init_Qformer(cls, num_query_token, vision_width, freeze):
encoder_config = BertConfig.from_pretrained("bert-base-uncased")
encoder_config.encoder_width = vision_width
# insert cross-attention layer every other block
encoder_config.add_cross_attention = True
encoder_config.cross_attention_freq = 2
encoder_config.query_length = num_query_token
Qformer = BertLMHeadModel(config=encoder_config)
query_tokens = nn.Parameter(
torch.zeros(1, num_query_token, encoder_config.hidden_size)
)
query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range)
Qformer.cls = None
Qformer.bert.embeddings.word_embeddings = None
Qformer.bert.embeddings.position_embeddings = None
for layer in Qformer.bert.encoder.layer:
layer.output = None
layer.intermediate = None
if freeze:
for name, param in Qformer.named_parameters():
param.requires_grad = False
Qformer = Qformer.eval() | Qformer.train = disabled_train | 1 | 2023-12-28 05:47:18+00:00 | 8k |
ali-vilab/dreamtalk | core/networks/generator.py | [
{
"identifier": "TransformerEncoder",
"path": "core/networks/transformer.py",
"snippet": "class TransformerEncoder(nn.Module):\r\n\r\n def __init__(self, encoder_layer, num_layers, norm=None):\r\n super().__init__()\r\n self.layers = _get_clones(encoder_layer, num_layers)\r\n sel... | import torch
import sys
from torch import nn
from .transformer import (
TransformerEncoder,
TransformerEncoderLayer,
PositionalEncoding,
TransformerDecoderLayer,
TransformerDecoder,
)
from core.utils import _reset_parameters
from core.networks.self_attention_pooling import SelfAttentionPooling
from configs.default import get_cfg_defaults | 3,945 | # self.ph_embedding = nn.Embedding(41, ph_embed_dim)
# self.increase_embed_dim = nn.Linear(ph_embed_dim, d_model)
# def forward(self, x):
# """
# Args:
# x (_type_): (B, num_frames, window)
# Returns:
# content: (B, num_frames, window, C_dmodel)
# """
# x_embedding = self.ph_embedding(x)
# x_embedding = self.increase_embed_dim(x_embedding)
# # (B, N, W, C)
# B, N, W, C = x_embedding.shape
# x_embedding = x_embedding.reshape(B * N, W, C)
# x_embedding = x_embedding.permute(1, 0, 2)
# # (W, B*N, C)
# pos = self.pos_embed(W)
# pos = pos.permute(1, 0, 2)
# # (W, 1, C)
# content = self.encoder(x_embedding, pos=pos)
# # (W, B*N, C)
# content = content.permute(1, 0, 2).reshape(B, N, W, C)
# # (B, N, W, C)
# return content
class ContentW2VEncoder(nn.Module):
def __init__(
self,
d_model=512,
nhead=8,
num_encoder_layers=6,
dim_feedforward=2048,
dropout=0.1,
activation="relu",
normalize_before=False,
pos_embed_len=80,
ph_embed_dim=128,
):
super().__init__()
encoder_layer = TransformerEncoderLayer(
d_model, nhead, dim_feedforward, dropout, activation, normalize_before
)
encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
self.encoder = TransformerEncoder(
encoder_layer, num_encoder_layers, encoder_norm
)
_reset_parameters(self.encoder)
self.pos_embed = PositionalEncoding(d_model, pos_embed_len)
self.increase_embed_dim = nn.Linear(1024, d_model)
def forward(self, x):
"""
Args:
x (_type_): (B, num_frames, window, C_wav2vec)
Returns:
content: (B, num_frames, window, C_dmodel)
"""
x_embedding = self.increase_embed_dim(
x
) # [16, 64, 11, 1024] -> [16, 64, 11, 256]
# (B, N, W, C)
B, N, W, C = x_embedding.shape
x_embedding = x_embedding.reshape(B * N, W, C)
x_embedding = x_embedding.permute(1, 0, 2) # [11, 1024, 256]
# (W, B*N, C)
pos = self.pos_embed(W)
pos = pos.permute(1, 0, 2) # [11, 1, 256]
# (W, 1, C)
content = self.encoder(x_embedding, pos=pos) # [11, 1024, 256]
# (W, B*N, C)
content = content.permute(1, 0, 2).reshape(B, N, W, C)
# (B, N, W, C)
return content
class StyleEncoder(nn.Module):
def __init__(
self,
d_model=512,
nhead=8,
num_encoder_layers=6,
dim_feedforward=2048,
dropout=0.1,
activation="relu",
normalize_before=False,
pos_embed_len=80,
input_dim=128,
aggregate_method="average",
):
super().__init__()
encoder_layer = TransformerEncoderLayer(
d_model, nhead, dim_feedforward, dropout, activation, normalize_before
)
encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
self.encoder = TransformerEncoder(
encoder_layer, num_encoder_layers, encoder_norm
)
_reset_parameters(self.encoder)
self.pos_embed = PositionalEncoding(d_model, pos_embed_len)
self.increase_embed_dim = nn.Linear(input_dim, d_model)
self.aggregate_method = None
if aggregate_method == "self_attention_pooling":
|
# class ContentEncoder(nn.Module):
# def __init__(
# self,
# d_model=512,
# nhead=8,
# num_encoder_layers=6,
# dim_feedforward=2048,
# dropout=0.1,
# activation="relu",
# normalize_before=False,
# pos_embed_len=80,
# ph_embed_dim=128,
# ):
# super().__init__()
# encoder_layer = TransformerEncoderLayer(
# d_model, nhead, dim_feedforward, dropout, activation, normalize_before
# )
# encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
# self.encoder = TransformerEncoder(
# encoder_layer, num_encoder_layers, encoder_norm
# )
# _reset_parameters(self.encoder)
# self.pos_embed = PositionalEncoding(d_model, pos_embed_len)
# self.ph_embedding = nn.Embedding(41, ph_embed_dim)
# self.increase_embed_dim = nn.Linear(ph_embed_dim, d_model)
# def forward(self, x):
# """
# Args:
# x (_type_): (B, num_frames, window)
# Returns:
# content: (B, num_frames, window, C_dmodel)
# """
# x_embedding = self.ph_embedding(x)
# x_embedding = self.increase_embed_dim(x_embedding)
# # (B, N, W, C)
# B, N, W, C = x_embedding.shape
# x_embedding = x_embedding.reshape(B * N, W, C)
# x_embedding = x_embedding.permute(1, 0, 2)
# # (W, B*N, C)
# pos = self.pos_embed(W)
# pos = pos.permute(1, 0, 2)
# # (W, 1, C)
# content = self.encoder(x_embedding, pos=pos)
# # (W, B*N, C)
# content = content.permute(1, 0, 2).reshape(B, N, W, C)
# # (B, N, W, C)
# return content
class ContentW2VEncoder(nn.Module):
def __init__(
self,
d_model=512,
nhead=8,
num_encoder_layers=6,
dim_feedforward=2048,
dropout=0.1,
activation="relu",
normalize_before=False,
pos_embed_len=80,
ph_embed_dim=128,
):
super().__init__()
encoder_layer = TransformerEncoderLayer(
d_model, nhead, dim_feedforward, dropout, activation, normalize_before
)
encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
self.encoder = TransformerEncoder(
encoder_layer, num_encoder_layers, encoder_norm
)
_reset_parameters(self.encoder)
self.pos_embed = PositionalEncoding(d_model, pos_embed_len)
self.increase_embed_dim = nn.Linear(1024, d_model)
def forward(self, x):
"""
Args:
x (_type_): (B, num_frames, window, C_wav2vec)
Returns:
content: (B, num_frames, window, C_dmodel)
"""
x_embedding = self.increase_embed_dim(
x
) # [16, 64, 11, 1024] -> [16, 64, 11, 256]
# (B, N, W, C)
B, N, W, C = x_embedding.shape
x_embedding = x_embedding.reshape(B * N, W, C)
x_embedding = x_embedding.permute(1, 0, 2) # [11, 1024, 256]
# (W, B*N, C)
pos = self.pos_embed(W)
pos = pos.permute(1, 0, 2) # [11, 1, 256]
# (W, 1, C)
content = self.encoder(x_embedding, pos=pos) # [11, 1024, 256]
# (W, B*N, C)
content = content.permute(1, 0, 2).reshape(B, N, W, C)
# (B, N, W, C)
return content
class StyleEncoder(nn.Module):
def __init__(
self,
d_model=512,
nhead=8,
num_encoder_layers=6,
dim_feedforward=2048,
dropout=0.1,
activation="relu",
normalize_before=False,
pos_embed_len=80,
input_dim=128,
aggregate_method="average",
):
super().__init__()
encoder_layer = TransformerEncoderLayer(
d_model, nhead, dim_feedforward, dropout, activation, normalize_before
)
encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
self.encoder = TransformerEncoder(
encoder_layer, num_encoder_layers, encoder_norm
)
_reset_parameters(self.encoder)
self.pos_embed = PositionalEncoding(d_model, pos_embed_len)
self.increase_embed_dim = nn.Linear(input_dim, d_model)
self.aggregate_method = None
if aggregate_method == "self_attention_pooling": | self.aggregate_method = SelfAttentionPooling(d_model) | 6 | 2023-12-28 05:39:31+00:00 | 8k |
jiawei-ren/dreamgaussian4d | 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 torchvision.transforms as transforms
import copy
import numpy as np
import torch
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 scene.hyper_loader import Load_hyper_data, format_hyper_data
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
from utils.general_utils import PILtoTorch
from tqdm import tqdm
from scene.neural_3D_dataset_NDC import Neural3D_NDC_Dataset | 5,816 | #
# 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
time : float
class SceneInfo(NamedTuple):
point_cloud: BasicPointCloud
train_cameras: list
test_cameras: list
video_cameras: list
nerf_normalization: dict
ply_path: str
maxtime: int
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 in ["SIMPLE_PINHOLE", "SIMPLE_RADIAL"]:
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)
elif intr.model == "OPENCV":
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)
| #
# 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
time : float
class SceneInfo(NamedTuple):
point_cloud: BasicPointCloud
train_cameras: list
test_cameras: list
video_cameras: list
nerf_normalization: dict
ply_path: str
maxtime: int
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 in ["SIMPLE_PINHOLE", "SIMPLE_RADIAL"]:
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)
elif intr.model == "OPENCV":
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) | image = PILtoTorch(image,None) | 14 | 2023-12-28 08:17:40+00:00 | 8k |
oppo-us-research/SpacetimeGaussians | script/pre_immersive_distorted.py | [
{
"identifier": "posetow2c_matrcs",
"path": "thirdparty/gaussian_splatting/utils/my_utils.py",
"snippet": "def posetow2c_matrcs(poses):\n tmp = inversestep4(inversestep3(inversestep2(inversestep1(poses))))\n N = tmp.shape[0]\n ret = []\n for i in range(N):\n ret.append(tmp[i])\n re... | import os
import cv2
import glob
import tqdm
import numpy as np
import shutil
import pickle
import argparse
import natsort
import struct
import pickle
import json
import cv2
import numpy as np
import os
import json
from scipy.spatial.transform import Rotation
from thirdparty.gaussian_splatting.utils.my_utils import posetow2c_matrcs, rotmat2qvec, qvec2rotmat
from thirdparty.gaussian_splatting.utils.graphics_utils import focal2fov, fov2focal
from thirdparty.colmap.pre_colmap import *
from thirdparty.gaussian_splatting.helper3dg import getcolmapsingleimdistort
from script.pre_n3d import extractframes | 4,815 | knew = np.zeros((3, 3), dtype=np.float32)
knew[0,0] = focalscale * intrinsics[0,0]
knew[1,1] = focalscale * intrinsics[1,1]
knew[0,2] = view['principal_point'][0] # cx fixed half of the width
knew[1,2] = view['principal_point'][1] #
knew[2,2] = 1.0
map1, map2 = cv2.fisheye.initUndistortRectifyMap(intrinsics, dis_cef, R=None, P=knew, size=(w, h), m1type=cv2.CV_32FC1)
undistorted_image = cv2.remap(image, map1, map2, interpolation=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT)
undistorted_image = undistorted_image.clip(0,255.0).astype(np.uint8)
cv2.imwrite(imagesavepath, undistorted_image)
if offset == 0:
#
distortingflow = getdistortedflow(image, intrinsics, dis_cef, "linear", crop_output=False, scale=1.0, knew=knew)
print("saved distortion mappers")
np.save(os.path.join(video, folder + ".npy"), distortingflow)
def softlinkdataset(originalpath, path, srcscene, scene):
videofolderlist = glob.glob(originalpath + "camera_*/")
if not os.path.exists(path):
os.makedirs(path)
for videofolder in videofolderlist:
newlink = os.path.join(path, videofolder.split("/")[-2])
if os.path.exists(newlink):
print("already exists do not make softlink again")
quit()
assert not os.path.exists(newlink)
cmd = " ln -s " + videofolder + " " + newlink
os.system(cmd)
print(cmd)
originalmodel = originalpath + "models.json"
newmodel = path + "models.json"
shutil.copy(originalmodel, newmodel)
if __name__ == "__main__" :
parser = argparse.ArgumentParser()
parser.add_argument("--videopath", default="", type=str)
parser.add_argument("--startframe", default=0, type=int)
parser.add_argument("--endframe", default=50, type=int)
args = parser.parse_args()
videopath = args.videopath
startframe = args.startframe
endframe = args.endframe
if startframe >= endframe:
print("start frame must smaller than end frame")
quit()
if startframe < 0 or endframe > 300:
print("frame must in range 0-300")
quit()
if not os.path.exists(videopath):
print("path not exist")
quit()
if not videopath.endswith("/"):
videopath = videopath + "/"
srcscene = videopath.split("/")[-2]
if srcscene not in Immersiveseven:
print("scene not in Immersiveseven", Immersiveseven)
print("Please check if the scene name is correct")
quit()
if "04_Trucks" in videopath:
print('04_Trucks')
if endframe > 150:
endframe = 150
postfix = "_dist" # distored model
scene = srcscene + postfix
originalpath = videopath #"
originalvideo = originalpath# 43 1
path = videopath[:-1] + postfix
video = originalpath # 43 1
scale = immmersivescaledict[scene]
videoslist = glob.glob(originalvideo + "*.mp4")
for v in tqdm.tqdm(videoslist):
extractframes(v)
try:
softlinkdataset(originalpath, path, srcscene, scene)
except:
print("softlink failed")
quit()
try:
imageundistort(video, offsetlist=[i for i in range(startframe,endframe)],focalscale=scale, fixfocal=None)
except:
print("undistort failed")
quit()
try:
for offset in tqdm.tqdm(range(startframe, endframe)):
convertmodel2dbfiles(video, offset=offset, scale=scale, removeverythingexceptinput=False)
except:
convertmodel2dbfiles(video, offset=offset, scale=scale, removeverythingexceptinput=True)
print("create colmap input failed, better clean the data and try again")
quit()
for offset in range(startframe, endframe):
| # MIT License
# Copyright (c) 2023 OPPO
# 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.
SCALEDICT = {}
# SCALEDICT["01_Welder_S11"] = 0.35
# ["04_Truck", "09_Alexa", "10_Alexa", "11_Alexa", "12_Cave"]
Immersiveseven = ["01_Welder", "02_Flames", "04_Truck", "09_Alexa", "10_Alexa", "11_Alexa", "12_Cave"]
immmersivescaledict = {}
immmersivescaledict["01_Welder"] = 0.36
immmersivescaledict["02_Flames"] = 0.35
immmersivescaledict["04_Truck"] = 0.36
immmersivescaledict["09_Alexa"] = 0.36
immmersivescaledict["10_Alexa"] = 0.36
immmersivescaledict["11_Alexa"] = 0.36
immmersivescaledict["12_Cave"] = 0.36
for scene in Immersiveseven:
immmersivescaledict[scene + "_dist"] =immmersivescaledict[scene]
SCALEDICT[scene + "_dist"] = immmersivescaledict[scene] #immmersivescaledict[scene] # to be checked with large scale
def convertmodel2dbfiles(path, offset=0, scale=1.0, removeverythingexceptinput=False):
projectfolder = os.path.join(path, "colmap_" + str(offset))
manualfolder = os.path.join(projectfolder, "manual")
if os.path.exists(projectfolder) and removeverythingexceptinput:
print("already exists colmap folder, better remove it and create a new one")
inputfolder = os.path.join(projectfolder, "input")
# remove everything except input folder
for file in os.listdir(projectfolder):
if file == "input":
continue
file_path = os.path.join(projectfolder, file)
if os.path.isfile(file_path):
os.remove(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
if not os.path.exists(manualfolder):
os.makedirs(manualfolder)
savetxt = os.path.join(manualfolder, "images.txt")
savecamera = os.path.join(manualfolder, "cameras.txt")
savepoints = os.path.join(manualfolder, "points3D.txt")
imagetxtlist = []
cameratxtlist = []
if os.path.exists(os.path.join(projectfolder, "input.db")):
os.remove(os.path.join(projectfolder, "input.db"))
db = COLMAPDatabase.connect(os.path.join(projectfolder, "input.db"))
db.create_tables()
with open(os.path.join(video + "models.json"), "r") as f:
meta = json.load(f)
for idx , camera in enumerate(meta):
cameraname = camera['name'] # camera_0001
view = camera
focolength = camera['focal_length']
width, height = camera['width'], camera['height']
principlepoint =[0,0]
principlepoint[0] = view['principal_point'][0]
principlepoint[1] = view['principal_point'][1]
distort1 = view['radial_distortion'][0]
distort2 = view['radial_distortion'][1]
distort3 = 0
distort4 = 0 #view['radial_distortion'][3]
R = Rotation.from_rotvec(view['orientation']).as_matrix()
t = np.array(view['position'])[:, np.newaxis]
w2c = np.concatenate((R, -np.dot(R, t)), axis=1)
colmapR = w2c[:3, :3]
T = w2c[:3, 3]
K = np.array([[focolength, 0, principlepoint[0]], [0, focolength, principlepoint[1]], [0, 0, 1]])
Knew = K.copy()
Knew[0,0] = K[0,0] * float(scale)
Knew[1,1] = K[1,1] * float(scale)
Knew[0,2] = view['principal_point'][0]#width * 0.5 #/ 2
Knew[1,2] = view['principal_point'][1]#height * 0.5 #/ 2
# transformation = np.array([[2, 0.0, 0.5],
# [0.0, 2, 0.5],
# [0.0, 0.0, 1.0]])
# Knew = np.dot(transformation, Knew)
newfocalx = Knew[0,0]
newfocaly = Knew[1,1]
newcx = Knew[0,2]
newcy = Knew[1,2]
colmapQ = rotmat2qvec(colmapR)
imageid = str(idx+1)
cameraid = imageid
pngname = cameraname + ".png"
line = imageid + " "
for j in range(4):
line += str(colmapQ[j]) + " "
for j in range(3):
line += str(T[j]) + " "
line = line + cameraid + " " + pngname + "\n"
empltyline = "\n"
imagetxtlist.append(line)
imagetxtlist.append(empltyline)
newwidth = width
newheight = height
params = np.array((newfocalx , newfocaly, newcx, newcy,))
camera_id = db.add_camera(1, newwidth, newheight, params) # RADIAL_FISHEYE # width and height
#
#cameraline = str(i+1) + " " + "PINHOLE " + str(width) + " " + str(height) + " " + str(focolength) + " " + str(focolength) + " " + str(W//2) + " " + str(H//2) + "\n"
cameraline = str(idx+1) + " " + "PINHOLE " + str(newwidth) + " " + str(newheight) + " " + str(newfocalx) + " " + str(newfocaly) + " " + str(newcx) + " " + str(newcy) + "\n"
cameratxtlist.append(cameraline)
image_id = db.add_image(pngname, camera_id, prior_q=np.array((colmapQ[0], colmapQ[1], colmapQ[2], colmapQ[3])), prior_t=np.array((T[0], T[1], T[2])), image_id=idx+1)
db.commit()
print("commited one")
db.close()
with open(savetxt, "w") as f:
for line in imagetxtlist :
f.write(line)
with open(savecamera, "w") as f:
for line in cameratxtlist :
f.write(line)
with open(savepoints, "w") as f:
pass
#https://github.com/Synthesis-AI-Dev/fisheye-distortion
def getdistortedflow(img: np.ndarray, cam_intr: np.ndarray, dist_coeff: np.ndarray,
mode: str, crop_output: bool = True,
crop_type: str = "corner", scale: float =2, cxoffset=None, cyoffset=None, knew=None):
assert cam_intr.shape == (3, 3)
assert dist_coeff.shape == (4,)
imshape = img.shape
if len(imshape) == 3:
h, w, chan = imshape
elif len(imshape) == 2:
h, w = imshape
chan = 1
else:
raise RuntimeError(f'Image has unsupported shape: {imshape}. Valid shapes: (H, W), (H, W, N)')
imdtype = img.dtype
dstW = int(w )
dstH = int(h )
# Get array of pixel co-ords
xs = np.arange(dstW)
ys = np.arange(dstH)
xs = xs #- 0.5 # + cxoffset / 2
ys = ys #- 0.5 # + cyoffset / 2
xv, yv = np.meshgrid(xs, ys)
img_pts = np.stack((xv, yv), axis=2) # shape (H, W, 2)
img_pts = img_pts.reshape((-1, 1, 2)).astype(np.float32) # shape: (N, 1, 2), in undistorted image coordiante
undistorted_px = cv2.fisheye.undistortPoints(img_pts, cam_intr, dist_coeff, None, knew) # shape: (N, 1, 2)
undistorted_px = undistorted_px.reshape((dstH, dstW, 2)) # Shape: (H, W, 2)
undistorted_px = np.flip(undistorted_px, axis=2) # flip x, y coordinates of the points as cv2 is height first
undistorted_px[:, :, 0] = undistorted_px[:, :, 0] #+ 0.5*cyoffset #- 0.25*cyoffset #orginalx (0, 1)
undistorted_px[:, :, 1] = undistorted_px[:, :, 1] #+ 0.5*cyoffset #- 0.25*cxoffset #orginaly (0, 1)
undistorted_px[:, :, 0] = undistorted_px[:, :, 0] / (h-1)#(h-1) #orginalx (0, 1)
undistorted_px[:, :, 1] = undistorted_px[:, :, 1] / (w-1)#(w-1) #orginaly (0, 1)
undistorted_px = 2 * (undistorted_px - 0.5) #to -1 to 1 for gridsample
undistorted_px[:, :, 0] = undistorted_px[:, :, 0] #orginalx (0, 1)
undistorted_px[:, :, 1] = undistorted_px[:, :, 1] #orginaly (0, 1)
undistorted_px = undistorted_px[:,:,::-1] # yx to xy for grid sample
return undistorted_px
def imageundistort(video, offsetlist=[0],focalscale=1.0, fixfocal=None):
with open(os.path.join(video + "models.json"), "r") as f:
meta = json.load(f)
for idx , camera in enumerate(meta):
folder = camera['name'] # camera_0001
view = camera
intrinsics = np.array([[view['focal_length'], 0.0, view['principal_point'][0]],
[0.0, view['focal_length'], view['principal_point'][1]],
[0.0, 0.0, 1.0]])
dis_cef = np.zeros((4))
dis_cef[:2] = np.array(view['radial_distortion'])[:2]
print("done one camera")
map1, map2 = None, None
for offset in offsetlist:
videofolder = os.path.join(video, folder)
imagepath = os.path.join(videofolder, str(offset) + ".png")
imagesavepath = os.path.join(video, "colmap_" + str(offset), "input", folder + ".png")
inputimagefolder = os.path.join(video, "colmap_" + str(offset), "input")
if not os.path.exists(inputimagefolder):
os.makedirs(inputimagefolder)
assert os.path.exists(imagepath)
image = cv2.imread(imagepath).astype(np.float32) #/ 255.0
h, w = image.shape[:2]
image_size = (w, h)
knew = np.zeros((3, 3), dtype=np.float32)
knew[0,0] = focalscale * intrinsics[0,0]
knew[1,1] = focalscale * intrinsics[1,1]
knew[0,2] = view['principal_point'][0] # cx fixed half of the width
knew[1,2] = view['principal_point'][1] #
knew[2,2] = 1.0
map1, map2 = cv2.fisheye.initUndistortRectifyMap(intrinsics, dis_cef, R=None, P=knew, size=(w, h), m1type=cv2.CV_32FC1)
undistorted_image = cv2.remap(image, map1, map2, interpolation=cv2.INTER_CUBIC, borderMode=cv2.BORDER_CONSTANT)
undistorted_image = undistorted_image.clip(0,255.0).astype(np.uint8)
cv2.imwrite(imagesavepath, undistorted_image)
if offset == 0:
#
distortingflow = getdistortedflow(image, intrinsics, dis_cef, "linear", crop_output=False, scale=1.0, knew=knew)
print("saved distortion mappers")
np.save(os.path.join(video, folder + ".npy"), distortingflow)
def softlinkdataset(originalpath, path, srcscene, scene):
videofolderlist = glob.glob(originalpath + "camera_*/")
if not os.path.exists(path):
os.makedirs(path)
for videofolder in videofolderlist:
newlink = os.path.join(path, videofolder.split("/")[-2])
if os.path.exists(newlink):
print("already exists do not make softlink again")
quit()
assert not os.path.exists(newlink)
cmd = " ln -s " + videofolder + " " + newlink
os.system(cmd)
print(cmd)
originalmodel = originalpath + "models.json"
newmodel = path + "models.json"
shutil.copy(originalmodel, newmodel)
if __name__ == "__main__" :
parser = argparse.ArgumentParser()
parser.add_argument("--videopath", default="", type=str)
parser.add_argument("--startframe", default=0, type=int)
parser.add_argument("--endframe", default=50, type=int)
args = parser.parse_args()
videopath = args.videopath
startframe = args.startframe
endframe = args.endframe
if startframe >= endframe:
print("start frame must smaller than end frame")
quit()
if startframe < 0 or endframe > 300:
print("frame must in range 0-300")
quit()
if not os.path.exists(videopath):
print("path not exist")
quit()
if not videopath.endswith("/"):
videopath = videopath + "/"
srcscene = videopath.split("/")[-2]
if srcscene not in Immersiveseven:
print("scene not in Immersiveseven", Immersiveseven)
print("Please check if the scene name is correct")
quit()
if "04_Trucks" in videopath:
print('04_Trucks')
if endframe > 150:
endframe = 150
postfix = "_dist" # distored model
scene = srcscene + postfix
originalpath = videopath #"
originalvideo = originalpath# 43 1
path = videopath[:-1] + postfix
video = originalpath # 43 1
scale = immmersivescaledict[scene]
videoslist = glob.glob(originalvideo + "*.mp4")
for v in tqdm.tqdm(videoslist):
extractframes(v)
try:
softlinkdataset(originalpath, path, srcscene, scene)
except:
print("softlink failed")
quit()
try:
imageundistort(video, offsetlist=[i for i in range(startframe,endframe)],focalscale=scale, fixfocal=None)
except:
print("undistort failed")
quit()
try:
for offset in tqdm.tqdm(range(startframe, endframe)):
convertmodel2dbfiles(video, offset=offset, scale=scale, removeverythingexceptinput=False)
except:
convertmodel2dbfiles(video, offset=offset, scale=scale, removeverythingexceptinput=True)
print("create colmap input failed, better clean the data and try again")
quit()
for offset in range(startframe, endframe): | getcolmapsingleimdistort(video, offset=offset) | 5 | 2023-12-28 04:16:32+00:00 | 8k |
kinggongzilla/ai-clone-whatsapp | train.py | [
{
"identifier": "fsdp_config",
"path": "configs/fsdp.py",
"snippet": "class fsdp_config:\n mixed_precision: bool=True\n use_fp16: bool=False\n sharding_strategy: ShardingStrategy = ShardingStrategy.FULL_SHARD\n checkpoint_type: StateDictType = StateDictType.SHARDED_STATE_DICT # alternativel... | import os
import fire
import random
import torch
import torch.optim as optim
from pkg_resources import packaging
from peft import get_peft_model, prepare_model_for_int8_training
from torch.distributed.fsdp import (
FullyShardedDataParallel as FSDP,
)
from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload
from torch.optim.lr_scheduler import StepLR
from transformers import (
AutoModelForCausalLM,
AutoTokenizer
)
from transformers.models.llama.modeling_llama import LlamaDecoderLayer
from configs.fsdp import fsdp_config as FSDP_CONFIG
from configs.training import train_config as TRAIN_CONFIG
from data.concatenator import ConcatDataset
from utils.config_utils import (
update_config,
generate_peft_config,
generate_dataset_config,
get_dataloader_kwargs,
)
from utils.dataset_utils import get_preprocessed_dataset
from utils.train_utils import (
train,
print_model_size,
) | 4,963 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
def main(**kwargs):
# Update the configuration for the training and sharding process
train_config, fsdp_config = TRAIN_CONFIG(), FSDP_CONFIG()
update_config((train_config, fsdp_config), **kwargs)
if train_config.whatsapp_username is None or train_config.whatsapp_username == "":
raise ValueError("Please provide your whatsapp_user_name in config/training.py or as commandline argument '--whatsapp_username [insert your username]'. Has to be same as in your exported WhatsApp chat .txt files")
# Set the seeds for reproducibility
torch.cuda.manual_seed(train_config.seed)
torch.manual_seed(train_config.seed)
random.seed(train_config.seed)
#clear gpu cache
torch.cuda.empty_cache()
# Load the pre-trained model and setup its configuration
model = AutoModelForCausalLM.from_pretrained(
train_config.model_name,
load_in_4bit=True if train_config.quantization else None,
device_map="auto" if train_config.quantization else None,
)
# Load the tokenizer and add special tokens
tokenizer = AutoTokenizer.from_pretrained(train_config.model_name)
tokenizer.pad_token_id = tokenizer.eos_token_id
print_model_size(model, train_config, 0)
# Prepare the model for int8 training if quantization is enabled
if train_config.quantization:
model = prepare_model_for_int8_training(model)
if train_config.use_peft:
peft_config = generate_peft_config(train_config, kwargs)
model = get_peft_model(model, peft_config)
model.print_trainable_parameters()
#setting up FSDP if enable_fsdp is enabled
if not train_config.quantization and not train_config.enable_fsdp:
model.to("cuda")
dataset_config = generate_dataset_config(train_config, kwargs)
# Load and preprocess the dataset for training and validation
dataset_train = get_preprocessed_dataset(
tokenizer,
dataset_config,
split="train",
)
print(f"--> Training Set Length = {len(dataset_train)}")
if train_config.run_validation:
dataset_val = get_preprocessed_dataset(
tokenizer,
dataset_config,
split="test",
)
print(f"--> Validation Set Length = {len(dataset_val)}")
if train_config.batching_strategy == "packing":
| # Copyright (c) Meta Platforms, Inc. and affiliates.
# This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
def main(**kwargs):
# Update the configuration for the training and sharding process
train_config, fsdp_config = TRAIN_CONFIG(), FSDP_CONFIG()
update_config((train_config, fsdp_config), **kwargs)
if train_config.whatsapp_username is None or train_config.whatsapp_username == "":
raise ValueError("Please provide your whatsapp_user_name in config/training.py or as commandline argument '--whatsapp_username [insert your username]'. Has to be same as in your exported WhatsApp chat .txt files")
# Set the seeds for reproducibility
torch.cuda.manual_seed(train_config.seed)
torch.manual_seed(train_config.seed)
random.seed(train_config.seed)
#clear gpu cache
torch.cuda.empty_cache()
# Load the pre-trained model and setup its configuration
model = AutoModelForCausalLM.from_pretrained(
train_config.model_name,
load_in_4bit=True if train_config.quantization else None,
device_map="auto" if train_config.quantization else None,
)
# Load the tokenizer and add special tokens
tokenizer = AutoTokenizer.from_pretrained(train_config.model_name)
tokenizer.pad_token_id = tokenizer.eos_token_id
print_model_size(model, train_config, 0)
# Prepare the model for int8 training if quantization is enabled
if train_config.quantization:
model = prepare_model_for_int8_training(model)
if train_config.use_peft:
peft_config = generate_peft_config(train_config, kwargs)
model = get_peft_model(model, peft_config)
model.print_trainable_parameters()
#setting up FSDP if enable_fsdp is enabled
if not train_config.quantization and not train_config.enable_fsdp:
model.to("cuda")
dataset_config = generate_dataset_config(train_config, kwargs)
# Load and preprocess the dataset for training and validation
dataset_train = get_preprocessed_dataset(
tokenizer,
dataset_config,
split="train",
)
print(f"--> Training Set Length = {len(dataset_train)}")
if train_config.run_validation:
dataset_val = get_preprocessed_dataset(
tokenizer,
dataset_config,
split="test",
)
print(f"--> Validation Set Length = {len(dataset_val)}")
if train_config.batching_strategy == "packing": | dataset_train = ConcatDataset(dataset_train, chunk_size=train_config.context_length) | 2 | 2023-12-28 00:02:08+00:00 | 8k |
FoundationVision/UniRef | projects/UniRef/uniref/models/deformable_detr/criterion.py | [
{
"identifier": "box_ops",
"path": "projects/UniRef/uniref/util/box_ops.py",
"snippet": "def box_cxcywh_to_xyxy(x):\ndef box_xyxy_to_cxcywh(x):\ndef box_iou(boxes1, boxes2):\ndef multi_box_iou(boxes1, boxes2):\ndef generalized_box_iou(boxes1, boxes2):\ndef generalized_multi_box_iou(boxes1, boxes2):\ndef... | import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
import random
from ...util import box_ops
from .segmentation import (dice_loss, sigmoid_focal_loss, mask_iou_loss, bootstrap_ce_loss, soft_aggregate)
from ...util.misc import (NestedTensor, nested_tensor_from_tensor_list,
accuracy, get_world_size, interpolate,
is_dist_avail_and_initialized, inverse_sigmoid)
from fvcore.nn import giou_loss, smooth_l1_loss | 5,606 |
if len(target_boxes) == 0:
losses = {}
losses['loss_bbox'] = src_boxes.sum() * 0.0
losses['loss_giou'] = src_boxes.sum() * 0.0
if use_iou_branch:
losses['loss_boxiou'] = src_boxes.sum() * 0.0
return losses
# box iou
if use_iou_branch:
with torch.no_grad():
ious = compute_box_iou(box_ops.box_cxcywh_to_xyxy(src_boxes),
box_ops.box_cxcywh_to_xyxy(target_boxes))
tgt_iou_scores = ious
src_iou_scores = outputs['pred_boxious'] # [B, N, 1]
src_iou_scores = src_iou_scores[idx]
src_iou_scores = src_iou_scores.flatten(0)
tgt_iou_scores = tgt_iou_scores.flatten(0)
loss_boxiou = F.binary_cross_entropy_with_logits(src_iou_scores, tgt_iou_scores, reduction='mean')
num_boxes = src_boxes.shape[0] if self.ota else num_boxes
loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction='none')
losses = {}
losses['loss_bbox'] = loss_bbox.sum() / num_boxes
loss_giou = giou_loss(box_ops.box_cxcywh_to_xyxy(src_boxes),box_ops.box_cxcywh_to_xyxy(target_boxes))
# loss_giou = 1 - torch.diag(box_ops.generalized_box_iou(
# box_ops.box_cxcywh_to_xyxy(src_boxes),
# box_ops.box_cxcywh_to_xyxy(target_boxes)))
losses['loss_giou'] = loss_giou.sum() / num_boxes
if use_iou_branch:
losses['loss_boxiou'] = loss_boxiou
return losses
def loss_masks(self, outputs, targets, indices, num_boxes):
"""Compute the losses related to the masks: the focal loss and the dice loss.
targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]
"""
assert "pred_masks" in outputs
src_masks = outputs["pred_masks"]
src_idx = self._get_src_permutation_idx(indices)
tgt_idx = self._get_tgt_permutation_idx(indices)
src_masks = outputs["pred_masks"] # list[tensor]: bs x [1, num_inst, num_frames, H/4, W/4]
bs = len(targets)
# src_masks: bs x [1, num_inst, num_frames, H/4, W/4] or [bs, num_inst, num_frames, H/4, W/4]
if type(src_masks) == list:
src_masks = torch.cat(src_masks, dim=1)[0] # [num_all_inst, num_frames, H/4, W/4]
if src_masks.ndim == 0:
# no mask label (only box label)
losses = {}
losses['loss_mask'] = src_masks * 0.0
losses['loss_dice'] = src_masks * 0.0
if self.mask_aux_loss:
losses["loss_mask_cls"] = src_masks * 0.0
losses["loss_mask_iou"] = src_masks * 0.0
return losses
# TODO use valid to mask invalid areas due to padding in loss
target_masks, valid = nested_tensor_from_tensor_list([t["masks"] for t in targets],
size_divisibility=32,
split=False).decompose()
# during training, the size_divisibility is 32
target_masks = target_masks.to(src_masks) # [bs, max_num_gt, H, W]
# for VOS, supervised in the original resolution
if target_masks.shape[-2:] == src_masks.shape[-2:]:
pass
else:
# downsample ground truth masks with ratio mask_out_stride
start = int(self.mask_out_stride // 2)
im_h, im_w = target_masks.shape[-2:]
target_masks = target_masks[:, :, start::self.mask_out_stride, start::self.mask_out_stride]
assert target_masks.size(2) * self.mask_out_stride == im_h
assert target_masks.size(3) * self.mask_out_stride == im_w
num_frames = src_masks.shape[1]
# # upsample predictions to the target size
# src_masks = interpolate(src_masks, size=target_masks.shape[-2:],
# mode="bilinear", align_corners=False)
target_masks = target_masks.reshape(bs, -1, num_frames, target_masks.shape[-2], target_masks.shape[-1])
target_masks = target_masks[tgt_idx] # [num_all_inst, num_frames, H/4, W/4]
num_boxes = src_masks.shape[0] if self.ota else num_boxes
if len(target_masks) == 0: # no gt
losses = {}
losses['loss_mask'] = src_masks.sum() * 0.0
losses['loss_dice'] = src_masks.sum() * 0.0
if self.mask_aux_loss:
losses["loss_mask_cls"] = src_masks.sum() * 0.0
losses["loss_mask_iou"] = src_masks.sum() * 0.0
return losses
if self.mask_aux_loss:
# convert instance mask to semantice mask
src_masks_aux = src_masks.flatten(0,1).sigmoid() # scores
src_masks_aux_list = []
for src_mask_aux in src_masks_aux:
src_masks_aux_list.append(soft_aggregate(src_mask_aux.unsqueeze(0), keep_bg=True))
src_masks_aux = torch.stack(src_masks_aux_list, dim=0) # [all_num_insts, 2, H, W]
# convert targets, including bg
target_masks_aux = torch.zeros_like(src_masks_aux) # [all_num_insts, 2, H, W]
target_masks_aux[:, 1, :, :] = target_masks.flatten(0,1).float()
target_masks_aux[:, 0, :, :] = 1.0 - target_masks.flatten(0,1).float()
src_masks = src_masks.flatten(1)
target_masks = target_masks.flatten(1)
# src_masks/target_masks: [n_targets, num_frames * H * W]
losses = {
"loss_mask": sigmoid_focal_loss(src_masks, target_masks, num_boxes),
"loss_dice": dice_loss(src_masks, target_masks, num_boxes),
}
if self.mask_aux_loss:
losses.update({"loss_mask_cls": bootstrap_ce_loss(src_masks_aux, target_masks_aux, num_boxes)})
|
class SmoothLabelCrossEntropyLoss(nn.Module):
def __init__(self, eps=0.1, ignore_index=None):
super().__init__()
self.eps = eps
self.log_soft = nn.LogSoftmax(dim=1)
self.kl = nn.KLDivLoss(reduction='none')
self.ignore_index = ignore_index
def forward(self, feature, target):
feature = feature.float()
if self.ignore_index is not None:
valid_mask = target != self.ignore_index
target = target[valid_mask]
feature = feature[valid_mask]
assert target.numel() > 0
eps = self.eps
n_class = feature.size(1)
one_hot = torch.zeros_like(feature).scatter(1, target.view(-1, 1), 1)
one_hot = one_hot * (1 - eps) + (1 - one_hot) * eps / (n_class - 1)
log_prb = self.log_soft(feature)
loss = self.kl(log_prb, one_hot)
return loss.sum(dim=1).mean()
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,
mask_out_stride=4, num_frames=1, ota=False, mask_aux_loss=False, cfg=None):
""" 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
self.mask_out_stride = mask_out_stride
self.num_frames = num_frames
self.ota = ota
self.mask_aux_loss = mask_aux_loss
# boxinst configs
if cfg is not None:
self.boxinst_enabled = cfg.MODEL.BOXINST.ENABLED
self.bottom_pixels_removed = cfg.MODEL.BOXINST.BOTTOM_PIXELS_REMOVED
self.pairwise_size = cfg.MODEL.BOXINST.PAIRWISE.SIZE
self.pairwise_dilation = cfg.MODEL.BOXINST.PAIRWISE.DILATION
self.pairwise_color_thresh = cfg.MODEL.BOXINST.PAIRWISE.COLOR_THRESH
self._warmup_iters = cfg.MODEL.BOXINST.PAIRWISE.WARMUP_ITERS
self.boxinst_topk = cfg.MODEL.BOXINST.TOPK
self.register_buffer("_iter", torch.zeros([1]))
def loss_labels(self, outputs, targets, indices, num_boxes, log=False):
"""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'] # [B, N, K]
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
if len(target_classes_o) == 0: # no gt in the batch
loss_ce = src_logits.sum() * 0.0
losses = {'loss_ce': loss_ce}
return losses
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]
num_boxes = len(idx[0]) if self.ota else num_boxes
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]
return losses
@torch.no_grad()
def loss_cardinality(self, outputs, targets, indices, num_boxes):
""" Compute the cardinality error, ie the absolute error in the number of predicted non-empty boxes
This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients
"""
pred_logits = outputs['pred_logits']
device = pred_logits.device
tgt_lengths = torch.as_tensor([len(v["labels"]) for v in targets], device=device)
# Count the number of predictions that are NOT "no-object" (which is the last class)
card_pred = (pred_logits.argmax(-1) != pred_logits.shape[-1] - 1).sum(1)
card_err = F.l1_loss(card_pred.float(), tgt_lengths.float())
losses = {'cardinality_error': card_err}
return losses
def loss_boxes(self, outputs, targets, indices, num_boxes):
"""Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]
The target boxes are expected in format (center_x, center_y, h, w), normalized by the image size.
"""
assert 'pred_boxes' in outputs
idx = self._get_src_permutation_idx(indices)
src_boxes = outputs['pred_boxes'][idx]
target_boxes = torch.cat([t['boxes'][i] for t, (_, i) in zip(targets, indices)], dim=0)
use_iou_branch = "pred_boxious" in outputs
if len(target_boxes) == 0:
losses = {}
losses['loss_bbox'] = src_boxes.sum() * 0.0
losses['loss_giou'] = src_boxes.sum() * 0.0
if use_iou_branch:
losses['loss_boxiou'] = src_boxes.sum() * 0.0
return losses
# box iou
if use_iou_branch:
with torch.no_grad():
ious = compute_box_iou(box_ops.box_cxcywh_to_xyxy(src_boxes),
box_ops.box_cxcywh_to_xyxy(target_boxes))
tgt_iou_scores = ious
src_iou_scores = outputs['pred_boxious'] # [B, N, 1]
src_iou_scores = src_iou_scores[idx]
src_iou_scores = src_iou_scores.flatten(0)
tgt_iou_scores = tgt_iou_scores.flatten(0)
loss_boxiou = F.binary_cross_entropy_with_logits(src_iou_scores, tgt_iou_scores, reduction='mean')
num_boxes = src_boxes.shape[0] if self.ota else num_boxes
loss_bbox = F.l1_loss(src_boxes, target_boxes, reduction='none')
losses = {}
losses['loss_bbox'] = loss_bbox.sum() / num_boxes
loss_giou = giou_loss(box_ops.box_cxcywh_to_xyxy(src_boxes),box_ops.box_cxcywh_to_xyxy(target_boxes))
# loss_giou = 1 - torch.diag(box_ops.generalized_box_iou(
# box_ops.box_cxcywh_to_xyxy(src_boxes),
# box_ops.box_cxcywh_to_xyxy(target_boxes)))
losses['loss_giou'] = loss_giou.sum() / num_boxes
if use_iou_branch:
losses['loss_boxiou'] = loss_boxiou
return losses
def loss_masks(self, outputs, targets, indices, num_boxes):
"""Compute the losses related to the masks: the focal loss and the dice loss.
targets dicts must contain the key "masks" containing a tensor of dim [nb_target_boxes, h, w]
"""
assert "pred_masks" in outputs
src_masks = outputs["pred_masks"]
src_idx = self._get_src_permutation_idx(indices)
tgt_idx = self._get_tgt_permutation_idx(indices)
src_masks = outputs["pred_masks"] # list[tensor]: bs x [1, num_inst, num_frames, H/4, W/4]
bs = len(targets)
# src_masks: bs x [1, num_inst, num_frames, H/4, W/4] or [bs, num_inst, num_frames, H/4, W/4]
if type(src_masks) == list:
src_masks = torch.cat(src_masks, dim=1)[0] # [num_all_inst, num_frames, H/4, W/4]
if src_masks.ndim == 0:
# no mask label (only box label)
losses = {}
losses['loss_mask'] = src_masks * 0.0
losses['loss_dice'] = src_masks * 0.0
if self.mask_aux_loss:
losses["loss_mask_cls"] = src_masks * 0.0
losses["loss_mask_iou"] = src_masks * 0.0
return losses
# TODO use valid to mask invalid areas due to padding in loss
target_masks, valid = nested_tensor_from_tensor_list([t["masks"] for t in targets],
size_divisibility=32,
split=False).decompose()
# during training, the size_divisibility is 32
target_masks = target_masks.to(src_masks) # [bs, max_num_gt, H, W]
# for VOS, supervised in the original resolution
if target_masks.shape[-2:] == src_masks.shape[-2:]:
pass
else:
# downsample ground truth masks with ratio mask_out_stride
start = int(self.mask_out_stride // 2)
im_h, im_w = target_masks.shape[-2:]
target_masks = target_masks[:, :, start::self.mask_out_stride, start::self.mask_out_stride]
assert target_masks.size(2) * self.mask_out_stride == im_h
assert target_masks.size(3) * self.mask_out_stride == im_w
num_frames = src_masks.shape[1]
# # upsample predictions to the target size
# src_masks = interpolate(src_masks, size=target_masks.shape[-2:],
# mode="bilinear", align_corners=False)
target_masks = target_masks.reshape(bs, -1, num_frames, target_masks.shape[-2], target_masks.shape[-1])
target_masks = target_masks[tgt_idx] # [num_all_inst, num_frames, H/4, W/4]
num_boxes = src_masks.shape[0] if self.ota else num_boxes
if len(target_masks) == 0: # no gt
losses = {}
losses['loss_mask'] = src_masks.sum() * 0.0
losses['loss_dice'] = src_masks.sum() * 0.0
if self.mask_aux_loss:
losses["loss_mask_cls"] = src_masks.sum() * 0.0
losses["loss_mask_iou"] = src_masks.sum() * 0.0
return losses
if self.mask_aux_loss:
# convert instance mask to semantice mask
src_masks_aux = src_masks.flatten(0,1).sigmoid() # scores
src_masks_aux_list = []
for src_mask_aux in src_masks_aux:
src_masks_aux_list.append(soft_aggregate(src_mask_aux.unsqueeze(0), keep_bg=True))
src_masks_aux = torch.stack(src_masks_aux_list, dim=0) # [all_num_insts, 2, H, W]
# convert targets, including bg
target_masks_aux = torch.zeros_like(src_masks_aux) # [all_num_insts, 2, H, W]
target_masks_aux[:, 1, :, :] = target_masks.flatten(0,1).float()
target_masks_aux[:, 0, :, :] = 1.0 - target_masks.flatten(0,1).float()
src_masks = src_masks.flatten(1)
target_masks = target_masks.flatten(1)
# src_masks/target_masks: [n_targets, num_frames * H * W]
losses = {
"loss_mask": sigmoid_focal_loss(src_masks, target_masks, num_boxes),
"loss_dice": dice_loss(src_masks, target_masks, num_boxes),
}
if self.mask_aux_loss:
losses.update({"loss_mask_cls": bootstrap_ce_loss(src_masks_aux, target_masks_aux, num_boxes)}) | losses.update({"loss_mask_iou": mask_iou_loss(src_masks_aux[:, 1, :, :], target_masks_aux[:, 1, :, :], num_boxes)}) | 3 | 2023-12-22 13:31:33+00:00 | 8k |
mkshing/scedit-pytorch | scedit_pytorch/diffusers_modules/unet_2d_condition.py | [
{
"identifier": "get_up_block",
"path": "scedit_pytorch/diffusers_modules/unet_2d_blocks.py",
"snippet": "def get_up_block(\n up_block_type: str,\n num_layers: int,\n in_channels: int,\n out_channels: int,\n prev_output_channel: int,\n temb_channels: int,\n add_upsample: bool,\n ... | from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple, Union
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.loaders import UNet2DConditionLoadersMixin
from diffusers.utils import (
USE_PEFT_BACKEND,
BaseOutput,
deprecate,
logging,
scale_lora_layers,
unscale_lora_layers,
)
from diffusers.models.activations import get_activation
from diffusers.models.attention_processor import (
ADDED_KV_ATTENTION_PROCESSORS,
CROSS_ATTENTION_PROCESSORS,
AttentionProcessor,
AttnAddedKVProcessor,
AttnProcessor,
)
from diffusers.models.embeddings import (
GaussianFourierProjection,
ImageHintTimeEmbedding,
ImageProjection,
ImageTimeEmbedding,
PositionNet,
TextImageProjection,
TextImageTimeEmbedding,
TextTimeEmbedding,
TimestepEmbedding,
Timesteps,
)
from diffusers.models.modeling_utils import ModelMixin
from diffusers.models.unet_2d_blocks import (
UNetMidBlock2D,
UNetMidBlock2DCrossAttn,
UNetMidBlock2DSimpleCrossAttn,
get_down_block,
)
from .unet_2d_blocks import get_up_block
from ..scedit import SCTunerLinearLayer
import torch
import torch.nn as nn
import torch.utils.checkpoint | 4,305 | for i, down_block_type in enumerate(down_block_types):
input_channel = output_channel
output_channel = block_out_channels[i]
is_final_block = i == len(block_out_channels) - 1
down_block = get_down_block(
down_block_type,
num_layers=layers_per_block[i],
transformer_layers_per_block=transformer_layers_per_block[i],
in_channels=input_channel,
out_channels=output_channel,
temb_channels=blocks_time_embed_dim,
add_downsample=not is_final_block,
resnet_eps=norm_eps,
resnet_act_fn=act_fn,
resnet_groups=norm_num_groups,
cross_attention_dim=cross_attention_dim[i],
num_attention_heads=num_attention_heads[i],
downsample_padding=downsample_padding,
dual_cross_attention=dual_cross_attention,
use_linear_projection=use_linear_projection,
only_cross_attention=only_cross_attention[i],
upcast_attention=upcast_attention,
resnet_time_scale_shift=resnet_time_scale_shift,
attention_type=attention_type,
resnet_skip_time_act=resnet_skip_time_act,
resnet_out_scale_factor=resnet_out_scale_factor,
cross_attention_norm=cross_attention_norm,
attention_head_dim=attention_head_dim[i]
if attention_head_dim[i] is not None
else output_channel,
dropout=dropout,
)
self.down_blocks.append(down_block)
# mid
if mid_block_type == "UNetMidBlock2DCrossAttn":
self.mid_block = UNetMidBlock2DCrossAttn(
transformer_layers_per_block=transformer_layers_per_block[-1],
in_channels=block_out_channels[-1],
temb_channels=blocks_time_embed_dim,
dropout=dropout,
resnet_eps=norm_eps,
resnet_act_fn=act_fn,
output_scale_factor=mid_block_scale_factor,
resnet_time_scale_shift=resnet_time_scale_shift,
cross_attention_dim=cross_attention_dim[-1],
num_attention_heads=num_attention_heads[-1],
resnet_groups=norm_num_groups,
dual_cross_attention=dual_cross_attention,
use_linear_projection=use_linear_projection,
upcast_attention=upcast_attention,
attention_type=attention_type,
)
elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
self.mid_block = UNetMidBlock2DSimpleCrossAttn(
in_channels=block_out_channels[-1],
temb_channels=blocks_time_embed_dim,
dropout=dropout,
resnet_eps=norm_eps,
resnet_act_fn=act_fn,
output_scale_factor=mid_block_scale_factor,
cross_attention_dim=cross_attention_dim[-1],
attention_head_dim=attention_head_dim[-1],
resnet_groups=norm_num_groups,
resnet_time_scale_shift=resnet_time_scale_shift,
skip_time_act=resnet_skip_time_act,
only_cross_attention=mid_block_only_cross_attention,
cross_attention_norm=cross_attention_norm,
)
elif mid_block_type == "UNetMidBlock2D":
self.mid_block = UNetMidBlock2D(
in_channels=block_out_channels[-1],
temb_channels=blocks_time_embed_dim,
dropout=dropout,
num_layers=0,
resnet_eps=norm_eps,
resnet_act_fn=act_fn,
output_scale_factor=mid_block_scale_factor,
resnet_groups=norm_num_groups,
resnet_time_scale_shift=resnet_time_scale_shift,
add_attention=False,
)
elif mid_block_type is None:
self.mid_block = None
else:
raise ValueError(f"unknown mid_block_type : {mid_block_type}")
# count how many layers upsample the images
self.num_upsamplers = 0
# up
reversed_block_out_channels = list(reversed(block_out_channels))
reversed_num_attention_heads = list(reversed(num_attention_heads))
reversed_layers_per_block = list(reversed(layers_per_block))
reversed_cross_attention_dim = list(reversed(cross_attention_dim))
reversed_transformer_layers_per_block = (
list(reversed(transformer_layers_per_block))
if reverse_transformer_layers_per_block is None
else reverse_transformer_layers_per_block
)
only_cross_attention = list(reversed(only_cross_attention))
output_channel = reversed_block_out_channels[0]
for i, up_block_type in enumerate(up_block_types):
is_final_block = i == len(block_out_channels) - 1
prev_output_channel = output_channel
output_channel = reversed_block_out_channels[i]
input_channel = reversed_block_out_channels[
min(i + 1, len(block_out_channels) - 1)
]
# add upsample block for all BUT final layer
if not is_final_block:
add_upsample = True
self.num_upsamplers += 1
else:
add_upsample = False
| # Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
@dataclass
class UNet2DConditionOutput(BaseOutput):
"""
The output of [`UNet2DConditionModel`].
Args:
sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
"""
sample: torch.FloatTensor = None
class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
r"""
A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
shaped output.
This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
for all models (such as downloading or saving).
Parameters:
sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
Height and width of input/output sample.
in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
flip_sin_to_cos (`bool`, *optional*, defaults to `False`):
Whether to flip the sin to cos in the time embedding.
freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
The tuple of downsample blocks to use.
mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
`UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
The tuple of upsample blocks to use.
only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
Whether to include self-attention in the basic transformer blocks, see
[`~models.attention.BasicTransformerBlock`].
block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
The tuple of output channels for each block.
layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
If `None`, normalization and activation layers is skipped in post-processing.
norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
The dimension of the cross attention features.
transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
[`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
[`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
[`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
[`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
encoder_hid_dim (`int`, *optional*, defaults to None):
If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
dimension to `cross_attention_dim`.
encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
num_attention_heads (`int`, *optional*):
The number of attention heads. If not defined, defaults to `attention_head_dim`
resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
class_embed_type (`str`, *optional*, defaults to `None`):
The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
`"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
addition_embed_type (`str`, *optional*, defaults to `None`):
Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
"text". "text" will use the `TextTimeEmbedding` layer.
addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
Dimension for the timestep embeddings.
num_class_embeds (`int`, *optional*, defaults to `None`):
Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
class conditioning with `class_embed_type` equal to `None`.
time_embedding_type (`str`, *optional*, defaults to `positional`):
The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
time_embedding_dim (`int`, *optional*, defaults to `None`):
An optional override for the dimension of the projected time embedding.
time_embedding_act_fn (`str`, *optional*, defaults to `None`):
Optional activation function to use only once on the time embeddings before they are passed to the rest of
the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
timestep_post_act (`str`, *optional*, defaults to `None`):
The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
time_cond_proj_dim (`int`, *optional*, defaults to `None`):
The dimension of `cond_proj` layer in the timestep embedding.
conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer. conv_out_kernel (`int`,
*optional*, default to `3`): The kernel size of `conv_out` layer. projection_class_embeddings_input_dim (`int`,
*optional*): The dimension of the `class_labels` input when
`class_embed_type="projection"`. Required when `class_embed_type="projection"`.
class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
embeddings with the class embeddings.
mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
`only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
`only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
otherwise.
"""
_supports_gradient_checkpointing = True
@register_to_config
def __init__(
self,
sample_size: Optional[int] = None,
in_channels: int = 4,
out_channels: int = 4,
center_input_sample: bool = False,
flip_sin_to_cos: bool = True,
freq_shift: int = 0,
down_block_types: Tuple[str] = (
"CrossAttnDownBlock2D",
"CrossAttnDownBlock2D",
"CrossAttnDownBlock2D",
"DownBlock2D",
),
mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
up_block_types: Tuple[str] = (
"UpBlock2D",
"CrossAttnUpBlock2D",
"CrossAttnUpBlock2D",
"CrossAttnUpBlock2D",
),
only_cross_attention: Union[bool, Tuple[bool]] = False,
block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
layers_per_block: Union[int, Tuple[int]] = 2,
downsample_padding: int = 1,
mid_block_scale_factor: float = 1,
dropout: float = 0.0,
act_fn: str = "silu",
norm_num_groups: Optional[int] = 32,
norm_eps: float = 1e-5,
cross_attention_dim: Union[int, Tuple[int]] = 1280,
transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
encoder_hid_dim: Optional[int] = None,
encoder_hid_dim_type: Optional[str] = None,
attention_head_dim: Union[int, Tuple[int]] = 8,
num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
dual_cross_attention: bool = False,
use_linear_projection: bool = False,
class_embed_type: Optional[str] = None,
addition_embed_type: Optional[str] = None,
addition_time_embed_dim: Optional[int] = None,
num_class_embeds: Optional[int] = None,
upcast_attention: bool = False,
resnet_time_scale_shift: str = "default",
resnet_skip_time_act: bool = False,
resnet_out_scale_factor: int = 1.0,
time_embedding_type: str = "positional",
time_embedding_dim: Optional[int] = None,
time_embedding_act_fn: Optional[str] = None,
timestep_post_act: Optional[str] = None,
time_cond_proj_dim: Optional[int] = None,
conv_in_kernel: int = 3,
conv_out_kernel: int = 3,
projection_class_embeddings_input_dim: Optional[int] = None,
attention_type: str = "default",
class_embeddings_concat: bool = False,
mid_block_only_cross_attention: Optional[bool] = None,
cross_attention_norm: Optional[str] = None,
addition_embed_type_num_heads=64,
):
super().__init__()
self.sample_size = sample_size
if num_attention_heads is not None:
raise ValueError(
"At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19."
)
# If `num_attention_heads` is not defined (which is the case for most models)
# it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
# The reason for this behavior is to correct for incorrectly named variables that were introduced
# when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
# Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
# which is why we correct for the naming here.
num_attention_heads = num_attention_heads or attention_head_dim
# Check inputs
if len(down_block_types) != len(up_block_types):
raise ValueError(
f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."
)
if len(block_out_channels) != len(down_block_types):
raise ValueError(
f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
)
if not isinstance(only_cross_attention, bool) and len(
only_cross_attention
) != len(down_block_types):
raise ValueError(
f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
)
if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(
down_block_types
):
raise ValueError(
f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
)
if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(
down_block_types
):
raise ValueError(
f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
)
if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(
down_block_types
):
raise ValueError(
f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}."
)
if not isinstance(layers_per_block, int) and len(layers_per_block) != len(
down_block_types
):
raise ValueError(
f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
)
if (
isinstance(transformer_layers_per_block, list)
and reverse_transformer_layers_per_block is None
):
for layer_number_per_block in transformer_layers_per_block:
if isinstance(layer_number_per_block, list):
raise ValueError(
"Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet."
)
# input
conv_in_padding = (conv_in_kernel - 1) // 2
self.conv_in = nn.Conv2d(
in_channels,
block_out_channels[0],
kernel_size=conv_in_kernel,
padding=conv_in_padding,
)
# time
if time_embedding_type == "fourier":
time_embed_dim = time_embedding_dim or block_out_channels[0] * 2
if time_embed_dim % 2 != 0:
raise ValueError(
f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}."
)
self.time_proj = GaussianFourierProjection(
time_embed_dim // 2,
set_W_to_weight=False,
log=False,
flip_sin_to_cos=flip_sin_to_cos,
)
timestep_input_dim = time_embed_dim
elif time_embedding_type == "positional":
time_embed_dim = time_embedding_dim or block_out_channels[0] * 4
self.time_proj = Timesteps(
block_out_channels[0], flip_sin_to_cos, freq_shift
)
timestep_input_dim = block_out_channels[0]
else:
raise ValueError(
f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
)
self.time_embedding = TimestepEmbedding(
timestep_input_dim,
time_embed_dim,
act_fn=act_fn,
post_act_fn=timestep_post_act,
cond_proj_dim=time_cond_proj_dim,
)
if encoder_hid_dim_type is None and encoder_hid_dim is not None:
encoder_hid_dim_type = "text_proj"
self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
logger.info(
"encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined."
)
if encoder_hid_dim is None and encoder_hid_dim_type is not None:
raise ValueError(
f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
)
if encoder_hid_dim_type == "text_proj":
self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
elif encoder_hid_dim_type == "text_image_proj":
# image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
# they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
# case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)`
self.encoder_hid_proj = TextImageProjection(
text_embed_dim=encoder_hid_dim,
image_embed_dim=cross_attention_dim,
cross_attention_dim=cross_attention_dim,
)
elif encoder_hid_dim_type == "image_proj":
# Kandinsky 2.2
self.encoder_hid_proj = ImageProjection(
image_embed_dim=encoder_hid_dim,
cross_attention_dim=cross_attention_dim,
)
elif encoder_hid_dim_type is not None:
raise ValueError(
f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
)
else:
self.encoder_hid_proj = None
# class embedding
if class_embed_type is None and num_class_embeds is not None:
self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
elif class_embed_type == "timestep":
self.class_embedding = TimestepEmbedding(
timestep_input_dim, time_embed_dim, act_fn=act_fn
)
elif class_embed_type == "identity":
self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
elif class_embed_type == "projection":
if projection_class_embeddings_input_dim is None:
raise ValueError(
"`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
)
# The projection `class_embed_type` is the same as the timestep `class_embed_type` except
# 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
# 2. it projects from an arbitrary input dimension.
#
# Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
# When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
# As a result, `TimestepEmbedding` can be passed arbitrary vectors.
self.class_embedding = TimestepEmbedding(
projection_class_embeddings_input_dim, time_embed_dim
)
elif class_embed_type == "simple_projection":
if projection_class_embeddings_input_dim is None:
raise ValueError(
"`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set"
)
self.class_embedding = nn.Linear(
projection_class_embeddings_input_dim, time_embed_dim
)
else:
self.class_embedding = None
if addition_embed_type == "text":
if encoder_hid_dim is not None:
text_time_embedding_from_dim = encoder_hid_dim
else:
text_time_embedding_from_dim = cross_attention_dim
self.add_embedding = TextTimeEmbedding(
text_time_embedding_from_dim,
time_embed_dim,
num_heads=addition_embed_type_num_heads,
)
elif addition_embed_type == "text_image":
# text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
# they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
# case when `addition_embed_type == "text_image"` (Kadinsky 2.1)`
self.add_embedding = TextImageTimeEmbedding(
text_embed_dim=cross_attention_dim,
image_embed_dim=cross_attention_dim,
time_embed_dim=time_embed_dim,
)
elif addition_embed_type == "text_time":
self.add_time_proj = Timesteps(
addition_time_embed_dim, flip_sin_to_cos, freq_shift
)
self.add_embedding = TimestepEmbedding(
projection_class_embeddings_input_dim, time_embed_dim
)
elif addition_embed_type == "image":
# Kandinsky 2.2
self.add_embedding = ImageTimeEmbedding(
image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim
)
elif addition_embed_type == "image_hint":
# Kandinsky 2.2 ControlNet
self.add_embedding = ImageHintTimeEmbedding(
image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim
)
elif addition_embed_type is not None:
raise ValueError(
f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'."
)
if time_embedding_act_fn is None:
self.time_embed_act = None
else:
self.time_embed_act = get_activation(time_embedding_act_fn)
self.down_blocks = nn.ModuleList([])
self.up_blocks = nn.ModuleList([])
if isinstance(only_cross_attention, bool):
if mid_block_only_cross_attention is None:
mid_block_only_cross_attention = only_cross_attention
only_cross_attention = [only_cross_attention] * len(down_block_types)
if mid_block_only_cross_attention is None:
mid_block_only_cross_attention = False
if isinstance(num_attention_heads, int):
num_attention_heads = (num_attention_heads,) * len(down_block_types)
if isinstance(attention_head_dim, int):
attention_head_dim = (attention_head_dim,) * len(down_block_types)
if isinstance(cross_attention_dim, int):
cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
if isinstance(layers_per_block, int):
layers_per_block = [layers_per_block] * len(down_block_types)
if isinstance(transformer_layers_per_block, int):
transformer_layers_per_block = [transformer_layers_per_block] * len(
down_block_types
)
if class_embeddings_concat:
# The time embeddings are concatenated with the class embeddings. The dimension of the
# time embeddings passed to the down, middle, and up blocks is twice the dimension of the
# regular time embeddings
blocks_time_embed_dim = time_embed_dim * 2
else:
blocks_time_embed_dim = time_embed_dim
# down
output_channel = block_out_channels[0]
for i, down_block_type in enumerate(down_block_types):
input_channel = output_channel
output_channel = block_out_channels[i]
is_final_block = i == len(block_out_channels) - 1
down_block = get_down_block(
down_block_type,
num_layers=layers_per_block[i],
transformer_layers_per_block=transformer_layers_per_block[i],
in_channels=input_channel,
out_channels=output_channel,
temb_channels=blocks_time_embed_dim,
add_downsample=not is_final_block,
resnet_eps=norm_eps,
resnet_act_fn=act_fn,
resnet_groups=norm_num_groups,
cross_attention_dim=cross_attention_dim[i],
num_attention_heads=num_attention_heads[i],
downsample_padding=downsample_padding,
dual_cross_attention=dual_cross_attention,
use_linear_projection=use_linear_projection,
only_cross_attention=only_cross_attention[i],
upcast_attention=upcast_attention,
resnet_time_scale_shift=resnet_time_scale_shift,
attention_type=attention_type,
resnet_skip_time_act=resnet_skip_time_act,
resnet_out_scale_factor=resnet_out_scale_factor,
cross_attention_norm=cross_attention_norm,
attention_head_dim=attention_head_dim[i]
if attention_head_dim[i] is not None
else output_channel,
dropout=dropout,
)
self.down_blocks.append(down_block)
# mid
if mid_block_type == "UNetMidBlock2DCrossAttn":
self.mid_block = UNetMidBlock2DCrossAttn(
transformer_layers_per_block=transformer_layers_per_block[-1],
in_channels=block_out_channels[-1],
temb_channels=blocks_time_embed_dim,
dropout=dropout,
resnet_eps=norm_eps,
resnet_act_fn=act_fn,
output_scale_factor=mid_block_scale_factor,
resnet_time_scale_shift=resnet_time_scale_shift,
cross_attention_dim=cross_attention_dim[-1],
num_attention_heads=num_attention_heads[-1],
resnet_groups=norm_num_groups,
dual_cross_attention=dual_cross_attention,
use_linear_projection=use_linear_projection,
upcast_attention=upcast_attention,
attention_type=attention_type,
)
elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
self.mid_block = UNetMidBlock2DSimpleCrossAttn(
in_channels=block_out_channels[-1],
temb_channels=blocks_time_embed_dim,
dropout=dropout,
resnet_eps=norm_eps,
resnet_act_fn=act_fn,
output_scale_factor=mid_block_scale_factor,
cross_attention_dim=cross_attention_dim[-1],
attention_head_dim=attention_head_dim[-1],
resnet_groups=norm_num_groups,
resnet_time_scale_shift=resnet_time_scale_shift,
skip_time_act=resnet_skip_time_act,
only_cross_attention=mid_block_only_cross_attention,
cross_attention_norm=cross_attention_norm,
)
elif mid_block_type == "UNetMidBlock2D":
self.mid_block = UNetMidBlock2D(
in_channels=block_out_channels[-1],
temb_channels=blocks_time_embed_dim,
dropout=dropout,
num_layers=0,
resnet_eps=norm_eps,
resnet_act_fn=act_fn,
output_scale_factor=mid_block_scale_factor,
resnet_groups=norm_num_groups,
resnet_time_scale_shift=resnet_time_scale_shift,
add_attention=False,
)
elif mid_block_type is None:
self.mid_block = None
else:
raise ValueError(f"unknown mid_block_type : {mid_block_type}")
# count how many layers upsample the images
self.num_upsamplers = 0
# up
reversed_block_out_channels = list(reversed(block_out_channels))
reversed_num_attention_heads = list(reversed(num_attention_heads))
reversed_layers_per_block = list(reversed(layers_per_block))
reversed_cross_attention_dim = list(reversed(cross_attention_dim))
reversed_transformer_layers_per_block = (
list(reversed(transformer_layers_per_block))
if reverse_transformer_layers_per_block is None
else reverse_transformer_layers_per_block
)
only_cross_attention = list(reversed(only_cross_attention))
output_channel = reversed_block_out_channels[0]
for i, up_block_type in enumerate(up_block_types):
is_final_block = i == len(block_out_channels) - 1
prev_output_channel = output_channel
output_channel = reversed_block_out_channels[i]
input_channel = reversed_block_out_channels[
min(i + 1, len(block_out_channels) - 1)
]
# add upsample block for all BUT final layer
if not is_final_block:
add_upsample = True
self.num_upsamplers += 1
else:
add_upsample = False
| up_block = get_up_block( | 0 | 2023-12-22 05:37:58+00:00 | 8k |
xhuangcv/humannorm | threestudio/models/guidance/controlnet_guidance.py | [
{
"identifier": "PromptProcessorOutput",
"path": "threestudio/models/prompt_processors/base.py",
"snippet": "class PromptProcessorOutput:\n text_embeddings: Float[Tensor, \"N Nf\"]\n uncond_text_embeddings: Float[Tensor, \"N Nf\"]\n text_embeddings_vd: Float[Tensor, \"Nv N Nf\"]\n uncond_tex... | import os
import cv2
import numpy as np
import torch
import torch.nn.functional as F
import threestudio
from dataclasses import dataclass
from controlnet_aux import CannyDetector, NormalBaeDetector
from diffusers import ControlNetModel, DDIMScheduler, StableDiffusionControlNetPipeline
from diffusers.utils.import_utils import is_xformers_available
from tqdm import tqdm
from threestudio.models.prompt_processors.base import PromptProcessorOutput
from threestudio.utils.base import BaseObject
from threestudio.utils.misc import C, parse_version
from threestudio.utils.typing import *
from threestudio.utils.config import ExperimentConfig, load_config
from threestudio.utils.typing import Optional | 4,775 | ) -> Float[Tensor, "B 4 64 64"]:
self.scheduler.config.num_train_timesteps = t.item()
self.scheduler.set_timesteps(self.cfg.diffusion_steps)
with torch.no_grad():
# add noise
noise = torch.randn_like(latents)
latents = self.scheduler.add_noise(latents, noise, t) # type: ignore
# sections of code used from https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py
threestudio.debug("Start editing...")
for i, t in enumerate(self.scheduler.timesteps):
# predict the noise residual with unet, NO grad!
with torch.no_grad():
# pred noise
latent_model_input = torch.cat([latents] * 2)
(
down_block_res_samples,
mid_block_res_sample,
) = self.forward_controlnet(
latent_model_input,
t,
encoder_hidden_states=text_embeddings,
image_cond=image_cond,
condition_scale=self.cfg.condition_scale,
)
noise_pred = self.forward_control_unet(
latent_model_input,
t,
encoder_hidden_states=text_embeddings,
cross_attention_kwargs=None,
down_block_additional_residuals=down_block_res_samples,
mid_block_additional_residual=mid_block_res_sample,
)
# perform classifier-free guidance
noise_pred_text, noise_pred_uncond = noise_pred.chunk(2)
noise_pred = noise_pred_uncond + self.cfg.guidance_scale * (
noise_pred_text - noise_pred_uncond
)
# get previous sample, continue loop
latents = self.scheduler.step(noise_pred, t, latents).prev_sample
threestudio.debug("Editing finished.")
return latents
def prepare_image_cond(self, cond_rgb: Float[Tensor, "B H W C"]):
if self.cfg.control_type == "normal":
cond_rgb = (
(cond_rgb[0].detach().cpu().numpy() * 255).astype(np.uint8).copy()
)
detected_map = self.preprocessor(cond_rgb)
control = (
torch.from_numpy(np.array(detected_map)).float().to(self.device) / 255.0
)
control = control.unsqueeze(0)
control = control.permute(0, 3, 1, 2)
elif self.cfg.control_type == "canny":
cond_rgb = (
(cond_rgb[0].detach().cpu().numpy() * 255).astype(np.uint8).copy()
)
blurred_img = cv2.blur(cond_rgb, ksize=(5, 5))
detected_map = self.preprocessor(
blurred_img, self.cfg.canny_lower_bound, self.cfg.canny_upper_bound
)
control = (
torch.from_numpy(np.array(detected_map)).float().to(self.device) / 255.0
)
control = control.unsqueeze(-1).repeat(1, 1, 3)
control = control.unsqueeze(0)
control = control.permute(0, 3, 1, 2)
elif self.cfg.control_type == "input_normal":
control = cond_rgb.permute(0, 3, 1, 2)
else:
raise ValueError(f"Unknown control type: {self.cfg.control_type}")
return F.interpolate(control, (512, 512), mode="bilinear", align_corners=False)
def compute_grad_sds(
self,
text_embeddings: Float[Tensor, "BB 77 768"],
latents: Float[Tensor, "B 4 64 64"],
image_cond: Float[Tensor, "B 3 512 512"],
t: Int[Tensor, "B"],
):
with torch.no_grad():
# add noise
noise = torch.randn_like(latents) # TODO: use torch generator
latents_noisy = self.scheduler.add_noise(latents, noise, t)
# pred noise
latent_model_input = torch.cat([latents_noisy] * 2)
down_block_res_samples, mid_block_res_sample = self.forward_controlnet(
latent_model_input,
t,
encoder_hidden_states=text_embeddings,
image_cond=image_cond,
condition_scale=self.cfg.condition_scale,
)
noise_pred = self.forward_control_unet(
latent_model_input,
t,
encoder_hidden_states=text_embeddings,
cross_attention_kwargs=None,
down_block_additional_residuals=down_block_res_samples,
mid_block_additional_residual=mid_block_res_sample,
)
# perform classifier-free guidance
noise_pred_text, noise_pred_uncond = noise_pred.chunk(2)
noise_pred = noise_pred_uncond + self.cfg.guidance_scale * (
noise_pred_text - noise_pred_uncond
)
w = (1 - self.alphas[t]).view(-1, 1, 1, 1)
grad = w * (noise_pred - noise)
return grad
def __call__(
self,
rgb: Float[Tensor, "B H W C"],
cond_rgb: Float[Tensor, "B H W C"],
|
@threestudio.register("stable-diffusion-controlnet-guidance")
class ControlNetGuidance(BaseObject):
@dataclass
class Config(BaseObject.Config):
cache_dir: Optional[str] = None
pretrained_model_name_or_path: str = "SG161222/Realistic_Vision_V2.0"
ddim_scheduler_name_or_path: str = "/home/xinhuang/.cache/huggingface/hub/models--CompVis--stable-diffusion-v1-4/snapshots/59ec6bdf37d6279d3c0faf36e89ff1aa34f7ebf4"
control_type: str = "normal" # normal/canny
enable_memory_efficient_attention: bool = False
enable_sequential_cpu_offload: bool = False
enable_attention_slicing: bool = False
enable_channels_last_format: bool = False
guidance_scale: float = 7.5
condition_scale: float = 1.5
grad_clip: Optional[
Any
] = None # field(default_factory=lambda: [0, 2.0, 8.0, 1000])
half_precision_weights: bool = True
min_step_percent: float = 0.02
max_step_percent: float = 0.98
diffusion_steps: int = 20
use_sds: bool = False
# Canny threshold
canny_lower_bound: int = 50
canny_upper_bound: int = 100
cfg: Config
def configure(self) -> None:
threestudio.info(f"Loading ControlNet ...")
controlnet_name_or_path: str
if self.cfg.control_type in ("normal", "input_normal"):
controlnet_name_or_path = "/home/xinhuang/.cache/huggingface/hub/models--lllyasviel--control_v11p_sd15_normalbae/snapshots/cb7296e6587a219068e9d65864e38729cd862aa8"
elif self.cfg.control_type == "canny":
controlnet_name_or_path = "/home/xinhuang/.cache/huggingface/hub/models--lllyasviel--control_v11p_sd15_canny/snapshots/115a470d547982438f70198e353a921996e2e819"
self.weights_dtype = (
torch.float16 if self.cfg.half_precision_weights else torch.float32
)
pipe_kwargs = {
"safety_checker": None,
"feature_extractor": None,
"requires_safety_checker": False,
"torch_dtype": self.weights_dtype,
"cache_dir": self.cfg.cache_dir,
}
controlnet = ControlNetModel.from_pretrained(
controlnet_name_or_path,
torch_dtype=self.weights_dtype,
cache_dir=self.cfg.cache_dir,
)
self.pipe = StableDiffusionControlNetPipeline.from_pretrained(
self.cfg.pretrained_model_name_or_path, controlnet=controlnet, **pipe_kwargs
).to(self.device)
self.scheduler = DDIMScheduler.from_pretrained(
self.cfg.ddim_scheduler_name_or_path,
subfolder="scheduler",
torch_dtype=self.weights_dtype,
cache_dir=self.cfg.cache_dir,
)
self.scheduler.set_timesteps(self.cfg.diffusion_steps)
if self.cfg.enable_memory_efficient_attention:
if parse_version(torch.__version__) >= parse_version("2"):
threestudio.info(
"PyTorch2.0 uses memory efficient attention by default."
)
elif not is_xformers_available():
threestudio.warn(
"xformers is not available, memory efficient attention is not enabled."
)
else:
self.pipe.enable_xformers_memory_efficient_attention()
if self.cfg.enable_sequential_cpu_offload:
self.pipe.enable_sequential_cpu_offload()
if self.cfg.enable_attention_slicing:
self.pipe.enable_attention_slicing(1)
if self.cfg.enable_channels_last_format:
self.pipe.unet.to(memory_format=torch.channels_last)
# Create model
self.vae = self.pipe.vae.eval()
self.unet = self.pipe.unet.eval()
self.controlnet = self.pipe.controlnet.eval()
if self.cfg.control_type == "normal":
self.preprocessor = NormalBaeDetector.from_pretrained(
"/home/xinhuang/.cache/huggingface/hub/models--lllyasviel--Annotators/snapshots/9a7d84251d487d11c4834466779de6b0d2c44486"
)
self.preprocessor.model.to(self.device)
elif self.cfg.control_type == "canny":
self.preprocessor = CannyDetector()
for p in self.vae.parameters():
p.requires_grad_(False)
for p in self.unet.parameters():
p.requires_grad_(False)
self.num_train_timesteps = self.scheduler.config.num_train_timesteps
self.set_min_max_steps() # set to default value
self.alphas: Float[Tensor, "..."] = self.scheduler.alphas_cumprod.to(
self.device
)
self.grad_clip_val: Optional[float] = None
threestudio.info(f"Loaded ControlNet!")
@torch.cuda.amp.autocast(enabled=False)
def set_min_max_steps(self, min_step_percent=0.02, max_step_percent=0.98):
self.min_step = int(self.num_train_timesteps * min_step_percent)
self.max_step = int(self.num_train_timesteps * max_step_percent)
@torch.cuda.amp.autocast(enabled=False)
def forward_controlnet(
self,
latents: Float[Tensor, "..."],
t: Float[Tensor, "..."],
image_cond: Float[Tensor, "..."],
condition_scale: float,
encoder_hidden_states: Float[Tensor, "..."],
) -> Float[Tensor, "..."]:
return self.controlnet(
latents.to(self.weights_dtype),
t.to(self.weights_dtype),
encoder_hidden_states=encoder_hidden_states.to(self.weights_dtype),
controlnet_cond=image_cond.to(self.weights_dtype),
conditioning_scale=condition_scale,
return_dict=False,
)
@torch.cuda.amp.autocast(enabled=False)
def forward_control_unet(
self,
latents: Float[Tensor, "..."],
t: Float[Tensor, "..."],
encoder_hidden_states: Float[Tensor, "..."],
cross_attention_kwargs,
down_block_additional_residuals,
mid_block_additional_residual,
) -> Float[Tensor, "..."]:
input_dtype = latents.dtype
return self.unet(
latents.to(self.weights_dtype),
t.to(self.weights_dtype),
encoder_hidden_states=encoder_hidden_states.to(self.weights_dtype),
cross_attention_kwargs=cross_attention_kwargs,
down_block_additional_residuals=down_block_additional_residuals,
mid_block_additional_residual=mid_block_additional_residual,
).sample.to(input_dtype)
@torch.cuda.amp.autocast(enabled=False)
def encode_images(
self, imgs: Float[Tensor, "B 3 512 512"]
) -> Float[Tensor, "B 4 64 64"]:
input_dtype = imgs.dtype
imgs = imgs * 2.0 - 1.0
posterior = self.vae.encode(imgs.to(self.weights_dtype)).latent_dist
latents = posterior.sample() * self.vae.config.scaling_factor
return latents.to(input_dtype)
@torch.cuda.amp.autocast(enabled=False)
def encode_cond_images(
self, imgs: Float[Tensor, "B 3 512 512"]
) -> Float[Tensor, "B 4 64 64"]:
input_dtype = imgs.dtype
imgs = imgs * 2.0 - 1.0
posterior = self.vae.encode(imgs.to(self.weights_dtype)).latent_dist
latents = posterior.mode()
uncond_image_latents = torch.zeros_like(latents)
latents = torch.cat([latents, latents, uncond_image_latents], dim=0)
return latents.to(input_dtype)
@torch.cuda.amp.autocast(enabled=False)
def decode_latents(
self,
latents: Float[Tensor, "B 4 H W"],
latent_height: int = 64,
latent_width: int = 64,
) -> Float[Tensor, "B 3 512 512"]:
input_dtype = latents.dtype
latents = F.interpolate(
latents, (latent_height, latent_width), mode="bilinear", align_corners=False
)
latents = 1 / self.vae.config.scaling_factor * latents
image = self.vae.decode(latents.to(self.weights_dtype)).sample
image = (image * 0.5 + 0.5).clamp(0, 1)
return image.to(input_dtype)
def edit_latents(
self,
text_embeddings: Float[Tensor, "BB 77 768"],
latents: Float[Tensor, "B 4 64 64"],
image_cond: Float[Tensor, "B 3 512 512"],
t: Int[Tensor, "B"],
) -> Float[Tensor, "B 4 64 64"]:
self.scheduler.config.num_train_timesteps = t.item()
self.scheduler.set_timesteps(self.cfg.diffusion_steps)
with torch.no_grad():
# add noise
noise = torch.randn_like(latents)
latents = self.scheduler.add_noise(latents, noise, t) # type: ignore
# sections of code used from https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_instruct_pix2pix.py
threestudio.debug("Start editing...")
for i, t in enumerate(self.scheduler.timesteps):
# predict the noise residual with unet, NO grad!
with torch.no_grad():
# pred noise
latent_model_input = torch.cat([latents] * 2)
(
down_block_res_samples,
mid_block_res_sample,
) = self.forward_controlnet(
latent_model_input,
t,
encoder_hidden_states=text_embeddings,
image_cond=image_cond,
condition_scale=self.cfg.condition_scale,
)
noise_pred = self.forward_control_unet(
latent_model_input,
t,
encoder_hidden_states=text_embeddings,
cross_attention_kwargs=None,
down_block_additional_residuals=down_block_res_samples,
mid_block_additional_residual=mid_block_res_sample,
)
# perform classifier-free guidance
noise_pred_text, noise_pred_uncond = noise_pred.chunk(2)
noise_pred = noise_pred_uncond + self.cfg.guidance_scale * (
noise_pred_text - noise_pred_uncond
)
# get previous sample, continue loop
latents = self.scheduler.step(noise_pred, t, latents).prev_sample
threestudio.debug("Editing finished.")
return latents
def prepare_image_cond(self, cond_rgb: Float[Tensor, "B H W C"]):
if self.cfg.control_type == "normal":
cond_rgb = (
(cond_rgb[0].detach().cpu().numpy() * 255).astype(np.uint8).copy()
)
detected_map = self.preprocessor(cond_rgb)
control = (
torch.from_numpy(np.array(detected_map)).float().to(self.device) / 255.0
)
control = control.unsqueeze(0)
control = control.permute(0, 3, 1, 2)
elif self.cfg.control_type == "canny":
cond_rgb = (
(cond_rgb[0].detach().cpu().numpy() * 255).astype(np.uint8).copy()
)
blurred_img = cv2.blur(cond_rgb, ksize=(5, 5))
detected_map = self.preprocessor(
blurred_img, self.cfg.canny_lower_bound, self.cfg.canny_upper_bound
)
control = (
torch.from_numpy(np.array(detected_map)).float().to(self.device) / 255.0
)
control = control.unsqueeze(-1).repeat(1, 1, 3)
control = control.unsqueeze(0)
control = control.permute(0, 3, 1, 2)
elif self.cfg.control_type == "input_normal":
control = cond_rgb.permute(0, 3, 1, 2)
else:
raise ValueError(f"Unknown control type: {self.cfg.control_type}")
return F.interpolate(control, (512, 512), mode="bilinear", align_corners=False)
def compute_grad_sds(
self,
text_embeddings: Float[Tensor, "BB 77 768"],
latents: Float[Tensor, "B 4 64 64"],
image_cond: Float[Tensor, "B 3 512 512"],
t: Int[Tensor, "B"],
):
with torch.no_grad():
# add noise
noise = torch.randn_like(latents) # TODO: use torch generator
latents_noisy = self.scheduler.add_noise(latents, noise, t)
# pred noise
latent_model_input = torch.cat([latents_noisy] * 2)
down_block_res_samples, mid_block_res_sample = self.forward_controlnet(
latent_model_input,
t,
encoder_hidden_states=text_embeddings,
image_cond=image_cond,
condition_scale=self.cfg.condition_scale,
)
noise_pred = self.forward_control_unet(
latent_model_input,
t,
encoder_hidden_states=text_embeddings,
cross_attention_kwargs=None,
down_block_additional_residuals=down_block_res_samples,
mid_block_additional_residual=mid_block_res_sample,
)
# perform classifier-free guidance
noise_pred_text, noise_pred_uncond = noise_pred.chunk(2)
noise_pred = noise_pred_uncond + self.cfg.guidance_scale * (
noise_pred_text - noise_pred_uncond
)
w = (1 - self.alphas[t]).view(-1, 1, 1, 1)
grad = w * (noise_pred - noise)
return grad
def __call__(
self,
rgb: Float[Tensor, "B H W C"],
cond_rgb: Float[Tensor, "B H W C"], | prompt_utils: PromptProcessorOutput, | 0 | 2023-12-23 12:37:48+00:00 | 8k |
jesenzhang/ComfyUI_StreamDiffusion | streamdiffusion/acceleration/tensorrt/utilities.py | [
{
"identifier": "CLIP",
"path": "streamdiffusion/acceleration/tensorrt/models.py",
"snippet": "class CLIP(BaseModel):\n def __init__(self, device, max_batch_size, embedding_dim, min_batch_size=1):\n super(CLIP, self).__init__(\n device=device,\n max_batch_size=max_batch_s... | import gc
import numpy as np
import onnx
import onnx_graphsurgeon as gs
import tensorrt as trt
import torch
from collections import OrderedDict
from typing import *
from cuda import cudart
from PIL import Image
from polygraphy import cuda
from polygraphy.backend.common import bytes_from_path
from polygraphy.backend.trt import (
CreateConfig,
Profile,
engine_from_bytes,
engine_from_network,
network_from_onnx_path,
save_engine,
)
from polygraphy.backend.trt import util as trt_util
from .models import CLIP, VAE, BaseModel, UNet, VAEEncoder | 6,281 |
if workspace_size > 0:
config_kwargs["memory_pool_limits"] = {trt.MemoryPoolType.WORKSPACE: workspace_size}
if not enable_all_tactics:
config_kwargs["tactic_sources"] = []
engine = engine_from_network(
network_from_onnx_path(onnx_path, flags=[trt.OnnxParserFlag.NATIVE_INSTANCENORM]),
config=CreateConfig(
fp16=fp16, refittable=enable_refit, profiles=[p], load_timing_cache=timing_cache, **config_kwargs
),
save_timing_cache=timing_cache,
)
save_engine(engine, path=self.engine_path)
def load(self):
print(f"Loading TensorRT engine: {self.engine_path}")
self.engine = engine_from_bytes(bytes_from_path(self.engine_path))
def activate(self, reuse_device_memory=None):
if reuse_device_memory:
self.context = self.engine.create_execution_context_without_device_memory()
self.context.device_memory = reuse_device_memory
else:
self.context = self.engine.create_execution_context()
def allocate_buffers(self, shape_dict=None, device="cuda"):
for idx in range(trt_util.get_bindings_per_profile(self.engine)):
binding = self.engine[idx]
if shape_dict and binding in shape_dict:
shape = shape_dict[binding]
else:
shape = self.engine.get_binding_shape(binding)
dtype = trt.nptype(self.engine.get_binding_dtype(binding))
if self.engine.binding_is_input(binding):
self.context.set_binding_shape(idx, shape)
tensor = torch.empty(tuple(shape), dtype=numpy_to_torch_dtype_dict[dtype]).to(device=device)
self.tensors[binding] = tensor
def infer(self, feed_dict, stream, use_cuda_graph=False):
for name, buf in feed_dict.items():
self.tensors[name].copy_(buf)
for name, tensor in self.tensors.items():
self.context.set_tensor_address(name, tensor.data_ptr())
if use_cuda_graph:
if self.cuda_graph_instance is not None:
CUASSERT(cudart.cudaGraphLaunch(self.cuda_graph_instance, stream.ptr))
CUASSERT(cudart.cudaStreamSynchronize(stream.ptr))
else:
# do inference before CUDA graph capture
noerror = self.context.execute_async_v3(stream.ptr)
if not noerror:
raise ValueError("ERROR: inference failed.")
# capture cuda graph
CUASSERT(
cudart.cudaStreamBeginCapture(stream.ptr, cudart.cudaStreamCaptureMode.cudaStreamCaptureModeGlobal)
)
self.context.execute_async_v3(stream.ptr)
self.graph = CUASSERT(cudart.cudaStreamEndCapture(stream.ptr))
self.cuda_graph_instance = CUASSERT(cudart.cudaGraphInstantiate(self.graph, 0))
else:
noerror = self.context.execute_async_v3(stream.ptr)
if not noerror:
raise ValueError("ERROR: inference failed.")
return self.tensors
def decode_images(images: torch.Tensor):
images = (
((images + 1) * 255 / 2).clamp(0, 255).detach().permute(0, 2, 3, 1).round().type(torch.uint8).cpu().numpy()
)
return [Image.fromarray(x) for x in images]
def preprocess_image(image: Image.Image):
w, h = image.size
w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
image = image.resize((w, h))
init_image = np.array(image).astype(np.float32) / 255.0
init_image = init_image[None].transpose(0, 3, 1, 2)
init_image = torch.from_numpy(init_image).contiguous()
return 2.0 * init_image - 1.0
def prepare_mask_and_masked_image(image: Image.Image, mask: Image.Image):
if isinstance(image, Image.Image):
image = np.array(image.convert("RGB"))
image = image[None].transpose(0, 3, 1, 2)
image = torch.from_numpy(image).to(dtype=torch.float32).contiguous() / 127.5 - 1.0
if isinstance(mask, Image.Image):
mask = np.array(mask.convert("L"))
mask = mask.astype(np.float32) / 255.0
mask = mask[None, None]
mask[mask < 0.5] = 0
mask[mask >= 0.5] = 1
mask = torch.from_numpy(mask).to(dtype=torch.float32).contiguous()
masked_image = image * (mask < 0.5)
return mask, masked_image
def create_models(
model_id: str,
use_auth_token: Optional[str],
device: Union[str, torch.device],
max_batch_size: int,
unet_in_channels: int = 4,
embedding_dim: int = 768,
):
models = {
"clip": CLIP(
hf_token=use_auth_token,
device=device,
max_batch_size=max_batch_size,
embedding_dim=embedding_dim,
),
| #! fork: https://github.com/NVIDIA/TensorRT/blob/main/demo/Diffusion/utilities.py
#
# Copyright 2022 The HuggingFace Inc. team.
# SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
TRT_LOGGER = trt.Logger(trt.Logger.ERROR)
# Map of numpy dtype -> torch dtype
numpy_to_torch_dtype_dict = {
np.uint8: torch.uint8,
np.int8: torch.int8,
np.int16: torch.int16,
np.int32: torch.int32,
np.int64: torch.int64,
np.float16: torch.float16,
np.float32: torch.float32,
np.float64: torch.float64,
np.complex64: torch.complex64,
np.complex128: torch.complex128,
}
if np.version.full_version >= "1.24.0":
numpy_to_torch_dtype_dict[np.bool_] = torch.bool
else:
numpy_to_torch_dtype_dict[np.bool] = torch.bool
# Map of torch dtype -> numpy dtype
torch_to_numpy_dtype_dict = {value: key for (key, value) in numpy_to_torch_dtype_dict.items()}
def CUASSERT(cuda_ret):
err = cuda_ret[0]
if err != cudart.cudaError_t.cudaSuccess:
raise RuntimeError(
f"CUDA ERROR: {err}, error code reference: https://nvidia.github.io/cuda-python/module/cudart.html#cuda.cudart.cudaError_t"
)
if len(cuda_ret) > 1:
return cuda_ret[1]
return None
class Engine:
def __init__(
self,
engine_path,
):
self.engine_path = engine_path
self.engine = None
self.context = None
self.buffers = OrderedDict()
self.tensors = OrderedDict()
self.cuda_graph_instance = None # cuda graph
def __del__(self):
[buf.free() for buf in self.buffers.values() if isinstance(buf, cuda.DeviceArray)]
del self.engine
del self.context
del self.buffers
del self.tensors
def refit(self, onnx_path, onnx_refit_path):
def convert_int64(arr):
# TODO: smarter conversion
if len(arr.shape) == 0:
return np.int32(arr)
return arr
def add_to_map(refit_dict, name, values):
if name in refit_dict:
assert refit_dict[name] is None
if values.dtype == np.int64:
values = convert_int64(values)
refit_dict[name] = values
print(f"Refitting TensorRT engine with {onnx_refit_path} weights")
refit_nodes = gs.import_onnx(onnx.load(onnx_refit_path)).toposort().nodes
# Construct mapping from weight names in refit model -> original model
name_map = {}
for n, node in enumerate(gs.import_onnx(onnx.load(onnx_path)).toposort().nodes):
refit_node = refit_nodes[n]
assert node.op == refit_node.op
# Constant nodes in ONNX do not have inputs but have a constant output
if node.op == "Constant":
name_map[refit_node.outputs[0].name] = node.outputs[0].name
# Handle scale and bias weights
elif node.op == "Conv":
if node.inputs[1].__class__ == gs.Constant:
name_map[refit_node.name + "_TRTKERNEL"] = node.name + "_TRTKERNEL"
if node.inputs[2].__class__ == gs.Constant:
name_map[refit_node.name + "_TRTBIAS"] = node.name + "_TRTBIAS"
# For all other nodes: find node inputs that are initializers (gs.Constant)
else:
for i, inp in enumerate(node.inputs):
if inp.__class__ == gs.Constant:
name_map[refit_node.inputs[i].name] = inp.name
def map_name(name):
if name in name_map:
return name_map[name]
return name
# Construct refit dictionary
refit_dict = {}
refitter = trt.Refitter(self.engine, TRT_LOGGER)
all_weights = refitter.get_all()
for layer_name, role in zip(all_weights[0], all_weights[1]):
# for speciailized roles, use a unique name in the map:
if role == trt.WeightsRole.KERNEL:
name = layer_name + "_TRTKERNEL"
elif role == trt.WeightsRole.BIAS:
name = layer_name + "_TRTBIAS"
else:
name = layer_name
assert name not in refit_dict, "Found duplicate layer: " + name
refit_dict[name] = None
for n in refit_nodes:
# Constant nodes in ONNX do not have inputs but have a constant output
if n.op == "Constant":
name = map_name(n.outputs[0].name)
print(f"Add Constant {name}\n")
add_to_map(refit_dict, name, n.outputs[0].values)
# Handle scale and bias weights
elif n.op == "Conv":
if n.inputs[1].__class__ == gs.Constant:
name = map_name(n.name + "_TRTKERNEL")
add_to_map(refit_dict, name, n.inputs[1].values)
if n.inputs[2].__class__ == gs.Constant:
name = map_name(n.name + "_TRTBIAS")
add_to_map(refit_dict, name, n.inputs[2].values)
# For all other nodes: find node inputs that are initializers (AKA gs.Constant)
else:
for inp in n.inputs:
name = map_name(inp.name)
if inp.__class__ == gs.Constant:
add_to_map(refit_dict, name, inp.values)
for layer_name, weights_role in zip(all_weights[0], all_weights[1]):
if weights_role == trt.WeightsRole.KERNEL:
custom_name = layer_name + "_TRTKERNEL"
elif weights_role == trt.WeightsRole.BIAS:
custom_name = layer_name + "_TRTBIAS"
else:
custom_name = layer_name
# Skip refitting Trilu for now; scalar weights of type int64 value 1 - for clip model
if layer_name.startswith("onnx::Trilu"):
continue
if refit_dict[custom_name] is not None:
refitter.set_weights(layer_name, weights_role, refit_dict[custom_name])
else:
print(f"[W] No refit weights for layer: {layer_name}")
if not refitter.refit_cuda_engine():
print("Failed to refit!")
exit(0)
def build(
self,
onnx_path,
fp16,
input_profile=None,
enable_refit=False,
enable_all_tactics=False,
timing_cache=None,
workspace_size=0,
):
print(f"Building TensorRT engine for {onnx_path}: {self.engine_path}")
p = Profile()
if input_profile:
for name, dims in input_profile.items():
assert len(dims) == 3
p.add(name, min=dims[0], opt=dims[1], max=dims[2])
config_kwargs = {}
if workspace_size > 0:
config_kwargs["memory_pool_limits"] = {trt.MemoryPoolType.WORKSPACE: workspace_size}
if not enable_all_tactics:
config_kwargs["tactic_sources"] = []
engine = engine_from_network(
network_from_onnx_path(onnx_path, flags=[trt.OnnxParserFlag.NATIVE_INSTANCENORM]),
config=CreateConfig(
fp16=fp16, refittable=enable_refit, profiles=[p], load_timing_cache=timing_cache, **config_kwargs
),
save_timing_cache=timing_cache,
)
save_engine(engine, path=self.engine_path)
def load(self):
print(f"Loading TensorRT engine: {self.engine_path}")
self.engine = engine_from_bytes(bytes_from_path(self.engine_path))
def activate(self, reuse_device_memory=None):
if reuse_device_memory:
self.context = self.engine.create_execution_context_without_device_memory()
self.context.device_memory = reuse_device_memory
else:
self.context = self.engine.create_execution_context()
def allocate_buffers(self, shape_dict=None, device="cuda"):
for idx in range(trt_util.get_bindings_per_profile(self.engine)):
binding = self.engine[idx]
if shape_dict and binding in shape_dict:
shape = shape_dict[binding]
else:
shape = self.engine.get_binding_shape(binding)
dtype = trt.nptype(self.engine.get_binding_dtype(binding))
if self.engine.binding_is_input(binding):
self.context.set_binding_shape(idx, shape)
tensor = torch.empty(tuple(shape), dtype=numpy_to_torch_dtype_dict[dtype]).to(device=device)
self.tensors[binding] = tensor
def infer(self, feed_dict, stream, use_cuda_graph=False):
for name, buf in feed_dict.items():
self.tensors[name].copy_(buf)
for name, tensor in self.tensors.items():
self.context.set_tensor_address(name, tensor.data_ptr())
if use_cuda_graph:
if self.cuda_graph_instance is not None:
CUASSERT(cudart.cudaGraphLaunch(self.cuda_graph_instance, stream.ptr))
CUASSERT(cudart.cudaStreamSynchronize(stream.ptr))
else:
# do inference before CUDA graph capture
noerror = self.context.execute_async_v3(stream.ptr)
if not noerror:
raise ValueError("ERROR: inference failed.")
# capture cuda graph
CUASSERT(
cudart.cudaStreamBeginCapture(stream.ptr, cudart.cudaStreamCaptureMode.cudaStreamCaptureModeGlobal)
)
self.context.execute_async_v3(stream.ptr)
self.graph = CUASSERT(cudart.cudaStreamEndCapture(stream.ptr))
self.cuda_graph_instance = CUASSERT(cudart.cudaGraphInstantiate(self.graph, 0))
else:
noerror = self.context.execute_async_v3(stream.ptr)
if not noerror:
raise ValueError("ERROR: inference failed.")
return self.tensors
def decode_images(images: torch.Tensor):
images = (
((images + 1) * 255 / 2).clamp(0, 255).detach().permute(0, 2, 3, 1).round().type(torch.uint8).cpu().numpy()
)
return [Image.fromarray(x) for x in images]
def preprocess_image(image: Image.Image):
w, h = image.size
w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
image = image.resize((w, h))
init_image = np.array(image).astype(np.float32) / 255.0
init_image = init_image[None].transpose(0, 3, 1, 2)
init_image = torch.from_numpy(init_image).contiguous()
return 2.0 * init_image - 1.0
def prepare_mask_and_masked_image(image: Image.Image, mask: Image.Image):
if isinstance(image, Image.Image):
image = np.array(image.convert("RGB"))
image = image[None].transpose(0, 3, 1, 2)
image = torch.from_numpy(image).to(dtype=torch.float32).contiguous() / 127.5 - 1.0
if isinstance(mask, Image.Image):
mask = np.array(mask.convert("L"))
mask = mask.astype(np.float32) / 255.0
mask = mask[None, None]
mask[mask < 0.5] = 0
mask[mask >= 0.5] = 1
mask = torch.from_numpy(mask).to(dtype=torch.float32).contiguous()
masked_image = image * (mask < 0.5)
return mask, masked_image
def create_models(
model_id: str,
use_auth_token: Optional[str],
device: Union[str, torch.device],
max_batch_size: int,
unet_in_channels: int = 4,
embedding_dim: int = 768,
):
models = {
"clip": CLIP(
hf_token=use_auth_token,
device=device,
max_batch_size=max_batch_size,
embedding_dim=embedding_dim,
), | "unet": UNet( | 3 | 2023-12-29 09:00:03+00:00 | 8k |
pjaos/ct6_meter_os | software/ct6_app_server/lib/db_handler.py | [
{
"identifier": "ConfigBase",
"path": "software/ct6_app_server/lib/config.py",
"snippet": "class ConfigBase(ConfigManager):\n \"\"\"@brief Responsible for managing configuration used by all apps.\"\"\"\n ICONS_ADDRESS = \"ICONS_ADDRESS\"\n ICONS_PORT = \"ICONS_POR... | from p3lib.database_if import DBConfig, DatabaseIF
from .config import ConfigBase
from .base_constants import BaseConstants | 4,419 | #!/usr/bin/env python3
class DBHandler(BaseConstants):
"""@brief Responsible for interacting with the database."""
def __init__(self, uio, config):
"""@brief Constructor
@param uio A UIO instance.
@param config A ConfigBase instance."""
self._uio = uio
self._config = config
self._dataBaseIF = None
def connect(self):
"""@brief connect to the database server."""
self.disconnect()
self._setupDBConfig()
self._dataBaseIF.connectNoDB()
self._uio.info("Connected to MySQL server.")
def disconnect(self):
"""@brief Shutdown the connection to the DBS"""
if self._dataBaseIF:
self._dataBaseIF.disconnect()
self._dataBaseIF = None
def _setupDBConfig(self):
"""@brief Setup the internal DB config"""
self._dataBaseIF = None
self._dbConfig = DBConfig()
| #!/usr/bin/env python3
class DBHandler(BaseConstants):
"""@brief Responsible for interacting with the database."""
def __init__(self, uio, config):
"""@brief Constructor
@param uio A UIO instance.
@param config A ConfigBase instance."""
self._uio = uio
self._config = config
self._dataBaseIF = None
def connect(self):
"""@brief connect to the database server."""
self.disconnect()
self._setupDBConfig()
self._dataBaseIF.connectNoDB()
self._uio.info("Connected to MySQL server.")
def disconnect(self):
"""@brief Shutdown the connection to the DBS"""
if self._dataBaseIF:
self._dataBaseIF.disconnect()
self._dataBaseIF = None
def _setupDBConfig(self):
"""@brief Setup the internal DB config"""
self._dataBaseIF = None
self._dbConfig = DBConfig() | self._dbConfig.serverAddress = self._config.getAttr(ConfigBase.DB_HOST) | 0 | 2023-12-24 06:32:07+00:00 | 8k |
neobundy/MLX-Stable-Diffusion-WebUI | stable_diffusion/model_io.py | [
{
"identifier": "CLIPTextModel",
"path": "stable_diffusion/clip.py",
"snippet": "class CLIPTextModel(nn.Module):\n \"\"\"Implements the text encoder transformer from CLIP.\"\"\"\n\n def __init__(self, config: CLIPTextModelConfig):\n super().__init__()\n\n self.token_embedding = nn.Em... | from typing import Optional
from functools import partial
from huggingface_hub import hf_hub_download
from mlx.utils import tree_unflatten
from safetensors import safe_open as safetensor_open
from .clip import CLIPTextModel
from .config import AutoencoderConfig, CLIPTextModelConfig, DiffusionConfig, UNetConfig
from .tokenizer import Tokenizer
from .unet import UNetModel
from .vae import Autoencoder
from .models import _DEFAULT_MODEL, _MODELS
from .config import DiffuserModelPathConfig
from tqdm import tqdm
import json
import mlx.core as mx
import numpy as np | 6,805 | value = value.transpose(0, 2, 3, 1)
_debug_print(f"Transposed dimensions in {key}")
return [(key, _from_numpy(value))]
def map_clip_text_encoder_weights(key, value):
# Remove prefixes
if key.startswith("text_model."):
key = key[11:]
_debug_print(f"Removed 'text_model.' prefix from {key}")
if key.startswith("embeddings."):
key = key[11:]
_debug_print(f"Removed 'embeddings.' prefix from {key}")
if key.startswith("encoder."):
key = key[8:]
_debug_print(f"Removed 'encoder.' prefix from {key}")
# Map attention layers
if "self_attn." in key:
key = key.replace("self_attn.", "attention.")
_debug_print(f"Replaced 'self_attn.' with 'attention.' in {key}")
if "q_proj." in key:
key = key.replace("q_proj.", "query_proj.")
_debug_print(f"Replaced 'q_proj.' with 'query_proj.' in {key}")
if "k_proj." in key:
key = key.replace("k_proj.", "key_proj.")
_debug_print(f"Replaced 'k_proj.' with 'key_proj.' in {key}")
if "v_proj." in key:
key = key.replace("v_proj.", "value_proj.")
_debug_print(f"Replaced 'v_proj.' with 'value_proj.' in {key}")
# Map ffn layers
if "mlp.fc1" in key:
key = key.replace("mlp.fc1", "linear1")
_debug_print(f"Replaced 'mlp.fc1' with 'linear1' in {key}")
if "mlp.fc2" in key:
key = key.replace("mlp.fc2", "linear2")
_debug_print(f"Replaced 'mlp.fc2' with 'linear2' in {key}")
return [(key, _from_numpy(value))]
def map_vae_weights(key, value):
# Map up/downsampling
if "downsamplers" in key:
key = key.replace("downsamplers.0.conv", "downsample")
_debug_print(f"Replaced 'downsamplers.0.conv' with 'downsample' in {key}")
if "upsamplers" in key:
key = key.replace("upsamplers.0.conv", "upsample")
_debug_print(f"Replaced 'upsamplers.0.conv' with 'upsample' in {key}")
# Map attention layers
if "to_k" in key:
key = key.replace("to_k", "key_proj")
_debug_print(f"Replaced 'to_k' with 'key_proj' in {key}")
if "to_out.0" in key:
key = key.replace("to_out.0", "out_proj")
_debug_print(f"Replaced 'to_out.0' with 'out_proj' in {key}")
if "to_q" in key:
key = key.replace("to_q", "query_proj")
_debug_print(f"Replaced 'to_q' with 'query_proj' in {key}")
if "to_v" in key:
key = key.replace("to_v", "value_proj")
_debug_print(f"Replaced 'to_v' with 'value_proj' in {key}")
# Map the mid block
if "mid_block.resnets.0" in key:
key = key.replace("mid_block.resnets.0", "mid_blocks.0")
_debug_print(f"Replaced 'mid_block.resnets.0' with 'mid_blocks.0' in {key}")
if "mid_block.attentions.0" in key:
key = key.replace("mid_block.attentions.0", "mid_blocks.1")
_debug_print(f"Replaced 'mid_block.attentions.0' with 'mid_blocks.1' in {key}")
if "mid_block.resnets.1" in key:
key = key.replace("mid_block.resnets.1", "mid_blocks.2")
_debug_print(f"Replaced 'mid_block.resnets.1' with 'mid_blocks.2' in {key}")
# Map the quant/post_quant layers
if "quant_conv" in key:
key = key.replace("quant_conv", "quant_proj")
value = value.squeeze()
_debug_print(f"Replaced 'quant_conv' with 'quant_proj' and squeezed value in {key}")
# Map the conv_shortcut to linear
if "conv_shortcut.weight" in key:
value = value.squeeze()
_debug_print(f"Squeezed 'conv_shortcut.weight' in {key}")
# Rearrange the dimensions to [B, H, W, C] - Autoencoder expects: B, H, W, C = x.shape
if len(value.shape) == 4:
value = value.transpose(0, 2, 3, 1)
_debug_print(f"Transposed dimensions in {key}")
return [(key, _from_numpy(value))]
def _flatten(params):
return [(k, v) for p in params for (k, v) in p]
# The weights of the model can be loaded as 16-bit floating point numbers, which is a form of quantization known as half-precision floating point.
# This can reduce the memory requirements of the model by half compared to 32-bit floating point numbers, at the cost of reduced numerical precision.
def _load_safetensor_weights(mapper, model, weight_file, float16: bool = False):
dtype = np.float16 if float16 else np.float32
_debug_print(f"Loading weights from {weight_file}")
with safetensor_open(weight_file, framework="numpy") as f:
keys = list(f.keys())
weights = _flatten([mapper(k, f.get_tensor(k).astype(dtype)) for k in tqdm(keys, desc=f"Loading weights from {weight_file}...")])
model.update(tree_unflatten(weights))
def _check_key(key: str, part: str):
if key not in _MODELS:
raise ValueError(
f"[{part}] '{key}' model not found, choose one of {{{','.join(_MODELS.keys())}}}"
)
| # Copyright © 2023 Apple Inc.
logfile = 'log.txt'
_DEBUG = False
def _debug_print(*args, **kwargs):
if _DEBUG:
# Convert the arguments to a string
message = ' '.join(map(str, args))
# Print the message to the console
print(message, **kwargs)
# Open the log file in append mode and write the message
with open(logfile, 'a') as f:
f.write(message + '\n')
def _from_numpy(x):
return mx.array(np.ascontiguousarray(x))
# The `map_*_weights` functions are used to adjust the weights of a model when loading it from a file.
# The weights of the model in the file might be in a different format than the weights of the model in the current codebase.
# When you load a pre-trained model, the weights are stored in a dictionary where the keys are the names of the parameters in the model.
# If the architecture of your model is different from the architecture of the model that the weights were trained on, you might need to adjust the keys and/or the weights to match your model's architecture.
# This is what the `map_*_weights` functions are doing. They are adjusting the keys and the weights to match the architecture of the models in the current codebase.
def map_unet_weights(key, value):
# Map up/downsampling
if "downsamplers" in key:
key = key.replace("downsamplers.0.conv", "downsample")
_debug_print(f"Replaced 'downsamplers.0.conv' with 'downsample' in {key}")
if "upsamplers" in key:
key = key.replace("upsamplers.0.conv", "upsample")
_debug_print(f"Replaced 'upsamplers.0.conv' with 'upsample' in {key}")
# Map the mid block
if "mid_block.resnets.0" in key:
key = key.replace("mid_block.resnets.0", "mid_blocks.0")
_debug_print(f"Replaced 'mid_block.resnets.0' with 'mid_blocks.0' in {key}")
if "mid_block.attentions.0" in key:
key = key.replace("mid_block.attentions.0", "mid_blocks.1")
_debug_print(f"Replaced 'mid_block.attentions.0' with 'mid_blocks.1' in {key}")
if "mid_block.resnets.1" in key:
key = key.replace("mid_block.resnets.1", "mid_blocks.2")
_debug_print(f"Replaced 'mid_block.resnets.1' with 'mid_blocks.2' in {key}")
# Map attention layers
if "to_k" in key:
key = key.replace("to_k", "key_proj")
_debug_print(f"Replaced 'to_k' with 'key_proj' in {key}")
if "to_out.0" in key:
key = key.replace("to_out.0", "out_proj")
_debug_print(f"Replaced 'to_out.0' with 'out_proj' in {key}")
if "to_q" in key:
key = key.replace("to_q", "query_proj")
_debug_print(f"Replaced 'to_q' with 'query_proj' in {key}")
if "to_v" in key:
key = key.replace("to_v", "value_proj")
_debug_print(f"Replaced 'to_v' with 'value_proj' in {key}")
# Map transformer ffn
if "ff.net.2" in key:
key = key.replace("ff.net.2", "linear3")
_debug_print(f"Replaced 'ff.net.2' with 'linear3' in {key}")
if "ff.net.0" in key:
k1 = key.replace("ff.net.0.proj", "linear1")
k2 = key.replace("ff.net.0.proj", "linear2")
v1, v2 = np.split(value, 2)
_debug_print(f"Replaced 'ff.net.0.proj' with 'linear1' and 'linear2' in {key}")
return [(k1, _from_numpy(v1)), (k2, _from_numpy(v2))]
# The weights of this 1x1 convolutional layer would be a 4-dimensional tensor
# with shape [out_channels, in_channels, 1, 1].
# The squeeze() function is used to remove the dimensions of size 1 from this tensor,
# converting it to a 2-dimensional tensor with shape [out_channels, in_channels].
# This is because the corresponding layer in the current model might be a linear layer
# rather than a convolutional layer, and the weights for a linear layer are expected to be a 2-dimensional tensor.
if "conv_shortcut.weight" in key:
value = value.squeeze()
_debug_print(f"Squeezed 'conv_shortcut.weight' in {key}")
# Transform the weights from 1x1 convs to linear
if len(value.shape) == 4 and ("proj_in" in key or "proj_out" in key):
value = value.squeeze()
_debug_print(f"Squeezed 'proj_in' or 'proj_out' in {key}")
if len(value.shape) == 4:
value = value.transpose(0, 2, 3, 1)
_debug_print(f"Transposed dimensions in {key}")
return [(key, _from_numpy(value))]
def map_clip_text_encoder_weights(key, value):
# Remove prefixes
if key.startswith("text_model."):
key = key[11:]
_debug_print(f"Removed 'text_model.' prefix from {key}")
if key.startswith("embeddings."):
key = key[11:]
_debug_print(f"Removed 'embeddings.' prefix from {key}")
if key.startswith("encoder."):
key = key[8:]
_debug_print(f"Removed 'encoder.' prefix from {key}")
# Map attention layers
if "self_attn." in key:
key = key.replace("self_attn.", "attention.")
_debug_print(f"Replaced 'self_attn.' with 'attention.' in {key}")
if "q_proj." in key:
key = key.replace("q_proj.", "query_proj.")
_debug_print(f"Replaced 'q_proj.' with 'query_proj.' in {key}")
if "k_proj." in key:
key = key.replace("k_proj.", "key_proj.")
_debug_print(f"Replaced 'k_proj.' with 'key_proj.' in {key}")
if "v_proj." in key:
key = key.replace("v_proj.", "value_proj.")
_debug_print(f"Replaced 'v_proj.' with 'value_proj.' in {key}")
# Map ffn layers
if "mlp.fc1" in key:
key = key.replace("mlp.fc1", "linear1")
_debug_print(f"Replaced 'mlp.fc1' with 'linear1' in {key}")
if "mlp.fc2" in key:
key = key.replace("mlp.fc2", "linear2")
_debug_print(f"Replaced 'mlp.fc2' with 'linear2' in {key}")
return [(key, _from_numpy(value))]
def map_vae_weights(key, value):
# Map up/downsampling
if "downsamplers" in key:
key = key.replace("downsamplers.0.conv", "downsample")
_debug_print(f"Replaced 'downsamplers.0.conv' with 'downsample' in {key}")
if "upsamplers" in key:
key = key.replace("upsamplers.0.conv", "upsample")
_debug_print(f"Replaced 'upsamplers.0.conv' with 'upsample' in {key}")
# Map attention layers
if "to_k" in key:
key = key.replace("to_k", "key_proj")
_debug_print(f"Replaced 'to_k' with 'key_proj' in {key}")
if "to_out.0" in key:
key = key.replace("to_out.0", "out_proj")
_debug_print(f"Replaced 'to_out.0' with 'out_proj' in {key}")
if "to_q" in key:
key = key.replace("to_q", "query_proj")
_debug_print(f"Replaced 'to_q' with 'query_proj' in {key}")
if "to_v" in key:
key = key.replace("to_v", "value_proj")
_debug_print(f"Replaced 'to_v' with 'value_proj' in {key}")
# Map the mid block
if "mid_block.resnets.0" in key:
key = key.replace("mid_block.resnets.0", "mid_blocks.0")
_debug_print(f"Replaced 'mid_block.resnets.0' with 'mid_blocks.0' in {key}")
if "mid_block.attentions.0" in key:
key = key.replace("mid_block.attentions.0", "mid_blocks.1")
_debug_print(f"Replaced 'mid_block.attentions.0' with 'mid_blocks.1' in {key}")
if "mid_block.resnets.1" in key:
key = key.replace("mid_block.resnets.1", "mid_blocks.2")
_debug_print(f"Replaced 'mid_block.resnets.1' with 'mid_blocks.2' in {key}")
# Map the quant/post_quant layers
if "quant_conv" in key:
key = key.replace("quant_conv", "quant_proj")
value = value.squeeze()
_debug_print(f"Replaced 'quant_conv' with 'quant_proj' and squeezed value in {key}")
# Map the conv_shortcut to linear
if "conv_shortcut.weight" in key:
value = value.squeeze()
_debug_print(f"Squeezed 'conv_shortcut.weight' in {key}")
# Rearrange the dimensions to [B, H, W, C] - Autoencoder expects: B, H, W, C = x.shape
if len(value.shape) == 4:
value = value.transpose(0, 2, 3, 1)
_debug_print(f"Transposed dimensions in {key}")
return [(key, _from_numpy(value))]
def _flatten(params):
return [(k, v) for p in params for (k, v) in p]
# The weights of the model can be loaded as 16-bit floating point numbers, which is a form of quantization known as half-precision floating point.
# This can reduce the memory requirements of the model by half compared to 32-bit floating point numbers, at the cost of reduced numerical precision.
def _load_safetensor_weights(mapper, model, weight_file, float16: bool = False):
dtype = np.float16 if float16 else np.float32
_debug_print(f"Loading weights from {weight_file}")
with safetensor_open(weight_file, framework="numpy") as f:
keys = list(f.keys())
weights = _flatten([mapper(k, f.get_tensor(k).astype(dtype)) for k in tqdm(keys, desc=f"Loading weights from {weight_file}...")])
model.update(tree_unflatten(weights))
def _check_key(key: str, part: str):
if key not in _MODELS:
raise ValueError(
f"[{part}] '{key}' model not found, choose one of {{{','.join(_MODELS.keys())}}}"
)
| def load_unet(key: str = _DEFAULT_MODEL, float16: bool = False): | 8 | 2023-12-25 05:49:34+00:00 | 8k |
Con6924/SPM | train_spm_xl.py | [
{
"identifier": "SPMNetwork",
"path": "src/models/spm.py",
"snippet": "class SPMNetwork(nn.Module):\n UNET_TARGET_REPLACE_MODULE_TRANSFORMER = [\n \"Transformer2DModel\",\n ]\n UNET_TARGET_REPLACE_MODULE_CONV = [\n \"ResnetBlock2D\",\n \"Downsample2D\",\n \"Upsample2... | import argparse
import gc
import torch
import src.engine.train_util as train_util
import wandb
from pathlib import Path
from tqdm import tqdm
from src.models.spm import (
SPMNetwork,
SPMLayer,
)
from src.engine.sampling import sample_xl
from src.models import model_util
from src.evaluation import eval_util
from src.configs import config as config_pkg
from src.configs import prompt as prompt_pkg
from src.configs.config import RootConfig
from src.configs.prompt import PromptEmbedsCache, PromptEmbedsPair, PromptSettings, PromptEmbedsXL | 5,383 | # ref:
# - https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py#L566
# - https://huggingface.co/spaces/baulab/Erasing-Concepts-In-Diffusion/blob/main/train.py
# - https://github.com/p1atdev/LECO/blob/main/train_lora_xl.py
DEVICE_CUDA = torch.device("cuda:0")
NUM_IMAGES_PER_PROMPT = 1
def flush():
torch.cuda.empty_cache()
gc.collect()
def train(
| # ref:
# - https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py#L566
# - https://huggingface.co/spaces/baulab/Erasing-Concepts-In-Diffusion/blob/main/train.py
# - https://github.com/p1atdev/LECO/blob/main/train_lora_xl.py
DEVICE_CUDA = torch.device("cuda:0")
NUM_IMAGES_PER_PROMPT = 1
def flush():
torch.cuda.empty_cache()
gc.collect()
def train( | config: RootConfig, | 7 | 2023-12-26 03:19:16+00:00 | 8k |
davep/oshit | oshit/app/widgets/comment_card.py | [
{
"identifier": "HN",
"path": "oshit/hn/client.py",
"snippet": "class HN:\n \"\"\"HackerNews API client.\"\"\"\n\n AGENT: Final[str] = \"Orange Site Hit (https://github.com/davep/oshit)\"\n \"\"\"The agent string to use when talking to the API.\"\"\"\n\n _BASE: Final[str] = \"https://hacker-... | from dataclasses import dataclass
from webbrowser import open as open_url
from textual import on
from textual.app import ComposeResult
from textual.containers import Vertical
from textual.binding import Binding
from textual.css.query import NoMatches
from textual.events import Click
from textual.message import Message
from textual.widget import Widget
from textual.widgets import Label
from humanize import naturaltime
from ...hn import HN
from ...hn.item import Article, Comment
from ..screens.user import UserDetails | 4,334 | """Provides a card for displaying a HackerNews comment."""
##############################################################################
# Python imports.
##############################################################################
# Textual imports.
##############################################################################
# Humanize imports.
##############################################################################
# Local imports.
##############################################################################
class CommentCard(Vertical, can_focus=True):
"""Widget that displays a comment."""
DEFAULT_CSS = """
$card-border: heavy;
CommentCard {
border-left: $card-border $primary;
border-bottom: $card-border $primary;
padding: 1 0 1 1;
margin: 0 1 1 1;
height: auto;
color: $text 70%;
CommentCard {
padding: 1 0 1 1;
margin: 0 0 1 0;
}
&:focus-within {
border-left: $card-border $accent 50%;
border-bottom: $card-border $accent 50%;
background: $boost 50%;
color: $text 80%;
}
&:focus {
border-left: $card-border $accent;
border-bottom: $card-border $accent;
background: $boost;
color: $text;
}
&.deleted {
color: $error 50%;
text-style: italic;
border: dashed $error 20%;
padding: 0;
Label {
text-align: center;
}
}
Label {
width: 1fr;
padding-right: 1;
}
/* These two should be combined. https://github.com/Textualize/textual/issues/3969 */
&.flagged Label {
color: $text-disabled;
text-style: italic;
}
&.dead Label {
color: $text-disabled;
text-style: italic;
}
.byline {
margin-top: 1;
text-align: right;
color: $text-muted;
text-style: italic;
}
}
"""
BINDINGS = [
Binding("enter", "gndn"),
Binding("s", "next(1)", "Next Sibling"),
Binding("S", "next(-1)", "Prev Sibling", key_display="Sh+S"),
Binding("p", "goto_parent", "Parent"),
Binding("r", "goto_root", "Go Root"),
Binding("u", "view_user", "View User"),
Binding("v", "view_online", "View on HN"),
]
def __init__(
| """Provides a card for displaying a HackerNews comment."""
##############################################################################
# Python imports.
##############################################################################
# Textual imports.
##############################################################################
# Humanize imports.
##############################################################################
# Local imports.
##############################################################################
class CommentCard(Vertical, can_focus=True):
"""Widget that displays a comment."""
DEFAULT_CSS = """
$card-border: heavy;
CommentCard {
border-left: $card-border $primary;
border-bottom: $card-border $primary;
padding: 1 0 1 1;
margin: 0 1 1 1;
height: auto;
color: $text 70%;
CommentCard {
padding: 1 0 1 1;
margin: 0 0 1 0;
}
&:focus-within {
border-left: $card-border $accent 50%;
border-bottom: $card-border $accent 50%;
background: $boost 50%;
color: $text 80%;
}
&:focus {
border-left: $card-border $accent;
border-bottom: $card-border $accent;
background: $boost;
color: $text;
}
&.deleted {
color: $error 50%;
text-style: italic;
border: dashed $error 20%;
padding: 0;
Label {
text-align: center;
}
}
Label {
width: 1fr;
padding-right: 1;
}
/* These two should be combined. https://github.com/Textualize/textual/issues/3969 */
&.flagged Label {
color: $text-disabled;
text-style: italic;
}
&.dead Label {
color: $text-disabled;
text-style: italic;
}
.byline {
margin-top: 1;
text-align: right;
color: $text-muted;
text-style: italic;
}
}
"""
BINDINGS = [
Binding("enter", "gndn"),
Binding("s", "next(1)", "Next Sibling"),
Binding("S", "next(-1)", "Prev Sibling", key_display="Sh+S"),
Binding("p", "goto_parent", "Parent"),
Binding("r", "goto_root", "Go Root"),
Binding("u", "view_user", "View User"),
Binding("v", "view_online", "View on HN"),
]
def __init__( | self, client: HN, parent_item: Article | Comment, comment: Comment | 2 | 2023-12-25 14:06:07+00:00 | 8k |
wwxu21/CUT | finetune_unlikelihood.py | [
{
"identifier": "LlamaForCausalLM",
"path": "modeling_llama_unlikelihood.py",
"snippet": "class LlamaForCausalLM(LlamaPreTrainedModel):\n _tied_weights_keys = [\"lm_head.weight\"]\n\n def __init__(self, config, threshold):\n super().__init__(config)\n self.model = LlamaModel(config)\... | import os
import sys
import json
import fire
import torch
import transformers
import numpy as np
import random
from typing import List
from torch.utils.data import DataLoader
from datasets import load_dataset, concatenate_datasets, Dataset
from transformers import TrainerCallback, TrainingArguments, TrainerState, TrainerControl
from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
from peft import (
LoraConfig,
prepare_model_for_int8_training,
set_peft_model_state_dict,
MODEL_TYPE_TO_PEFT_MODEL_MAPPING,
PeftModel,
)
from peft.utils import _prepare_prompt_learning_config
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.utils import PaddingStrategy
from transformers import LlamaTokenizer, LlamaConfig
from modeling_llama_unlikelihood import LlamaForCausalLM, PeftModelForCausalLM
from prompter import Prompter
from typing import Optional, Union, Any
from dataclasses import dataclass | 6,444 | if return_tensors is None:
return_tensors = self.return_tensors
labels = [feature["labels"] for feature in features] if "labels" in features[0].keys() else None
labels_neg = [feature["labels_neg"] for feature in features] if "labels_neg" in features[0].keys() else None
# We have to pad the labels before calling `tokenizer.pad` as this method won't pad them and needs them of the
# same length to return tensors.
if labels is not None:
max_label_length = max(len(l) for l in labels)
if labels_neg is not None:
max_label_length_neg = max(len(l) for l in labels_neg)
max_label_length = max(max_label_length, max_label_length_neg)
if self.pad_to_multiple_of is not None:
max_label_length = (
(max_label_length + self.pad_to_multiple_of - 1)
// self.pad_to_multiple_of
* self.pad_to_multiple_of
)
# self.tokenizer.padding_side = "left"
padding_side = self.tokenizer.padding_side
for feature in features:
feature['weight_like'] = [feature['weight_like']]
feature['weight_unlike'] = [feature['weight_unlike']]
remainder = [self.label_pad_token_id] * (max_label_length - len(feature["labels"]))
remainder_length = max_label_length - len(feature["labels_neg"])
remainder_label = [self.label_pad_token_id] * remainder_length
remainder_ids = [self.tokenizer.pad_token_id] * remainder_length
remainder_mask = [0] * remainder_length
if isinstance(feature["labels"], list):
feature["labels"] = (
feature["labels"] + remainder if padding_side == "right" else remainder + feature["labels"]
)
feature["labels_neg"] = (
feature["labels_neg"] + remainder_label if padding_side == "right" else remainder_label + feature["labels_neg"]
)
feature["input_ids_neg"] = (
feature["input_ids_neg"] + remainder_ids if padding_side == "right" else remainder_ids + feature["input_ids_neg"]
)
feature["attention_mask_neg"] = (
feature["attention_mask_neg"] + remainder_mask if padding_side == "right" else remainder_mask + feature["attention_mask_neg"]
)
elif padding_side == "right":
feature["labels"] = np.concatenate([feature["labels"], remainder]).astype(np.int64)
feature["labels_neg"] = np.concatenate([feature["labels_neg"], remainder_label]).astype(np.int64)
feature["input_ids_neg"] = np.concatenate([feature["input_ids_neg"], remainder_ids]).astype(np.int64)
feature["attention_mask_neg"] = np.concatenate([feature["attention_mask_neg"], remainder_mask]).astype(np.int64)
else:
feature["labels"] = np.concatenate([remainder, feature["labels"]]).astype(np.int64)
feature["labels_neg"] = np.concatenate([remainder_label, feature["labels_neg"]]).astype(np.int64)
feature["input_ids_neg"] = np.concatenate([remainder_ids, feature["input_ids_neg"]]).astype(np.int64)
feature["attention_mask_neg"] = np.concatenate([remainder_mask, feature["attention_mask_neg"]]).astype(np.int64)
features = self.tokenizer.pad(
features,
padding=self.padding,
max_length=max_label_length,
pad_to_multiple_of=self.pad_to_multiple_of,
return_tensors=return_tensors,
)
# prepare decoder_input_ids
if (
labels is not None
and self.model is not None
and hasattr(self.model, "prepare_decoder_input_ids_from_labels")
):
decoder_input_ids = self.model.prepare_decoder_input_ids_from_labels(labels=features["labels"])
features["decoder_input_ids"] = decoder_input_ids
return features
class SavePeftModelCallback(TrainerCallback):
def on_save(
self,
args: TrainingArguments,
state: TrainerState,
control: TrainerControl,
**kwargs,
):
checkpoint_folder = os.path.join(args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{state.global_step}")
kwargs["model"].save_pretrained(checkpoint_folder)
pytorch_model_path = os.path.join(checkpoint_folder, "pytorch_model.bin")
torch.save({}, pytorch_model_path)
return control
class LoadBestPeftModelCallback(TrainerCallback):
def on_train_end(
self,
args: TrainingArguments,
state: TrainerState,
control: TrainerControl,
**kwargs,
):
print(f"Loading best peft model from {state.best_model_checkpoint} (score: {state.best_metric}).")
best_model_path = os.path.join(state.best_model_checkpoint, "adapter_model.bin")
adapters_weights = torch.load(best_model_path)
model = kwargs["model"]
set_peft_model_state_dict(model, adapters_weights)
return control
def get_peft_model(model, peft_config, adapter_name: str = "default"):
"""
Returns a Peft model object from a model and a config.
Args:
model ([`transformers.PreTrainedModel`]): Model to be wrapped.
peft_config ([`PeftConfig`]): Configuration object containing the parameters of the Peft model.
"""
model_config = getattr(model, "config", {"model_type": "custom"})
if hasattr(model_config, "to_dict"):
model_config = model_config.to_dict()
peft_config.base_model_name_or_path = model.__dict__.get("name_or_path", None)
if peft_config.task_type not in MODEL_TYPE_TO_PEFT_MODEL_MAPPING.keys() and not peft_config.is_prompt_learning:
return PeftModel(model, peft_config, adapter_name=adapter_name)
if peft_config.is_prompt_learning:
peft_config = _prepare_prompt_learning_config(peft_config, model_config)
| seed = 42
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
@dataclass
class MyDataCollator:
"""
Data collator that will dynamically pad the inputs received, as well as the labels.
Args:
tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):
The tokenizer used for encoding the data.
model ([`PreTrainedModel`]):
The model that is being trained. If set and has the *prepare_decoder_input_ids_from_labels*, use it to
prepare the *decoder_input_ids*
This is useful when using *label_smoothing* to avoid calculating loss twice.
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
among:
- `True` or `'longest'` (default): Pad to the longest sequence in the batch (or no padding if only a single
sequence is provided).
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
acceptable input length for the model if that argument is not provided.
- `False` or `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths).
max_length (`int`, *optional*):
Maximum length of the returned list and optionally padding length (see above).
pad_to_multiple_of (`int`, *optional*):
If set will pad the sequence to a multiple of the provided value.
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
7.5 (Volta).
label_pad_token_id (`int`, *optional*, defaults to -100):
The id to use when padding the labels (-100 will be automatically ignored by PyTorch loss functions).
return_tensors (`str`):
The type of Tensor to return. Allowable values are "np", "pt" and "tf".
"""
tokenizer: PreTrainedTokenizerBase
model: Optional[Any] = None
padding: Union[bool, str, PaddingStrategy] = True
max_length: Optional[int] = None
pad_to_multiple_of: Optional[int] = None
label_pad_token_id: int = -100
return_tensors: str = "pt"
def __call__(self, features, return_tensors=None):
if return_tensors is None:
return_tensors = self.return_tensors
labels = [feature["labels"] for feature in features] if "labels" in features[0].keys() else None
labels_neg = [feature["labels_neg"] for feature in features] if "labels_neg" in features[0].keys() else None
# We have to pad the labels before calling `tokenizer.pad` as this method won't pad them and needs them of the
# same length to return tensors.
if labels is not None:
max_label_length = max(len(l) for l in labels)
if labels_neg is not None:
max_label_length_neg = max(len(l) for l in labels_neg)
max_label_length = max(max_label_length, max_label_length_neg)
if self.pad_to_multiple_of is not None:
max_label_length = (
(max_label_length + self.pad_to_multiple_of - 1)
// self.pad_to_multiple_of
* self.pad_to_multiple_of
)
# self.tokenizer.padding_side = "left"
padding_side = self.tokenizer.padding_side
for feature in features:
feature['weight_like'] = [feature['weight_like']]
feature['weight_unlike'] = [feature['weight_unlike']]
remainder = [self.label_pad_token_id] * (max_label_length - len(feature["labels"]))
remainder_length = max_label_length - len(feature["labels_neg"])
remainder_label = [self.label_pad_token_id] * remainder_length
remainder_ids = [self.tokenizer.pad_token_id] * remainder_length
remainder_mask = [0] * remainder_length
if isinstance(feature["labels"], list):
feature["labels"] = (
feature["labels"] + remainder if padding_side == "right" else remainder + feature["labels"]
)
feature["labels_neg"] = (
feature["labels_neg"] + remainder_label if padding_side == "right" else remainder_label + feature["labels_neg"]
)
feature["input_ids_neg"] = (
feature["input_ids_neg"] + remainder_ids if padding_side == "right" else remainder_ids + feature["input_ids_neg"]
)
feature["attention_mask_neg"] = (
feature["attention_mask_neg"] + remainder_mask if padding_side == "right" else remainder_mask + feature["attention_mask_neg"]
)
elif padding_side == "right":
feature["labels"] = np.concatenate([feature["labels"], remainder]).astype(np.int64)
feature["labels_neg"] = np.concatenate([feature["labels_neg"], remainder_label]).astype(np.int64)
feature["input_ids_neg"] = np.concatenate([feature["input_ids_neg"], remainder_ids]).astype(np.int64)
feature["attention_mask_neg"] = np.concatenate([feature["attention_mask_neg"], remainder_mask]).astype(np.int64)
else:
feature["labels"] = np.concatenate([remainder, feature["labels"]]).astype(np.int64)
feature["labels_neg"] = np.concatenate([remainder_label, feature["labels_neg"]]).astype(np.int64)
feature["input_ids_neg"] = np.concatenate([remainder_ids, feature["input_ids_neg"]]).astype(np.int64)
feature["attention_mask_neg"] = np.concatenate([remainder_mask, feature["attention_mask_neg"]]).astype(np.int64)
features = self.tokenizer.pad(
features,
padding=self.padding,
max_length=max_label_length,
pad_to_multiple_of=self.pad_to_multiple_of,
return_tensors=return_tensors,
)
# prepare decoder_input_ids
if (
labels is not None
and self.model is not None
and hasattr(self.model, "prepare_decoder_input_ids_from_labels")
):
decoder_input_ids = self.model.prepare_decoder_input_ids_from_labels(labels=features["labels"])
features["decoder_input_ids"] = decoder_input_ids
return features
class SavePeftModelCallback(TrainerCallback):
def on_save(
self,
args: TrainingArguments,
state: TrainerState,
control: TrainerControl,
**kwargs,
):
checkpoint_folder = os.path.join(args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{state.global_step}")
kwargs["model"].save_pretrained(checkpoint_folder)
pytorch_model_path = os.path.join(checkpoint_folder, "pytorch_model.bin")
torch.save({}, pytorch_model_path)
return control
class LoadBestPeftModelCallback(TrainerCallback):
def on_train_end(
self,
args: TrainingArguments,
state: TrainerState,
control: TrainerControl,
**kwargs,
):
print(f"Loading best peft model from {state.best_model_checkpoint} (score: {state.best_metric}).")
best_model_path = os.path.join(state.best_model_checkpoint, "adapter_model.bin")
adapters_weights = torch.load(best_model_path)
model = kwargs["model"]
set_peft_model_state_dict(model, adapters_weights)
return control
def get_peft_model(model, peft_config, adapter_name: str = "default"):
"""
Returns a Peft model object from a model and a config.
Args:
model ([`transformers.PreTrainedModel`]): Model to be wrapped.
peft_config ([`PeftConfig`]): Configuration object containing the parameters of the Peft model.
"""
model_config = getattr(model, "config", {"model_type": "custom"})
if hasattr(model_config, "to_dict"):
model_config = model_config.to_dict()
peft_config.base_model_name_or_path = model.__dict__.get("name_or_path", None)
if peft_config.task_type not in MODEL_TYPE_TO_PEFT_MODEL_MAPPING.keys() and not peft_config.is_prompt_learning:
return PeftModel(model, peft_config, adapter_name=adapter_name)
if peft_config.is_prompt_learning:
peft_config = _prepare_prompt_learning_config(peft_config, model_config) | return PeftModelForCausalLM(model, peft_config, adapter_name=adapter_name) | 1 | 2023-12-22 07:32:19+00:00 | 8k |
Maximilian-Winter/llama-cpp-agent | src/llama_cpp_agent/structured_output_agent.py | [
{
"identifier": "LlamaCppAgent",
"path": "src/llama_cpp_agent/llm_agent.py",
"snippet": "class LlamaCppAgent:\n \"\"\"\n A base agent that can be used for chat, structured output and function calling. Is used as part of all other agents.\n \"\"\"\n def __init__(self, model: Union[Llama, Llam... | import json
from copy import copy
from typing import Type, Callable, Union
from llama_cpp import Llama, LlamaGrammar
from pydantic import BaseModel
from .llm_agent import LlamaCppAgent, StreamingResponse
from .llm_prompt_template import PromptTemplate
from .llm_settings import LlamaLLMGenerationSettings, LlamaLLMSettings
from .output_parser import extract_object_from_response
from .messages_formatter import MessagesFormatterType, MessagesFormatter
from .gbnf_grammar_generator.gbnf_grammar_from_pydantic_models import generate_gbnf_grammar_and_documentation | 5,194 |
class StructuredOutputAgent:
"""
An agent that creates structured output based on pydantic models from an unstructured text.
"""
def __init__(self, llama_llm: Union[Llama, LlamaLLMSettings],
llama_generation_settings: LlamaLLMGenerationSettings = LlamaLLMGenerationSettings(),
messages_formatter_type: MessagesFormatterType = MessagesFormatterType.CHATML,
custom_messages_formatter: MessagesFormatter = None,
streaming_callback: Callable[[StreamingResponse], None] = None,
debug_output: bool = False):
self.llama_generation_settings = llama_generation_settings
self.grammar_cache = {}
self.system_prompt_template = PromptTemplate.from_string(
"You are an advanced AI agent. You are tasked to assist the user by creating structured output in JSON format.\n\n{documentation}")
self.creation_prompt_template = PromptTemplate.from_string(
"Create an JSON response based on the following input.\n\nInput:\n\n{user_input}")
|
class StructuredOutputAgent:
"""
An agent that creates structured output based on pydantic models from an unstructured text.
"""
def __init__(self, llama_llm: Union[Llama, LlamaLLMSettings],
llama_generation_settings: LlamaLLMGenerationSettings = LlamaLLMGenerationSettings(),
messages_formatter_type: MessagesFormatterType = MessagesFormatterType.CHATML,
custom_messages_formatter: MessagesFormatter = None,
streaming_callback: Callable[[StreamingResponse], None] = None,
debug_output: bool = False):
self.llama_generation_settings = llama_generation_settings
self.grammar_cache = {}
self.system_prompt_template = PromptTemplate.from_string(
"You are an advanced AI agent. You are tasked to assist the user by creating structured output in JSON format.\n\n{documentation}")
self.creation_prompt_template = PromptTemplate.from_string(
"Create an JSON response based on the following input.\n\nInput:\n\n{user_input}")
| self.llama_cpp_agent = LlamaCppAgent(llama_llm, debug_output=debug_output, | 0 | 2023-12-29 16:54:39+00:00 | 8k |
usail-hkust/LLMTSCS | utils/oneline.py | [
{
"identifier": "DIC_AGENTS",
"path": "utils/config.py",
"snippet": "DIC_AGENTS = {\n \"Random\": RandomAgent,\n \"Fixedtime\": FixedtimeAgent,\n \"MaxPressure\": MaxPressureAgent,\n \"EfficientMaxPressure\": EfficientMaxPressureAgent,\n \"AdvancedMaxPressure\": AdvancedMaxPressureAgent,\... | from .config import DIC_AGENTS
from .my_utils import merge, get_state, get_state_detail, eight_phase_list, dump_json
from copy import deepcopy
from .cityflow_env import CityFlowEnv
from .pipeline import path_check, copy_cityflow_file, copy_conf_file
from tqdm import tqdm
import os
import time
import numpy as np
import wandb
import threading | 6,467 |
class OneLine:
def __init__(self, dic_agent_conf, dic_traffic_env_conf, dic_path, roadnet, trafficflow):
self.dic_agent_conf = dic_agent_conf
self.dic_traffic_env_conf = dic_traffic_env_conf
self.dic_path = dic_path
self.agents = []
self.env = None
self.roadnet = roadnet
self.trafficflow = trafficflow
self.models = []
self.initialize()
def initialize(self):
path_check(self.dic_path)
copy_conf_file(self.dic_path, self.dic_agent_conf, self.dic_traffic_env_conf)
copy_cityflow_file(self.dic_path, self.dic_traffic_env_conf)
self.env = CityFlowEnv(
path_to_log=self.dic_path["PATH_TO_WORK_DIRECTORY"],
path_to_work_directory=self.dic_path["PATH_TO_WORK_DIRECTORY"],
dic_traffic_env_conf=self.dic_traffic_env_conf,
dic_path=self.dic_path
)
self.env.reset()
agent_name = self.dic_traffic_env_conf["MODEL_NAME"]
for i in range(self.dic_traffic_env_conf['NUM_INTERSECTIONS']):
if "ChatGPT" in agent_name:
|
class OneLine:
def __init__(self, dic_agent_conf, dic_traffic_env_conf, dic_path, roadnet, trafficflow):
self.dic_agent_conf = dic_agent_conf
self.dic_traffic_env_conf = dic_traffic_env_conf
self.dic_path = dic_path
self.agents = []
self.env = None
self.roadnet = roadnet
self.trafficflow = trafficflow
self.models = []
self.initialize()
def initialize(self):
path_check(self.dic_path)
copy_conf_file(self.dic_path, self.dic_agent_conf, self.dic_traffic_env_conf)
copy_cityflow_file(self.dic_path, self.dic_traffic_env_conf)
self.env = CityFlowEnv(
path_to_log=self.dic_path["PATH_TO_WORK_DIRECTORY"],
path_to_work_directory=self.dic_path["PATH_TO_WORK_DIRECTORY"],
dic_traffic_env_conf=self.dic_traffic_env_conf,
dic_path=self.dic_path
)
self.env.reset()
agent_name = self.dic_traffic_env_conf["MODEL_NAME"]
for i in range(self.dic_traffic_env_conf['NUM_INTERSECTIONS']):
if "ChatGPT" in agent_name: | agent = DIC_AGENTS[agent_name.split("-")[0]]( | 0 | 2023-12-26 08:31:47+00:00 | 8k |
alipay/private_llm | demo/edge_device.py | [
{
"identifier": "PLLlamaConfig",
"path": "demo/model.py",
"snippet": "class PLLlamaConfig(LlamaConfig):\n def __init__(\n self,\n vocab_size=32000,\n hidden_size=4096,\n intermediate_size=11008,\n num_hidden_layers=32,\n num_attention_heads=32,\n num_k... | from demo.model import PLLlamaConfig, LlamaForDevice
from pl_lib import CommProfiler
from transformers import AutoTokenizer
from pl_lib import init_tcp_b
import torch
import logging
import argparse | 3,636 |
parser = argparse.ArgumentParser()
parser.add_argument(
"weight_path",
default=None,
help="path to device model weight",
)
parser.add_argument(
"llama_path",
default=None,
help="root dir of huggingface llama model, should contain weight files and config",
)
parser.add_argument(
"--ip",
default="127.0.0.1",
help="socket ip of cloud",
)
parser.add_argument(
"--port",
default=12345,
help="socket port of cloud",
)
parser.add_argument(
"--device",
default="cpu",
help="device of model",
)
parser.add_argument(
"--debug",
default=False,
)
args = parser.parse_args()
log_format = "%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s"
logging.basicConfig(
level=logging.DEBUG if args.debug else logging.INFO, format=log_format
)
if __name__ == "__main__":
mock_small = True
load_weights = False
logging.info("start connecting...")
s = init_tcp_b(args.ip, args.port)
config = PLLlamaConfig.from_pretrained(args.llama_path)
config.rcd = 128
config.rdc = 128
tokenizer = AutoTokenizer.from_pretrained(args.llama_path)
logging.info("Initializing Model")
|
parser = argparse.ArgumentParser()
parser.add_argument(
"weight_path",
default=None,
help="path to device model weight",
)
parser.add_argument(
"llama_path",
default=None,
help="root dir of huggingface llama model, should contain weight files and config",
)
parser.add_argument(
"--ip",
default="127.0.0.1",
help="socket ip of cloud",
)
parser.add_argument(
"--port",
default=12345,
help="socket port of cloud",
)
parser.add_argument(
"--device",
default="cpu",
help="device of model",
)
parser.add_argument(
"--debug",
default=False,
)
args = parser.parse_args()
log_format = "%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s"
logging.basicConfig(
level=logging.DEBUG if args.debug else logging.INFO, format=log_format
)
if __name__ == "__main__":
mock_small = True
load_weights = False
logging.info("start connecting...")
s = init_tcp_b(args.ip, args.port)
config = PLLlamaConfig.from_pretrained(args.llama_path)
config.rcd = 128
config.rdc = 128
tokenizer = AutoTokenizer.from_pretrained(args.llama_path)
logging.info("Initializing Model") | model = LlamaForDevice(config) | 1 | 2023-12-25 06:28:04+00:00 | 8k |
kokiez/solana-sniper | jupiter/jupiter.py | [
{
"identifier": "sendWebhook",
"path": "webhook.py",
"snippet": "def sendWebhook(title_type_info, description):\r\n global error_webhook\r\n global webhook_url\r\n title = \"\"\r\n title_type = title_type_info.split(\"|\")\r\n if title_type[0] == \"msg\":\r\n title = title_type[1]\... | from webhook import sendWebhook
from alreadyBought import soldToken
from jupiter.sell_swap import sell
from birdeye import get_price, getSymbol
from monitor_price_strategy import limit_order, trailing_stop_loss_func, take_profit_and_trailing_stop
import time, sys, os
| 5,525 | # from Wallet_Info import get_wallet_Info
def jupiter_swap(config, ctx, payer, desired_token_address, txB, execution_time, limit_order_sell_Bool, take_profit_ratio, trailing_stop_Bool, trailing_stop_ratio, Limit_and_Trailing_Stop_Bool, bought_token_price):
token_symbol, SOl_Symbol = getSymbol(desired_token_address)
txB = str(txB)
# saveTokenTime()
sell_NOW = True
if limit_order_sell_Bool:
sell_NOW = limit_order(bought_token_price,desired_token_address, take_profit_ratio, execution_time, txB)
elif trailing_stop_Bool:
sell_NOW = trailing_stop_loss_func(bought_token_price,desired_token_address, trailing_stop_ratio, execution_time, txB)
elif Limit_and_Trailing_Stop_Bool:
sell_NOW = take_profit_and_trailing_stop(bought_token_price,desired_token_address, trailing_stop_ratio, take_profit_ratio, execution_time, txB)
# Call Sell Method - returns transaction hash (txS= tx for sell)
if sell_NOW == False:
bought_token_curr_price = get_price(desired_token_address)
start_time = time.time()
txS = sell(ctx, payer, desired_token_address, config)
end_time = time.time()
execution_time = end_time - start_time
print(f"Total Sell Execution time: {execution_time} seconds")
if str(txS) != 'failed':
txS = str(txS)
print("-" * 79)
print(f"| {'Sold Price':<15} | {'Tx Sell':<40} |")
print("-" * 79)
print(f"| {bought_token_curr_price:.12f} | {txS:<40} |")
sendWebhook(f"msg_s|SELL INFO {token_symbol}",f"Token Address: {desired_token_address}\nSold at: {bought_token_curr_price:.12f}\nTotal Sell Execution time: {execution_time} seconds\nSell TXN: https://solscan.io/tx/{txS}\n------------------- END -------------------")
print("-" * 79)
| # from Wallet_Info import get_wallet_Info
def jupiter_swap(config, ctx, payer, desired_token_address, txB, execution_time, limit_order_sell_Bool, take_profit_ratio, trailing_stop_Bool, trailing_stop_ratio, Limit_and_Trailing_Stop_Bool, bought_token_price):
token_symbol, SOl_Symbol = getSymbol(desired_token_address)
txB = str(txB)
# saveTokenTime()
sell_NOW = True
if limit_order_sell_Bool:
sell_NOW = limit_order(bought_token_price,desired_token_address, take_profit_ratio, execution_time, txB)
elif trailing_stop_Bool:
sell_NOW = trailing_stop_loss_func(bought_token_price,desired_token_address, trailing_stop_ratio, execution_time, txB)
elif Limit_and_Trailing_Stop_Bool:
sell_NOW = take_profit_and_trailing_stop(bought_token_price,desired_token_address, trailing_stop_ratio, take_profit_ratio, execution_time, txB)
# Call Sell Method - returns transaction hash (txS= tx for sell)
if sell_NOW == False:
bought_token_curr_price = get_price(desired_token_address)
start_time = time.time()
txS = sell(ctx, payer, desired_token_address, config)
end_time = time.time()
execution_time = end_time - start_time
print(f"Total Sell Execution time: {execution_time} seconds")
if str(txS) != 'failed':
txS = str(txS)
print("-" * 79)
print(f"| {'Sold Price':<15} | {'Tx Sell':<40} |")
print("-" * 79)
print(f"| {bought_token_curr_price:.12f} | {txS:<40} |")
sendWebhook(f"msg_s|SELL INFO {token_symbol}",f"Token Address: {desired_token_address}\nSold at: {bought_token_curr_price:.12f}\nTotal Sell Execution time: {execution_time} seconds\nSell TXN: https://solscan.io/tx/{txS}\n------------------- END -------------------")
print("-" * 79)
| soldToken(desired_token_address) | 1 | 2023-12-26 11:40:05+00:00 | 8k |
kraina-ai/quackosm | quackosm/pbf_file_reader.py | [
{
"identifier": "FEATURES_INDEX",
"path": "quackosm/_constants.py",
"snippet": "FEATURES_INDEX = \"feature_id\""
},
{
"identifier": "GEOMETRY_COLUMN",
"path": "quackosm/_constants.py",
"snippet": "GEOMETRY_COLUMN = \"geometry\""
},
{
"identifier": "WGS84_CRS",
"path": "quacko... | import hashlib
import json
import shutil
import tempfile
import warnings
import duckdb
import geoarrow.pyarrow as ga
import geopandas as gpd
import psutil
import pyarrow as pa
import pyarrow.parquet as pq
import shapely.wkt as wktlib
import quackosm._geo_arrow_io as io
from collections.abc import Iterable
from math import floor
from pathlib import Path
from typing import Any, Literal, NamedTuple, Optional, Union, cast
from shapely.geometry.base import BaseGeometry
from quackosm._constants import FEATURES_INDEX, GEOMETRY_COLUMN, WGS84_CRS
from quackosm._osm_tags_filters import GroupedOsmTagsFilter, OsmTagsFilter, merge_osm_tags_filter
from quackosm._osm_way_polygon_features import OsmWayPolygonConfig, parse_dict_to_config_object
from quackosm._rich_progress import ( # type: ignore[attr-defined]
TaskProgressBar,
TaskProgressSpinner,
)
from quackosm._typing import is_expected_type | 4,390 | )
self._delete_directories(
tmp_dir_name,
[
"nodes_valid_with_tags",
],
)
filtered_ways_with_linestrings = self._get_filtered_ways_with_linestrings(
osm_parquet_files=converted_osm_parquet_files,
ways_refs_with_nodes_structs=ways_refs_with_nodes_structs,
tmp_dir_name=tmp_dir_name,
)
required_ways_with_linestrings = self._get_required_ways_with_linestrings(
osm_parquet_files=converted_osm_parquet_files,
ways_refs_with_nodes_structs=ways_refs_with_nodes_structs,
tmp_dir_name=tmp_dir_name,
)
self._delete_directories(
tmp_dir_name,
[
"ways_required_grouped",
"ways_required_ids",
"ways_with_unnested_nodes_refs",
"ways_refs_with_nodes_structs",
"required_ways_ids_grouped",
"required_ways_grouped",
"required_ways_tmp",
"filtered_ways_ids_grouped",
"filtered_ways_grouped",
"filtered_ways_tmp",
],
)
filtered_ways_with_proper_geometry = self._get_filtered_ways_with_proper_geometry(
converted_osm_parquet_files, filtered_ways_with_linestrings, tmp_dir_name
)
self._delete_directories(
tmp_dir_name,
[
"ways_prepared_ids",
"ways_filtered_ids",
"ways_all_with_tags",
"filtered_ways_with_linestrings",
],
)
filtered_relations_with_geometry = self._get_filtered_relations_with_geometry(
converted_osm_parquet_files, required_ways_with_linestrings, tmp_dir_name
)
self._delete_directories(
tmp_dir_name,
[
"relations_all_with_tags",
"relations_with_unnested_way_refs",
"relations_filtered_ids",
"required_ways_with_linestrings",
"valid_relation_parts",
"relation_inner_parts",
"relation_outer_parts",
"relation_outer_parts_with_holes",
"relation_outer_parts_without_holes",
],
)
self._concatenate_results_to_geoparquet(
PbfFileReader.ParsedOSMFeatures(
nodes=filtered_nodes_with_geometry,
ways=filtered_ways_with_proper_geometry,
relations=filtered_relations_with_geometry,
),
tmp_dir_name=tmp_dir_name,
save_file_path=result_file_path,
explode_tags=explode_tags,
)
return result_file_path
def _generate_geoparquet_result_file_path(
self,
pbf_file_path: Union[str, Path],
explode_tags: bool,
filter_osm_ids: list[str],
) -> Path:
pbf_file_name = Path(pbf_file_path).name.removesuffix(".osm.pbf")
osm_filter_tags_hash_part = "nofilter"
if self.tags_filter is not None:
h = hashlib.new("sha256")
h.update(json.dumps(self.tags_filter).encode())
osm_filter_tags_hash_part = h.hexdigest()
clipping_geometry_hash_part = "noclip"
if self.geometry_filter is not None:
h = hashlib.new("sha256")
h.update(wktlib.dumps(self.geometry_filter).encode())
clipping_geometry_hash_part = h.hexdigest()
exploded_tags_part = "exploded" if explode_tags else "compact"
filter_osm_ids_hash_part = ""
if filter_osm_ids:
h = hashlib.new("sha256")
h.update(json.dumps(sorted(set(filter_osm_ids))).encode())
filter_osm_ids_hash_part = f"_{h.hexdigest()}"
result_file_name = (
f"{pbf_file_name}_{osm_filter_tags_hash_part}"
f"_{clipping_geometry_hash_part}_{exploded_tags_part}{filter_osm_ids_hash_part}.geoparquet"
)
return Path(self.working_directory) / result_file_name
def _prefilter_elements_ids(
self, elements: "duckdb.DuckDBPyRelation", tmp_dir_name: str, filter_osm_ids: list[str]
) -> ConvertedOSMParquetFiles:
sql_filter = self._generate_osm_tags_sql_filter()
filtered_tags_clause = self._generate_filtered_tags_clause()
is_intersecting = self.geometry_filter is not None
| """
PBF File Reader.
This module contains a reader capable of parsing a PBF file into a GeoDataFrame.
"""
__all__ = [
"PbfFileReader",
]
class PbfFileReader:
"""
PbfFileReader.
PBF(Protocolbuffer Binary Format)[1] file reader is a dedicated `*.osm.pbf` files reader
class based on DuckDB[2] and its spatial extension[3].
Handler can filter out OSM features based on tags filter and geometry filter
to limit the result.
References:
1. https://wiki.openstreetmap.org/wiki/PBF_Format
2. https://duckdb.org/
3. https://github.com/duckdb/duckdb_spatial
"""
class ConvertedOSMParquetFiles(NamedTuple):
"""List of parquet files read from the `*.osm.pbf` file."""
nodes_valid_with_tags: "duckdb.DuckDBPyRelation"
nodes_filtered_ids: "duckdb.DuckDBPyRelation"
ways_all_with_tags: "duckdb.DuckDBPyRelation"
ways_with_unnested_nodes_refs: "duckdb.DuckDBPyRelation"
ways_required_ids: "duckdb.DuckDBPyRelation"
ways_filtered_ids: "duckdb.DuckDBPyRelation"
relations_all_with_tags: "duckdb.DuckDBPyRelation"
relations_with_unnested_way_refs: "duckdb.DuckDBPyRelation"
relations_filtered_ids: "duckdb.DuckDBPyRelation"
class ParsedOSMFeatures(NamedTuple):
"""Final list of parsed features from the `*.osm.pbf` file."""
nodes: "duckdb.DuckDBPyRelation"
ways: "duckdb.DuckDBPyRelation"
relations: "duckdb.DuckDBPyRelation"
def __init__(
self,
tags_filter: Optional[Union[OsmTagsFilter, GroupedOsmTagsFilter]] = None,
geometry_filter: Optional[BaseGeometry] = None,
working_directory: Union[str, Path] = "files",
osm_way_polygon_features_config: Optional[
Union[OsmWayPolygonConfig, dict[str, Any]]
] = None,
) -> None:
"""
Initialize PbfFileReader.
Args:
tags_filter (Union[OsmTagsFilter, GroupedOsmTagsFilter], optional): A dictionary
specifying which tags to download.
The keys should be OSM tags (e.g. `building`, `amenity`).
The values should either be `True` for retrieving all objects with the tag,
string for retrieving a single tag-value pair
or list of strings for retrieving all values specified in the list.
`tags={'leisure': 'park}` would return parks from the area.
`tags={'leisure': 'park, 'amenity': True, 'shop': ['bakery', 'bicycle']}`
would return parks, all amenity types, bakeries and bicycle shops.
If `None`, handler will allow all of the tags to be parsed. Defaults to `None`.
geometry_filter (BaseGeometry, optional): Region which can be used to filter only
intersecting OSM objects. Defaults to `None`.
working_directory (Union[str, Path], optional): Directory where to save
the parsed `*.parquet` files. Defaults to "files".
osm_way_polygon_features_config (Union[OsmWayPolygonConfig, dict[str, Any]], optional):
Config used to determine which closed way features are polygons.
Modifications to this config left are left for experienced OSM users.
Defaults to predefined "osm_way_polygon_features.json".
"""
self.tags_filter = tags_filter
self.merged_tags_filter = merge_osm_tags_filter(tags_filter) if tags_filter else None
self.geometry_filter = geometry_filter
self.working_directory = Path(working_directory)
self.working_directory.mkdir(parents=True, exist_ok=True)
self.connection: duckdb.DuckDBPyConnection = None
self.rows_per_bucket = 1_000_000
memory = psutil.virtual_memory()
# If less than 8 / 16 GB total memory, reduce number of rows per group
if memory.total < (8 * (1024**3)):
self.rows_per_bucket = 100_000
elif memory.total < (16 * (1024**3)):
self.rows_per_bucket = 500_000
if osm_way_polygon_features_config is None:
# Config based on two sources + manual OSM wiki check
# 1. https://github.com/tyrasd/osm-polygon-features/blob/v0.9.2/polygon-features.json
# 2. https://github.com/ideditor/id-area-keys/blob/v5.0.1/areaKeys.json
osm_way_polygon_features_config = json.loads(
(Path(__file__).parent / "osm_way_polygon_features.json").read_text()
)
self.osm_way_polygon_features_config: OsmWayPolygonConfig = (
osm_way_polygon_features_config
if isinstance(osm_way_polygon_features_config, OsmWayPolygonConfig)
else parse_dict_to_config_object(osm_way_polygon_features_config)
)
def get_features_gdf(
self,
file_paths: Union[str, Path, Iterable[Union[str, Path]]],
explode_tags: Optional[bool] = None,
ignore_cache: bool = False,
filter_osm_ids: Optional[list[str]] = None,
) -> gpd.GeoDataFrame:
"""
Get features GeoDataFrame from a list of PBF files.
Function parses multiple PBF files and returns a single GeoDataFrame with parsed
OSM objects.
Args:
file_paths (Union[str, Path, Iterable[Union[str, Path]]]):
Path or list of paths of `*.osm.pbf` files to be parsed.
explode_tags (bool, optional): Whether to split tags into columns based on OSM tag keys.
If `None`, will be set based on `tags_filter` parameter.
If no tags filter is provided, then `explode_tags` will set to `False`,
if there is tags filter it will set to `True`. Defaults to `None`.
ignore_cache: (bool, optional): Whether to ignore precalculated geoparquet files or not.
Defaults to False.
filter_osm_ids: (list[str], optional): List of OSM features ids to read from the file.
Have to be in the form of 'node/<id>', 'way/<id>' or 'relation/<id>'.
Defaults to an empty list.
Returns:
gpd.GeoDataFrame: GeoDataFrame with OSM features.
"""
if isinstance(file_paths, (str, Path)):
file_paths = [file_paths]
if filter_osm_ids is None:
filter_osm_ids = []
if explode_tags is None:
explode_tags = self.tags_filter is not None
parsed_geoparquet_files = []
for file_path in file_paths:
parsed_geoparquet_file = self.convert_pbf_to_gpq(
file_path,
explode_tags=explode_tags,
ignore_cache=ignore_cache,
filter_osm_ids=filter_osm_ids,
)
parsed_geoparquet_files.append(parsed_geoparquet_file)
parquet_tables = [
io.read_geoparquet_table(parsed_parquet_file) # type: ignore
for parsed_parquet_file in parsed_geoparquet_files
]
joined_parquet_table: pa.Table = pa.concat_tables(parquet_tables)
gdf_parquet = gpd.GeoDataFrame(
data=joined_parquet_table.drop(GEOMETRY_COLUMN).to_pandas(maps_as_pydicts="strict"),
geometry=ga.to_geopandas(joined_parquet_table.column(GEOMETRY_COLUMN)),
).set_index(FEATURES_INDEX)
return gdf_parquet
def convert_pbf_to_gpq(
self,
pbf_path: Union[str, Path],
result_file_path: Optional[Union[str, Path]] = None,
explode_tags: Optional[bool] = None,
ignore_cache: bool = False,
filter_osm_ids: Optional[list[str]] = None,
) -> Path:
"""
Convert PBF file to GeoParquet file.
Args:
pbf_path (Union[str, Path]): Pbf file to be parsed to GeoParquet.
result_file_path (Union[str, Path], optional): Where to save
the geoparquet file. If not provided, will be generated based on hashes
from provided tags filter and geometry filter. Defaults to `None`.
explode_tags (bool, optional): Whether to split tags into columns based on OSM tag keys.
If `None`, will be set based on `tags_filter` parameter.
If no tags filter is provided, then `explode_tags` will set to `False`,
if there is tags filter it will set to `True`. Defaults to `None`.
ignore_cache (bool, optional): Whether to ignore precalculated geoparquet files or not.
Defaults to False.
filter_osm_ids: (list[str], optional): List of OSM features ids to read from the file.
Have to be in the form of 'node/<id>', 'way/<id>' or 'relation/<id>'.
Defaults to an empty list.
Returns:
Path: Path to the generated GeoParquet file.
"""
if filter_osm_ids is None:
filter_osm_ids = []
if explode_tags is None:
explode_tags = self.tags_filter is not None
with tempfile.TemporaryDirectory(dir=self.working_directory.resolve()) as tmp_dir_name:
try:
self._set_up_duckdb_connection(tmp_dir_name)
result_file_path = result_file_path or self._generate_geoparquet_result_file_path(
pbf_path,
filter_osm_ids=filter_osm_ids,
explode_tags=explode_tags,
)
parsed_geoparquet_file = self._parse_pbf_file(
pbf_path=pbf_path,
tmp_dir_name=tmp_dir_name,
result_file_path=Path(result_file_path),
filter_osm_ids=filter_osm_ids,
explode_tags=explode_tags,
ignore_cache=ignore_cache,
)
return parsed_geoparquet_file
finally:
if self.connection is not None:
self.connection.close()
self.connection = None
def _set_up_duckdb_connection(self, tmp_dir_name: str) -> None:
self.connection = duckdb.connect(
database=str(Path(tmp_dir_name) / "db.duckdb"),
config=dict(preserve_insertion_order=False),
)
for extension_name in ("parquet", "spatial"):
self.connection.install_extension(extension_name)
self.connection.load_extension(extension_name)
self.connection.sql("""
CREATE OR REPLACE MACRO linestring_to_linestring_wkt(ls) AS
'LINESTRING (' || array_to_string([pt.x || ' ' || pt.y for pt in ls], ', ') || ')';
""")
self.connection.sql("""
CREATE OR REPLACE MACRO linestring_to_polygon_wkt(ls) AS
'POLYGON ((' || array_to_string([pt.x || ' ' || pt.y for pt in ls], ', ') || '))';
""")
def _parse_pbf_file(
self,
pbf_path: Union[str, Path],
tmp_dir_name: str,
result_file_path: Path,
filter_osm_ids: list[str],
explode_tags: bool = True,
ignore_cache: bool = False,
) -> Path:
if not result_file_path.exists() or ignore_cache:
elements = self.connection.sql(f"SELECT * FROM ST_READOSM('{Path(pbf_path)}');")
converted_osm_parquet_files = self._prefilter_elements_ids(
elements, tmp_dir_name, filter_osm_ids
)
self._delete_directories(
tmp_dir_name,
[
"nodes_filtered_non_distinct_ids",
"nodes_prepared_ids",
"ways_valid_ids",
"ways_filtered_non_distinct_ids",
"relations_valid_ids",
"relations_ids",
],
)
filtered_nodes_with_geometry = self._get_filtered_nodes_with_geometry(
converted_osm_parquet_files, tmp_dir_name
)
self._delete_directories(tmp_dir_name, "nodes_filtered_ids")
ways_refs_with_nodes_structs = self._get_ways_refs_with_nodes_structs(
converted_osm_parquet_files, tmp_dir_name
)
self._delete_directories(
tmp_dir_name,
[
"nodes_valid_with_tags",
],
)
filtered_ways_with_linestrings = self._get_filtered_ways_with_linestrings(
osm_parquet_files=converted_osm_parquet_files,
ways_refs_with_nodes_structs=ways_refs_with_nodes_structs,
tmp_dir_name=tmp_dir_name,
)
required_ways_with_linestrings = self._get_required_ways_with_linestrings(
osm_parquet_files=converted_osm_parquet_files,
ways_refs_with_nodes_structs=ways_refs_with_nodes_structs,
tmp_dir_name=tmp_dir_name,
)
self._delete_directories(
tmp_dir_name,
[
"ways_required_grouped",
"ways_required_ids",
"ways_with_unnested_nodes_refs",
"ways_refs_with_nodes_structs",
"required_ways_ids_grouped",
"required_ways_grouped",
"required_ways_tmp",
"filtered_ways_ids_grouped",
"filtered_ways_grouped",
"filtered_ways_tmp",
],
)
filtered_ways_with_proper_geometry = self._get_filtered_ways_with_proper_geometry(
converted_osm_parquet_files, filtered_ways_with_linestrings, tmp_dir_name
)
self._delete_directories(
tmp_dir_name,
[
"ways_prepared_ids",
"ways_filtered_ids",
"ways_all_with_tags",
"filtered_ways_with_linestrings",
],
)
filtered_relations_with_geometry = self._get_filtered_relations_with_geometry(
converted_osm_parquet_files, required_ways_with_linestrings, tmp_dir_name
)
self._delete_directories(
tmp_dir_name,
[
"relations_all_with_tags",
"relations_with_unnested_way_refs",
"relations_filtered_ids",
"required_ways_with_linestrings",
"valid_relation_parts",
"relation_inner_parts",
"relation_outer_parts",
"relation_outer_parts_with_holes",
"relation_outer_parts_without_holes",
],
)
self._concatenate_results_to_geoparquet(
PbfFileReader.ParsedOSMFeatures(
nodes=filtered_nodes_with_geometry,
ways=filtered_ways_with_proper_geometry,
relations=filtered_relations_with_geometry,
),
tmp_dir_name=tmp_dir_name,
save_file_path=result_file_path,
explode_tags=explode_tags,
)
return result_file_path
def _generate_geoparquet_result_file_path(
self,
pbf_file_path: Union[str, Path],
explode_tags: bool,
filter_osm_ids: list[str],
) -> Path:
pbf_file_name = Path(pbf_file_path).name.removesuffix(".osm.pbf")
osm_filter_tags_hash_part = "nofilter"
if self.tags_filter is not None:
h = hashlib.new("sha256")
h.update(json.dumps(self.tags_filter).encode())
osm_filter_tags_hash_part = h.hexdigest()
clipping_geometry_hash_part = "noclip"
if self.geometry_filter is not None:
h = hashlib.new("sha256")
h.update(wktlib.dumps(self.geometry_filter).encode())
clipping_geometry_hash_part = h.hexdigest()
exploded_tags_part = "exploded" if explode_tags else "compact"
filter_osm_ids_hash_part = ""
if filter_osm_ids:
h = hashlib.new("sha256")
h.update(json.dumps(sorted(set(filter_osm_ids))).encode())
filter_osm_ids_hash_part = f"_{h.hexdigest()}"
result_file_name = (
f"{pbf_file_name}_{osm_filter_tags_hash_part}"
f"_{clipping_geometry_hash_part}_{exploded_tags_part}{filter_osm_ids_hash_part}.geoparquet"
)
return Path(self.working_directory) / result_file_name
def _prefilter_elements_ids(
self, elements: "duckdb.DuckDBPyRelation", tmp_dir_name: str, filter_osm_ids: list[str]
) -> ConvertedOSMParquetFiles:
sql_filter = self._generate_osm_tags_sql_filter()
filtered_tags_clause = self._generate_filtered_tags_clause()
is_intersecting = self.geometry_filter is not None
| with TaskProgressSpinner("Reading nodes", "1"): | 7 | 2023-12-28 11:26:41+00:00 | 8k |
KyanChen/TTP | mmseg/models/decode_heads/vpd_depth_head.py | [
{
"identifier": "MODELS",
"path": "mmseg/registry/registry.py",
"snippet": "MODELS = Registry('model', parent=MMENGINE_MODELS, locations=['mmseg.models'])"
},
{
"identifier": "SampleList",
"path": "mmseg/utils/typing_utils.py",
"snippet": ""
},
{
"identifier": "build_loss",
"... | from typing import Dict, List, Optional, Sequence, Union
from mmcv.cnn import build_conv_layer, build_norm_layer, build_upsample_layer
from mmengine.model import BaseModule
from torch import Tensor
from mmseg.registry import MODELS
from mmseg.utils import SampleList
from ..builder import build_loss
from ..utils import resize
from .decode_head import BaseDecodeHead
import torch
import torch.nn as nn
import torch.nn.functional as F | 5,536 | fmap_border (Union[int, Sequence[int]]): Feature map border for
cropping. Defaults to 0.
align_corners (bool): Flag for align_corners in interpolation.
Defaults to False.
loss_decode (dict): Configurations for the loss function. Defaults to
dict(type='SiLogLoss').
init_cfg (dict): Initialization configurations. Defaults to
dict(type='TruncNormal', std=0.02, layer=['Conv2d', 'Linear']).
"""
num_classes = 1
out_channels = 1
input_transform = None
def __init__(
self,
max_depth: float = 10.0,
in_channels: Sequence[int] = [320, 640, 1280, 1280],
embed_dim: int = 192,
feature_dim: int = 1536,
num_deconv_layers: int = 3,
num_deconv_filters: Sequence[int] = (32, 32, 32),
fmap_border: Union[int, Sequence[int]] = 0,
align_corners: bool = False,
loss_decode: dict = dict(type='SiLogLoss'),
init_cfg=dict(
type='TruncNormal', std=0.02, layer=['Conv2d', 'Linear']),
):
super(BaseDecodeHead, self).__init__(init_cfg=init_cfg)
# initialize parameters
self.in_channels = in_channels
self.max_depth = max_depth
self.align_corners = align_corners
# feature map border
if isinstance(fmap_border, int):
fmap_border = (fmap_border, fmap_border)
self.fmap_border = fmap_border
# define network layers
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels[0], in_channels[0], 3, stride=2, padding=1),
nn.GroupNorm(16, in_channels[0]),
nn.ReLU(),
nn.Conv2d(in_channels[0], in_channels[0], 3, stride=2, padding=1),
)
self.conv2 = nn.Conv2d(
in_channels[1], in_channels[1], 3, stride=2, padding=1)
self.conv_aggregation = nn.Sequential(
nn.Conv2d(sum(in_channels), feature_dim, 1),
nn.GroupNorm(16, feature_dim),
nn.ReLU(),
)
self.decoder = VPDDepthDecoder(
in_channels=embed_dim * 8,
out_channels=embed_dim,
num_deconv_layers=num_deconv_layers,
num_deconv_filters=num_deconv_filters)
self.depth_pred_layer = nn.Sequential(
nn.Conv2d(
embed_dim, embed_dim, kernel_size=3, stride=1, padding=1),
nn.ReLU(inplace=False),
nn.Conv2d(embed_dim, 1, kernel_size=3, stride=1, padding=1))
# build loss
if isinstance(loss_decode, dict):
self.loss_decode = build_loss(loss_decode)
elif isinstance(loss_decode, (list, tuple)):
self.loss_decode = nn.ModuleList()
for loss in loss_decode:
self.loss_decode.append(build_loss(loss))
else:
raise TypeError(f'loss_decode must be a dict or sequence of dict,\
but got {type(loss_decode)}')
def _stack_batch_gt(self, batch_data_samples: SampleList) -> Tensor:
gt_depth_maps = [
data_sample.gt_depth_map.data for data_sample in batch_data_samples
]
return torch.stack(gt_depth_maps, dim=0)
def forward(self, x):
x = [
x[0], x[1],
torch.cat([x[2], F.interpolate(x[3], scale_factor=2)], dim=1)
]
x = torch.cat([self.conv1(x[0]), self.conv2(x[1]), x[2]], dim=1)
x = self.conv_aggregation(x)
x = x[:, :, :x.size(2) - self.fmap_border[0], :x.size(3) -
self.fmap_border[1]].contiguous()
x = self.decoder(x)
out = self.depth_pred_layer(x)
depth = torch.sigmoid(out) * self.max_depth
return depth
def loss_by_feat(self, pred_depth_map: Tensor,
batch_data_samples: SampleList) -> dict:
"""Compute depth estimation loss.
Args:
pred_depth_map (Tensor): The output from decode head forward
function.
batch_data_samples (List[:obj:`SegDataSample`]): The seg
data samples. It usually includes information such
as `metainfo` and `gt_dpeth_map`.
Returns:
dict[str, Tensor]: a dictionary of loss components
"""
gt_depth_map = self._stack_batch_gt(batch_data_samples)
loss = dict()
| # Copyright (c) OpenMMLab. All rights reserved.
class VPDDepthDecoder(BaseModule):
"""VPD Depth Decoder class.
Args:
in_channels (int): Number of input channels.
out_channels (int): Number of output channels.
num_deconv_layers (int): Number of deconvolution layers.
num_deconv_filters (List[int]): List of output channels for
deconvolution layers.
init_cfg (Optional[Union[Dict, List[Dict]]], optional): Configuration
for weight initialization. Defaults to Normal for Conv2d and
ConvTranspose2d layers.
"""
def __init__(self,
in_channels: int,
out_channels: int,
num_deconv_layers: int,
num_deconv_filters: List[int],
init_cfg: Optional[Union[Dict, List[Dict]]] = dict(
type='Normal',
std=0.001,
layer=['Conv2d', 'ConvTranspose2d'])):
super().__init__(init_cfg=init_cfg)
self.in_channels = in_channels
self.deconv_layers = self._make_deconv_layer(
num_deconv_layers,
num_deconv_filters,
)
conv_layers = []
conv_layers.append(
build_conv_layer(
dict(type='Conv2d'),
in_channels=num_deconv_filters[-1],
out_channels=out_channels,
kernel_size=3,
stride=1,
padding=1))
conv_layers.append(build_norm_layer(dict(type='BN'), out_channels)[1])
conv_layers.append(nn.ReLU(inplace=True))
self.conv_layers = nn.Sequential(*conv_layers)
self.up_sample = nn.Upsample(
scale_factor=2, mode='bilinear', align_corners=False)
def forward(self, x):
"""Forward pass through the decoder network."""
out = self.deconv_layers(x)
out = self.conv_layers(out)
out = self.up_sample(out)
out = self.up_sample(out)
return out
def _make_deconv_layer(self, num_layers, num_deconv_filters):
"""Make deconv layers."""
layers = []
in_channels = self.in_channels
for i in range(num_layers):
num_channels = num_deconv_filters[i]
layers.append(
build_upsample_layer(
dict(type='deconv'),
in_channels=in_channels,
out_channels=num_channels,
kernel_size=2,
stride=2,
padding=0,
output_padding=0,
bias=False))
layers.append(nn.BatchNorm2d(num_channels))
layers.append(nn.ReLU(inplace=True))
in_channels = num_channels
return nn.Sequential(*layers)
@MODELS.register_module()
class VPDDepthHead(BaseDecodeHead):
"""Depth Prediction Head for VPD.
.. _`VPD`: https://arxiv.org/abs/2303.02153
Args:
max_depth (float): Maximum depth value. Defaults to 10.0.
in_channels (Sequence[int]): Number of input channels for each
convolutional layer.
embed_dim (int): Dimension of embedding. Defaults to 192.
feature_dim (int): Dimension of aggregated feature. Defaults to 1536.
num_deconv_layers (int): Number of deconvolution layers in the
decoder. Defaults to 3.
num_deconv_filters (Sequence[int]): Number of filters for each deconv
layer. Defaults to (32, 32, 32).
fmap_border (Union[int, Sequence[int]]): Feature map border for
cropping. Defaults to 0.
align_corners (bool): Flag for align_corners in interpolation.
Defaults to False.
loss_decode (dict): Configurations for the loss function. Defaults to
dict(type='SiLogLoss').
init_cfg (dict): Initialization configurations. Defaults to
dict(type='TruncNormal', std=0.02, layer=['Conv2d', 'Linear']).
"""
num_classes = 1
out_channels = 1
input_transform = None
def __init__(
self,
max_depth: float = 10.0,
in_channels: Sequence[int] = [320, 640, 1280, 1280],
embed_dim: int = 192,
feature_dim: int = 1536,
num_deconv_layers: int = 3,
num_deconv_filters: Sequence[int] = (32, 32, 32),
fmap_border: Union[int, Sequence[int]] = 0,
align_corners: bool = False,
loss_decode: dict = dict(type='SiLogLoss'),
init_cfg=dict(
type='TruncNormal', std=0.02, layer=['Conv2d', 'Linear']),
):
super(BaseDecodeHead, self).__init__(init_cfg=init_cfg)
# initialize parameters
self.in_channels = in_channels
self.max_depth = max_depth
self.align_corners = align_corners
# feature map border
if isinstance(fmap_border, int):
fmap_border = (fmap_border, fmap_border)
self.fmap_border = fmap_border
# define network layers
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels[0], in_channels[0], 3, stride=2, padding=1),
nn.GroupNorm(16, in_channels[0]),
nn.ReLU(),
nn.Conv2d(in_channels[0], in_channels[0], 3, stride=2, padding=1),
)
self.conv2 = nn.Conv2d(
in_channels[1], in_channels[1], 3, stride=2, padding=1)
self.conv_aggregation = nn.Sequential(
nn.Conv2d(sum(in_channels), feature_dim, 1),
nn.GroupNorm(16, feature_dim),
nn.ReLU(),
)
self.decoder = VPDDepthDecoder(
in_channels=embed_dim * 8,
out_channels=embed_dim,
num_deconv_layers=num_deconv_layers,
num_deconv_filters=num_deconv_filters)
self.depth_pred_layer = nn.Sequential(
nn.Conv2d(
embed_dim, embed_dim, kernel_size=3, stride=1, padding=1),
nn.ReLU(inplace=False),
nn.Conv2d(embed_dim, 1, kernel_size=3, stride=1, padding=1))
# build loss
if isinstance(loss_decode, dict):
self.loss_decode = build_loss(loss_decode)
elif isinstance(loss_decode, (list, tuple)):
self.loss_decode = nn.ModuleList()
for loss in loss_decode:
self.loss_decode.append(build_loss(loss))
else:
raise TypeError(f'loss_decode must be a dict or sequence of dict,\
but got {type(loss_decode)}')
def _stack_batch_gt(self, batch_data_samples: SampleList) -> Tensor:
gt_depth_maps = [
data_sample.gt_depth_map.data for data_sample in batch_data_samples
]
return torch.stack(gt_depth_maps, dim=0)
def forward(self, x):
x = [
x[0], x[1],
torch.cat([x[2], F.interpolate(x[3], scale_factor=2)], dim=1)
]
x = torch.cat([self.conv1(x[0]), self.conv2(x[1]), x[2]], dim=1)
x = self.conv_aggregation(x)
x = x[:, :, :x.size(2) - self.fmap_border[0], :x.size(3) -
self.fmap_border[1]].contiguous()
x = self.decoder(x)
out = self.depth_pred_layer(x)
depth = torch.sigmoid(out) * self.max_depth
return depth
def loss_by_feat(self, pred_depth_map: Tensor,
batch_data_samples: SampleList) -> dict:
"""Compute depth estimation loss.
Args:
pred_depth_map (Tensor): The output from decode head forward
function.
batch_data_samples (List[:obj:`SegDataSample`]): The seg
data samples. It usually includes information such
as `metainfo` and `gt_dpeth_map`.
Returns:
dict[str, Tensor]: a dictionary of loss components
"""
gt_depth_map = self._stack_batch_gt(batch_data_samples)
loss = dict() | pred_depth_map = resize( | 3 | 2023-12-23 08:36:47+00:00 | 8k |
jiayev/GPT4V-Image-Captioner | utils/models/cogvlm_model.py | [
{
"identifier": "LlamaVisionExpertFCMixin",
"path": "utils/models/mixin.py",
"snippet": "class LlamaVisionExpertFCMixin(BaseMixin):\r\n def __init__(self, in_features, hidden_features, num_layers=32, num_vision_layers=0, vision_layer_range=None,\r\n params_dtype=torch.float, device=to... | from sat.model.official.llama_model import LLaMAModel
from sat.model.base_model import BaseMixin
from .mixin import LlamaVisionExpertFCMixin, LlamaVisionExpertAttnMixin
from sat.resources.urls import MODEL_URLS
from .eva_clip_model import EVA2CLIPModel
from copy import deepcopy
from sat.model.finetune import PTuningV2Mixin
from sat.model.finetune.lora2 import LoraMixin
import json
import torch
import torch.nn as nn
import argparse
| 4,408 |
MODEL_URLS["cogvlm-base-224"] = "r2://cogvlm-base-224.zip"
MODEL_URLS["cogvlm-base-490"] = "r2://cogvlm-base-490.zip"
MODEL_URLS["cogvlm-chat-v1.1"] = "r2://cogvlm-chat-v1.1.zip"
MODEL_URLS["cogvlm-grounding-base"] = "r2://cogvlm-grounding-base.zip"
MODEL_URLS["cogvlm-grounding-generalist-v1.1"] = "r2://cogvlm-grounding-generalist-v1.1.zip"
class GLU(nn.Module):
def __init__(self, args, in_features):
super().__init__()
self.linear_proj = nn.Linear(in_features, args.hidden_size, bias=False)
self.norm1 = nn.LayerNorm(args.hidden_size)
self.act1 = nn.GELU()
self.act2 = nn.functional.silu
self.dense_h_to_4h = nn.Linear(args.hidden_size, args.inner_hidden_size, bias=False)
self.gate_proj = nn.Linear(args.hidden_size, args.inner_hidden_size, bias=False)
self.dense_4h_to_h = nn.Linear(args.inner_hidden_size, args.hidden_size, bias=False)
def forward(self, x):
x = self.linear_proj(x)
x = self.act1(self.norm1(x))
x = self.act2(self.gate_proj(x)) * self.dense_h_to_4h(x)
x = self.dense_4h_to_h(x)
return x
def override_dist_dtype_device_args(args, b={}):
if args.mode == 'inference':
minimal_args = argparse.Namespace(
world_size=args.world_size,
rank=args.rank,
local_rank=args.local_rank,
skip_init=args.skip_init,
use_gpu_initialization=args.use_gpu_initialization,
deepspeed=args.deepspeed,
bf16=args.bf16,
fp16=args.fp16,
mode=args.mode,
device=args.device
)
else:
minimal_args = argparse.Namespace(
world_size=args.world_size,
rank=args.rank,
local_rank=args.local_rank,
skip_init=args.skip_init,
use_gpu_initialization=args.use_gpu_initialization,
deepspeed=args.deepspeed,
bf16=args.bf16,
fp16=args.fp16,
mode=args.mode,
checkpoint_activations=args.checkpoint_activations if not hasattr(args, 'vit_checkpoint_activations') else args.vit_checkpoint_activations,
checkpoint_num_layers=args.checkpoint_num_layers,
device=args.device,
hidden_dropout=0.,
attention_dropout=0.,
)
if hasattr(args, 'model_parallel_size'):
b['model_parallel_size'] = args.model_parallel_size
return argparse.Namespace(**deepcopy(b), **vars(minimal_args))
class ImageMixin(BaseMixin):
def __init__(self, args):
super().__init__()
vit_args = override_dist_dtype_device_args(args, args.eva_args)
self.vit_model = EVA2CLIPModel(EVA2CLIPModel.get_args(**vars(vit_args)))
self.in_features = 1792
self.linear_proj = GLU(args, self.in_features)
self.image_length = args.image_length
self.boi = nn.Parameter(torch.zeros(1, 1, args.hidden_size))
self.eoi = nn.Parameter(torch.zeros(1, 1, args.hidden_size))
def word_embedding_forward(self, input_ids, output_cross_layer, **kw_args):
vision_inputs = {}
for k in kw_args:
if k.startswith('vision_') and k != 'vision_expert_mask':
vision_inputs[k[7:]] = kw_args[k]
if input_ids.shape[1] == 1 or not vision_inputs:
return self.transformer.word_embeddings(input_ids)
image_emb = self.vit_model(**vision_inputs)[0]
image_emb = self.linear_proj(image_emb)
image_embed_mask = kw_args['image_embed_mask']
word_embedding = self.transformer.word_embeddings(input_ids).clone()
word_embedding[image_embed_mask.bool()] = torch.cat([self.boi.repeat(len(image_emb), 1, 1), image_emb, self.eoi.repeat(len(image_emb), 1, 1)], dim=1).reshape(-1, image_emb.shape[-1])
return word_embedding.contiguous()
class CogVLMModel(LLaMAModel):
def __init__(self, args, transformer=None, parallel_output=True, **kwargs):
super().__init__(args, transformer=transformer, parallel_output=parallel_output, **kwargs)
self.image_length = args.image_length
self.add_mixin("eva", ImageMixin(args))
self.del_mixin("mlp")
|
MODEL_URLS["cogvlm-base-224"] = "r2://cogvlm-base-224.zip"
MODEL_URLS["cogvlm-base-490"] = "r2://cogvlm-base-490.zip"
MODEL_URLS["cogvlm-chat-v1.1"] = "r2://cogvlm-chat-v1.1.zip"
MODEL_URLS["cogvlm-grounding-base"] = "r2://cogvlm-grounding-base.zip"
MODEL_URLS["cogvlm-grounding-generalist-v1.1"] = "r2://cogvlm-grounding-generalist-v1.1.zip"
class GLU(nn.Module):
def __init__(self, args, in_features):
super().__init__()
self.linear_proj = nn.Linear(in_features, args.hidden_size, bias=False)
self.norm1 = nn.LayerNorm(args.hidden_size)
self.act1 = nn.GELU()
self.act2 = nn.functional.silu
self.dense_h_to_4h = nn.Linear(args.hidden_size, args.inner_hidden_size, bias=False)
self.gate_proj = nn.Linear(args.hidden_size, args.inner_hidden_size, bias=False)
self.dense_4h_to_h = nn.Linear(args.inner_hidden_size, args.hidden_size, bias=False)
def forward(self, x):
x = self.linear_proj(x)
x = self.act1(self.norm1(x))
x = self.act2(self.gate_proj(x)) * self.dense_h_to_4h(x)
x = self.dense_4h_to_h(x)
return x
def override_dist_dtype_device_args(args, b={}):
if args.mode == 'inference':
minimal_args = argparse.Namespace(
world_size=args.world_size,
rank=args.rank,
local_rank=args.local_rank,
skip_init=args.skip_init,
use_gpu_initialization=args.use_gpu_initialization,
deepspeed=args.deepspeed,
bf16=args.bf16,
fp16=args.fp16,
mode=args.mode,
device=args.device
)
else:
minimal_args = argparse.Namespace(
world_size=args.world_size,
rank=args.rank,
local_rank=args.local_rank,
skip_init=args.skip_init,
use_gpu_initialization=args.use_gpu_initialization,
deepspeed=args.deepspeed,
bf16=args.bf16,
fp16=args.fp16,
mode=args.mode,
checkpoint_activations=args.checkpoint_activations if not hasattr(args, 'vit_checkpoint_activations') else args.vit_checkpoint_activations,
checkpoint_num_layers=args.checkpoint_num_layers,
device=args.device,
hidden_dropout=0.,
attention_dropout=0.,
)
if hasattr(args, 'model_parallel_size'):
b['model_parallel_size'] = args.model_parallel_size
return argparse.Namespace(**deepcopy(b), **vars(minimal_args))
class ImageMixin(BaseMixin):
def __init__(self, args):
super().__init__()
vit_args = override_dist_dtype_device_args(args, args.eva_args)
self.vit_model = EVA2CLIPModel(EVA2CLIPModel.get_args(**vars(vit_args)))
self.in_features = 1792
self.linear_proj = GLU(args, self.in_features)
self.image_length = args.image_length
self.boi = nn.Parameter(torch.zeros(1, 1, args.hidden_size))
self.eoi = nn.Parameter(torch.zeros(1, 1, args.hidden_size))
def word_embedding_forward(self, input_ids, output_cross_layer, **kw_args):
vision_inputs = {}
for k in kw_args:
if k.startswith('vision_') and k != 'vision_expert_mask':
vision_inputs[k[7:]] = kw_args[k]
if input_ids.shape[1] == 1 or not vision_inputs:
return self.transformer.word_embeddings(input_ids)
image_emb = self.vit_model(**vision_inputs)[0]
image_emb = self.linear_proj(image_emb)
image_embed_mask = kw_args['image_embed_mask']
word_embedding = self.transformer.word_embeddings(input_ids).clone()
word_embedding[image_embed_mask.bool()] = torch.cat([self.boi.repeat(len(image_emb), 1, 1), image_emb, self.eoi.repeat(len(image_emb), 1, 1)], dim=1).reshape(-1, image_emb.shape[-1])
return word_embedding.contiguous()
class CogVLMModel(LLaMAModel):
def __init__(self, args, transformer=None, parallel_output=True, **kwargs):
super().__init__(args, transformer=transformer, parallel_output=parallel_output, **kwargs)
self.image_length = args.image_length
self.add_mixin("eva", ImageMixin(args))
self.del_mixin("mlp")
| self.add_mixin("mlp", LlamaVisionExpertFCMixin(args.hidden_size, args.inner_hidden_size, args.num_layers, 32))
| 0 | 2023-12-27 08:12:37+00:00 | 8k |
Emperor-WS/PyEmber | ember/nn/modules/pool.py | [
{
"identifier": "Module",
"path": "ember/nn/modules/module.py",
"snippet": "class Module(ABC):\n \"\"\"\n Base class for all neural network modules.\n\n Attributes:\n training: Indicates whether the module is in training mode.\n _modules: Dictionary to store sub-modules.\n ... | import numpy as np
import ember
from .module import Module
from ._utils import im2col, col2im | 4,336 |
class MaxPool2d(Module):
"""
2D Max Pooling Layer for Convolutional Neural Networks.
This layer downsamples the spatial dimensions of the input tensor by taking the maximum value
within a defined pool size, with optional stride and padding.
Args:
- kernel_size (int or tuple of int): Size of the pooling window. If int, the window is square.
- stride (int): Step size to slide the pooling window.
- pad (int): Zero-padding added to the input.
Methods:
- forward(input_data): Performs the forward pass for max pooling.
- backward(dout): Computes the backward pass for max pooling.
"""
def __init__(self, kernel_size, stride=1, pad=0):
"""
Constructor for MaxPool2d.
Args:
- kernel_size (int or tuple of int): Size of the pooling window. If int, the window is square.
- stride (int): Step size to slide the pooling window.
- pad (int): Zero-padding added to the input.
"""
super().__init__()
# If pool_size is an int, convert it to a tuple (square window)
if isinstance(kernel_size, int):
kernel_size = (kernel_size, kernel_size)
self.kernel_size = kernel_size
self.stride = stride
self.pad = pad
def forward(self, input_data):
"""
Performs the forward pass for max pooling.
Args:
- input_data: The input tensor.
Returns:
- out: The output tensor after max pooling.
"""
# Extract dimensions
N, C, input_height, input_width = input_data.shape
# Calculate output dimensions
out_h = int(1 + (input_height - self.kernel_size[0]) / self.stride)
out_w = int(1 + (input_width - self.kernel_size[1]) / self.stride)
# Apply im2col to input_data
col = im2col(input_data, *self.kernel_size, self.stride, self.pad)
col = col.reshape(-1, np.product(self.kernel_size))
# Find the indices of the maximum values and the maximum values
argmax = ember.argmax(col, axis=1)
out = ember.max(col, axis=1)
out = out.reshape(N, out_h + 2 * self.pad, out_w + 2 *
self.pad, C).transpose(0, 3, 1, 2)
# Cache input_data and argmax for backward pass
self._cache['x'] = input_data
self._cache['argmax'] = argmax
return out
def backward(self, dout):
"""
Computes the backward pass for max pooling.
Args:
- dout: The gradient of the output.
Returns:
- dx: The gradient with respect to the input.
"""
# Transpose dout for easier manipulation
dout = dout.transpose(0, 2, 3, 1)
# Calculate pool size
pool_size = np.product(self.kernel_size)
# Create a matrix with zeros and assign gradients to max positions
dmax = ember.zeros((dout.size, pool_size))
x = self._cache['x']
argmax = self._cache['argmax']
dmax[ember.arange(argmax.size), argmax.flatten()] = dout.flatten()
dmax = dmax.reshape(dout.shape + (pool_size,))
# Reshape dmax for col2im
dcol = dmax.reshape(dmax.shape[0] * dmax.shape[1] * dmax.shape[2], -1)
# Apply col2im to get the gradient with respect to the input
|
class MaxPool2d(Module):
"""
2D Max Pooling Layer for Convolutional Neural Networks.
This layer downsamples the spatial dimensions of the input tensor by taking the maximum value
within a defined pool size, with optional stride and padding.
Args:
- kernel_size (int or tuple of int): Size of the pooling window. If int, the window is square.
- stride (int): Step size to slide the pooling window.
- pad (int): Zero-padding added to the input.
Methods:
- forward(input_data): Performs the forward pass for max pooling.
- backward(dout): Computes the backward pass for max pooling.
"""
def __init__(self, kernel_size, stride=1, pad=0):
"""
Constructor for MaxPool2d.
Args:
- kernel_size (int or tuple of int): Size of the pooling window. If int, the window is square.
- stride (int): Step size to slide the pooling window.
- pad (int): Zero-padding added to the input.
"""
super().__init__()
# If pool_size is an int, convert it to a tuple (square window)
if isinstance(kernel_size, int):
kernel_size = (kernel_size, kernel_size)
self.kernel_size = kernel_size
self.stride = stride
self.pad = pad
def forward(self, input_data):
"""
Performs the forward pass for max pooling.
Args:
- input_data: The input tensor.
Returns:
- out: The output tensor after max pooling.
"""
# Extract dimensions
N, C, input_height, input_width = input_data.shape
# Calculate output dimensions
out_h = int(1 + (input_height - self.kernel_size[0]) / self.stride)
out_w = int(1 + (input_width - self.kernel_size[1]) / self.stride)
# Apply im2col to input_data
col = im2col(input_data, *self.kernel_size, self.stride, self.pad)
col = col.reshape(-1, np.product(self.kernel_size))
# Find the indices of the maximum values and the maximum values
argmax = ember.argmax(col, axis=1)
out = ember.max(col, axis=1)
out = out.reshape(N, out_h + 2 * self.pad, out_w + 2 *
self.pad, C).transpose(0, 3, 1, 2)
# Cache input_data and argmax for backward pass
self._cache['x'] = input_data
self._cache['argmax'] = argmax
return out
def backward(self, dout):
"""
Computes the backward pass for max pooling.
Args:
- dout: The gradient of the output.
Returns:
- dx: The gradient with respect to the input.
"""
# Transpose dout for easier manipulation
dout = dout.transpose(0, 2, 3, 1)
# Calculate pool size
pool_size = np.product(self.kernel_size)
# Create a matrix with zeros and assign gradients to max positions
dmax = ember.zeros((dout.size, pool_size))
x = self._cache['x']
argmax = self._cache['argmax']
dmax[ember.arange(argmax.size), argmax.flatten()] = dout.flatten()
dmax = dmax.reshape(dout.shape + (pool_size,))
# Reshape dmax for col2im
dcol = dmax.reshape(dmax.shape[0] * dmax.shape[1] * dmax.shape[2], -1)
# Apply col2im to get the gradient with respect to the input | dx = col2im(dcol, x.shape, * | 2 | 2023-12-23 23:11:58+00:00 | 8k |
Hassi34/iot-device-identification | src/stage_04_training_and_eval.py | [
{
"identifier": "read_yaml",
"path": "src/utils/common.py",
"snippet": "def read_yaml(path_to_yaml: str) -> dict:\n with open(path_to_yaml) as yaml_file:\n content = yaml.safe_load(yaml_file)\n return content"
},
{
"identifier": "get_logger",
"path": "src/utils/sys_logging.py",
... | import argparse
import time
import torch.nn.functional as F
import io
import pytorch_lightning as pl
import mlflow
import onnxruntime as rt
import numpy as np
import torch
import sys
from src.utils.common import read_yaml
from src.utils.sys_logging import get_logger
from src.utils import MLFlowManager
from src.utils.data_ops import load_np_arr_from_gz
from sklearn.metrics import classification_report
from src.lightning_pckg.model import NN
from src.utils.ml import plot_confusion_matrix
from src.lightning_pckg.training_callbacks import PrintingCallback
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning.callbacks import EarlyStopping
from pathlib import Path
from pytorch_lightning.accelerators import CPUAccelerator
from src.utils.ml import (
IoT_Dataset,
get_default_device,
to_device,
DeviceDataLoader,
)
from torch.utils.data import DataLoader
from datetime import datetime | 4,775 | Path(ONNX_TRAINED_MODEL_FILE_PATH).parent.absolute().mkdir(
parents=True, exist_ok=True
)
model.to_onnx(
file_path=ONNX_TRAINED_MODEL_FILE_PATH,
input_sample=sample_input,
input_names=["input"],
verbose=True,
)
logger.info(f'ONNX model has been exported to "{ONNX_TRAINED_MODEL_FILE_PATH}"')
logger.info("Starting model validation...")
onnx_sess = rt.InferenceSession(
ONNX_TRAINED_MODEL_FILE_PATH,
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
input_name = onnx_sess.get_inputs()[0].name
input_data = {input_name: sample_input.cpu().numpy()}
output = onnx_sess.run(None, input_data)
if isinstance(output[0], np.ndarray) and len(output[0][0]) == num_classes:
logger.info("Model validation passed")
else:
logger.critical("Model validation failed!")
sys.exit(1)
logger.info("Exporting ONNX model for buffering...")
buffer = io.BytesIO()
torch.onnx.export(model.cpu(), sample_input.cpu(), f=buffer)
buffer.seek(0)
onnx_model = buffer.read()
logger.info("Loaded bytes string from buffer which holds the ONNX model")
logger.info("Started logging the ONNX model to MLFlow model repository...")
mlflow.onnx.log_model(
onnx_model=onnx_model,
artifact_path=ONNX_LOGGED_MODEL_DIR,
pip_requirements=mlflow.onnx.get_default_pip_requirements(),
onnx_execution_providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
code_paths=["src/stage_04_training_and_eval.py"],
registered_model_name=ONNX_MODEL_NAME,
)
logger.info("ONNX has been saved in MLFlow models repo...")
latest_model_version = mlflow_service.latest_model_version(
model_name=ONNX_MODEL_NAME
)
versions = mlflow_service.client.search_model_versions(f"name='{ONNX_MODEL_NAME}'")
for version in versions:
if version.current_stage == "Staging":
mlflow_service.transition_model_version_stage(
model_name=ONNX_MODEL_NAME,
model_version=version.version,
stage="Archived",
)
logger.info(
f"Model previous version # {version.version} has been transitioned from Staging to Archive"
)
mlflow_service.transition_model_version_stage(
model_name=ONNX_MODEL_NAME, model_version=latest_model_version, stage="Staging"
)
logger.info(
f"Model latest version # {latest_model_version} has been transitioned to MLFlow Staging"
)
mlflow.log_artifact(
f"{CONFUSION_MATRIX_PLOT_FILE_PATH}", artifact_path=ARTIFACT_DIR
)
logger.info("Logged the confusion metrics artifact to MLflow artifacts repo")
mlflow.log_artifact(f"{RAW_DATA_FILE_PATH}", artifact_path=ARTIFACT_DIR)
logger.info(
f"Logged the raw data file from {RAW_DATA_FILE_PATH} to MLflow artifacts repo"
)
if __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("--config", "-c", default="configs/system.yaml")
args.add_argument("--params", "-p", default="configs/params.yaml")
parsed_args = args.parse_args()
config = read_yaml(parsed_args.config)
params = read_yaml(parsed_args.params)
LOGS_FILE_PATH = config["logs"]["RUNNING_LOGS_FILE_PATH"]
X_TRAIN_FILE_PATH = config["data"]["PREPROCESSED_DATA_FILE_PATHS"][0]
Y_TRAIN_FILE_PATH = config["data"]["PREPROCESSED_DATA_FILE_PATHS"][1]
X_TEST_FILE_PATH = config["data"]["PREPROCESSED_DATA_FILE_PATHS"][2]
Y_TEST_FILE_PATH = config["data"]["PREPROCESSED_DATA_FILE_PATHS"][3]
EXPERIMENT_NAME = config["mlflow"]["EXPERIMENT_NAME"]
PYTORCH_MODEL_NAME = config["mlflow"]["PYTORCH_MODEL_NAME"]
ONNX_MODEL_NAME = config["mlflow"]["ONNX_MODEL_NAME"]
ONNX_LOGGED_MODEL_DIR = config["mlflow"]["ONNX_LOGGED_MODEL_DIR"]
ARTIFACT_DIR = config["mlflow"]["ARTIFACT_DIR"]
BATCH_SIZE_FOR_DATA_LOADER = params["data_preprocessing"][
"BATCH_SIZE_FOR_DATA_LOADER"
]
NUMBER_OF_EPOCHS = params["ml"]["MAX_NUMBER_OF_EPOCHS"]
MODEL_LOSS_PLOT_FILE_PATH = config["artifacts"]["MODEL_LOSS_PLOT_FILE_PATH"]
MODEL_ACCURACY_PLOT_FILE_PATH = config["artifacts"]["MODEL_ACCURACY_PLOT_FILE_PATH"]
CONFUSION_MATRIX_PLOT_FILE_PATH = config["artifacts"][
"CONFUSION_MATRIX_PLOT_FILE_PATH"
]
TRAINED_MODEL_FILE_PATH = config["artifacts"]["TRAINED_MODEL_FILE_PATH"]
ONNX_TRAINED_MODEL_FILE_PATH = config["artifacts"]["ONNX_TRAINED_MODEL_FILE_PATH"]
TENSORBOARD_LOGS_DIR = config["logs"]["TENSORBOARD_LOGS_DIR"]
ACCELERATOR = params["ml"]["ACCELERATOR"]
DEVICES = params["ml"]["DEVICES"]
MAX_NUMBER_OF_EPOCHS = params["ml"]["MAX_NUMBER_OF_EPOCHS"]
EARLY_STOPPING_PATIENCE = params["ml"]["EARLY_STOPPING_PATIENCE"]
METRICS_TO_TRACK = params["ml"]["METRICS_TO_TRACK"]
MIN_NUMBER_OF_EPOCHS = params["ml"]["MIN_NUMBER_OF_EPOCHS"]
PRECISION = params["ml"]["PRECISION"]
LEARNING_RATE = params["ml"]["LEARNING_RATE"]
CKPT_DIR = config["ckpt"]["CKPT_DIR"]
TOP_K_CKPT_TO_BE_SAVED = params["ckpt"]["TOP_K_CKPT_TO_BE_SAVED"]
OPTIMIZATION_MODE = params["ckpt"]["OPTIMIZATION_MODE"]
CKPT_FILE_PATH_FOR_TRAINING = config["ckpt"]["CKPT_FILE_PATH_FOR_TRAINING"]
RAW_DATA_FILE_PATH = config["data"]["RAW_DATA_FILE_PATH"][0]
|
# from pytorch_lightning.loggers import MLFlowLogger
STAGE = "Training and Evaluation"
def train_eval():
torch.set_float32_matmul_precision("medium")
X_train = load_np_arr_from_gz(X_TRAIN_FILE_PATH)
y_train = load_np_arr_from_gz(Y_TRAIN_FILE_PATH)
X_test = load_np_arr_from_gz(X_TEST_FILE_PATH)
y_test = load_np_arr_from_gz(Y_TEST_FILE_PATH)
logger.info(
f"Numpy Arrays have been loaded having the shapes : {X_train.shape, y_train.shape, X_test.shape, y_test.shape}"
)
num_classes = len(np.unique(y_train))
X_train = torch.tensor(X_train, dtype=torch.float32)
y_train = torch.tensor(y_train).type(torch.LongTensor)
X_test = torch.tensor(X_test, dtype=torch.float32)
y_test = torch.tensor(y_test).type(torch.LongTensor)
logger.info("Convertd numpy arrays to the pytorch tensors")
mlflow_service = MLFlowManager()
experiment_id = mlflow_service.get_or_create_an_experiment(EXPERIMENT_NAME)
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
run_name = config["mlflow"]["RUN_ID_PREFIX"] + "-" + timestamp
mlflow.pytorch.autolog(
silent=False, log_models=False, registered_model_name=PYTORCH_MODEL_NAME
)
train_ds = IoT_Dataset(X_train, y_train)
test_ds = IoT_Dataset(X_test, y_test)
logger.info("Train and Test Datasets created ")
train_dl = DataLoader(train_ds, batch_size=BATCH_SIZE_FOR_DATA_LOADER, shuffle=True)
test_dl = DataLoader(test_ds, batch_size=BATCH_SIZE_FOR_DATA_LOADER, shuffle=False)
logger.info("Train and Test DataLoaders created ")
device = get_default_device()
device = 'cpu'
logger.info(f'The default device is "{device}"')
for x, y in train_dl:
input_tensor_length = x.shape[1]
sample_input = x[0].unsqueeze(0)
break
logger.info(
f"Input and output tensor length is going to be {input_tensor_length} and {num_classes} respectively"
)
model = NN(
input_size=input_tensor_length,
learning_rate=LEARNING_RATE,
num_classes=num_classes,
)
to_device(model, device)
train_dl = DeviceDataLoader(train_dl, device)
test_dl = DeviceDataLoader(test_dl, device)
if ACCELERATOR == "cpu":
accelerator = CPUAccelerator()
elif ACCELERATOR == "gpu":
accelerator = 'gpu'
trainer = pl.Trainer(
logger=TensorBoardLogger(TENSORBOARD_LOGS_DIR, name=EXPERIMENT_NAME),
# logger=MLFlowLogger(experiment_name="my_experiment", save_dir="my_logs"),
# profiler= 'simple', #find the bottleneck then commitout
accelerator=accelerator,
devices=DEVICES,
min_epochs=MIN_NUMBER_OF_EPOCHS,
max_epochs=MAX_NUMBER_OF_EPOCHS,
resume_from_checkpoint=CKPT_FILE_PATH_FOR_TRAINING,
precision=PRECISION,
callbacks=[
PrintingCallback(),
EarlyStopping(monitor=METRICS_TO_TRACK, patience=EARLY_STOPPING_PATIENCE),
ModelCheckpoint(
dirpath=CKPT_DIR,
save_top_k=TOP_K_CKPT_TO_BE_SAVED,
mode=OPTIMIZATION_MODE,
monitor=METRICS_TO_TRACK,
filename=f"{time.strftime('%Y%m%d%H%M%S')}-" + "{epoch}-{val_loss:.2f}",
verbose=True,
),
],
)
logger.info("Starting mlflow experiment...")
valid_dl = test_dl # This is just for the demo purpose, you should always specify the different data for test and validation
mlflow.start_run(experiment_id=experiment_id, run_name=run_name)
trainer.fit(model, train_dl, valid_dl)
trainer.validate(model, valid_dl)
trainer.test(model, test_dl)
# trainer.save_checkpoint
y_actual = []
y_predicted_list = []
for x, y in valid_dl:
to_device(model, device)
out = model(x)
probabilities = F.softmax(out, dim=1)
y_predicted = torch.max(probabilities, 1)[1]
y_predicted_list.extend(y_predicted.tolist())
y_actual.extend(y.tolist())
labels = list(params["labels_mapping"].values())
if len(y_actual) > 0 and len(y_predicted_list) > 0:
plot_confusion_matrix(
CONFUSION_MATRIX_PLOT_FILE_PATH,
y=y_actual,
predicted_y=y_predicted_list,
label_names=labels,
)
logger.info("Model has been trained successfully")
logger.info(classification_report(y_actual, y_predicted_list, target_names=labels))
logger.info("Converting model to onnx format")
model.eval()
Path(ONNX_TRAINED_MODEL_FILE_PATH).parent.absolute().mkdir(
parents=True, exist_ok=True
)
model.to_onnx(
file_path=ONNX_TRAINED_MODEL_FILE_PATH,
input_sample=sample_input,
input_names=["input"],
verbose=True,
)
logger.info(f'ONNX model has been exported to "{ONNX_TRAINED_MODEL_FILE_PATH}"')
logger.info("Starting model validation...")
onnx_sess = rt.InferenceSession(
ONNX_TRAINED_MODEL_FILE_PATH,
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
input_name = onnx_sess.get_inputs()[0].name
input_data = {input_name: sample_input.cpu().numpy()}
output = onnx_sess.run(None, input_data)
if isinstance(output[0], np.ndarray) and len(output[0][0]) == num_classes:
logger.info("Model validation passed")
else:
logger.critical("Model validation failed!")
sys.exit(1)
logger.info("Exporting ONNX model for buffering...")
buffer = io.BytesIO()
torch.onnx.export(model.cpu(), sample_input.cpu(), f=buffer)
buffer.seek(0)
onnx_model = buffer.read()
logger.info("Loaded bytes string from buffer which holds the ONNX model")
logger.info("Started logging the ONNX model to MLFlow model repository...")
mlflow.onnx.log_model(
onnx_model=onnx_model,
artifact_path=ONNX_LOGGED_MODEL_DIR,
pip_requirements=mlflow.onnx.get_default_pip_requirements(),
onnx_execution_providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
code_paths=["src/stage_04_training_and_eval.py"],
registered_model_name=ONNX_MODEL_NAME,
)
logger.info("ONNX has been saved in MLFlow models repo...")
latest_model_version = mlflow_service.latest_model_version(
model_name=ONNX_MODEL_NAME
)
versions = mlflow_service.client.search_model_versions(f"name='{ONNX_MODEL_NAME}'")
for version in versions:
if version.current_stage == "Staging":
mlflow_service.transition_model_version_stage(
model_name=ONNX_MODEL_NAME,
model_version=version.version,
stage="Archived",
)
logger.info(
f"Model previous version # {version.version} has been transitioned from Staging to Archive"
)
mlflow_service.transition_model_version_stage(
model_name=ONNX_MODEL_NAME, model_version=latest_model_version, stage="Staging"
)
logger.info(
f"Model latest version # {latest_model_version} has been transitioned to MLFlow Staging"
)
mlflow.log_artifact(
f"{CONFUSION_MATRIX_PLOT_FILE_PATH}", artifact_path=ARTIFACT_DIR
)
logger.info("Logged the confusion metrics artifact to MLflow artifacts repo")
mlflow.log_artifact(f"{RAW_DATA_FILE_PATH}", artifact_path=ARTIFACT_DIR)
logger.info(
f"Logged the raw data file from {RAW_DATA_FILE_PATH} to MLflow artifacts repo"
)
if __name__ == "__main__":
args = argparse.ArgumentParser()
args.add_argument("--config", "-c", default="configs/system.yaml")
args.add_argument("--params", "-p", default="configs/params.yaml")
parsed_args = args.parse_args()
config = read_yaml(parsed_args.config)
params = read_yaml(parsed_args.params)
LOGS_FILE_PATH = config["logs"]["RUNNING_LOGS_FILE_PATH"]
X_TRAIN_FILE_PATH = config["data"]["PREPROCESSED_DATA_FILE_PATHS"][0]
Y_TRAIN_FILE_PATH = config["data"]["PREPROCESSED_DATA_FILE_PATHS"][1]
X_TEST_FILE_PATH = config["data"]["PREPROCESSED_DATA_FILE_PATHS"][2]
Y_TEST_FILE_PATH = config["data"]["PREPROCESSED_DATA_FILE_PATHS"][3]
EXPERIMENT_NAME = config["mlflow"]["EXPERIMENT_NAME"]
PYTORCH_MODEL_NAME = config["mlflow"]["PYTORCH_MODEL_NAME"]
ONNX_MODEL_NAME = config["mlflow"]["ONNX_MODEL_NAME"]
ONNX_LOGGED_MODEL_DIR = config["mlflow"]["ONNX_LOGGED_MODEL_DIR"]
ARTIFACT_DIR = config["mlflow"]["ARTIFACT_DIR"]
BATCH_SIZE_FOR_DATA_LOADER = params["data_preprocessing"][
"BATCH_SIZE_FOR_DATA_LOADER"
]
NUMBER_OF_EPOCHS = params["ml"]["MAX_NUMBER_OF_EPOCHS"]
MODEL_LOSS_PLOT_FILE_PATH = config["artifacts"]["MODEL_LOSS_PLOT_FILE_PATH"]
MODEL_ACCURACY_PLOT_FILE_PATH = config["artifacts"]["MODEL_ACCURACY_PLOT_FILE_PATH"]
CONFUSION_MATRIX_PLOT_FILE_PATH = config["artifacts"][
"CONFUSION_MATRIX_PLOT_FILE_PATH"
]
TRAINED_MODEL_FILE_PATH = config["artifacts"]["TRAINED_MODEL_FILE_PATH"]
ONNX_TRAINED_MODEL_FILE_PATH = config["artifacts"]["ONNX_TRAINED_MODEL_FILE_PATH"]
TENSORBOARD_LOGS_DIR = config["logs"]["TENSORBOARD_LOGS_DIR"]
ACCELERATOR = params["ml"]["ACCELERATOR"]
DEVICES = params["ml"]["DEVICES"]
MAX_NUMBER_OF_EPOCHS = params["ml"]["MAX_NUMBER_OF_EPOCHS"]
EARLY_STOPPING_PATIENCE = params["ml"]["EARLY_STOPPING_PATIENCE"]
METRICS_TO_TRACK = params["ml"]["METRICS_TO_TRACK"]
MIN_NUMBER_OF_EPOCHS = params["ml"]["MIN_NUMBER_OF_EPOCHS"]
PRECISION = params["ml"]["PRECISION"]
LEARNING_RATE = params["ml"]["LEARNING_RATE"]
CKPT_DIR = config["ckpt"]["CKPT_DIR"]
TOP_K_CKPT_TO_BE_SAVED = params["ckpt"]["TOP_K_CKPT_TO_BE_SAVED"]
OPTIMIZATION_MODE = params["ckpt"]["OPTIMIZATION_MODE"]
CKPT_FILE_PATH_FOR_TRAINING = config["ckpt"]["CKPT_FILE_PATH_FOR_TRAINING"]
RAW_DATA_FILE_PATH = config["data"]["RAW_DATA_FILE_PATH"][0]
| logger = get_logger(LOGS_FILE_PATH) | 1 | 2023-12-25 10:40:19+00:00 | 8k |
see2023/Bert-VITS2-ext | 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 torchaudio
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 models import VisemesNet
from config import config
from tools.translate import translate | 3,772 | # 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
net_v = None
device = config.webui_config.device
if device == "mps":
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
def audio_to_visemes(audio_raw, z):
global net_v
visemes = net_v(z)
visemes = visemes.squeeze(0)
visemes = visemes.transpose(0, 1)
visemes = visemes.data.cpu().float().numpy()
print('visemes shape:', visemes.shape)
# save as pcm_s16le wav
torchaudio.save('tmp.wav', audio_raw, hps.data.sampling_rate, encoding='PCM_S', bits_per_sample=16)
# save visemes to tmp.npy
np.save('tmp.npy', visemes)
# save z to tmp_z.npy like visemes
np.save('tmp_z.npy', z.squeeze(0).transpose(0, 1).data.cpu().float().numpy())
print('tmp.wav, tmp.npy, tmp_z.npy saved')
def generate_audio(
slices,
sdp_ratio,
noise_scale,
noise_scale_w,
length_scale,
speaker,
language,
reference_audio,
emotion,
style_text,
style_weight,
skip_start=False,
skip_end=False,
):
audio_list = []
audio_raw_list = []
z_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
skip_end = idx != len(slices) - 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
net_v = None
device = config.webui_config.device
if device == "mps":
os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1"
def audio_to_visemes(audio_raw, z):
global net_v
visemes = net_v(z)
visemes = visemes.squeeze(0)
visemes = visemes.transpose(0, 1)
visemes = visemes.data.cpu().float().numpy()
print('visemes shape:', visemes.shape)
# save as pcm_s16le wav
torchaudio.save('tmp.wav', audio_raw, hps.data.sampling_rate, encoding='PCM_S', bits_per_sample=16)
# save visemes to tmp.npy
np.save('tmp.npy', visemes)
# save z to tmp_z.npy like visemes
np.save('tmp_z.npy', z.squeeze(0).transpose(0, 1).data.cpu().float().numpy())
print('tmp.wav, tmp.npy, tmp_z.npy saved')
def generate_audio(
slices,
sdp_ratio,
noise_scale,
noise_scale_w,
length_scale,
speaker,
language,
reference_audio,
emotion,
style_text,
style_weight,
skip_start=False,
skip_end=False,
):
audio_list = []
audio_raw_list = []
z_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
skip_end = idx != len(slices) - 1 | audio, audio_raw, z = infer( | 1 | 2023-12-27 03:09:11+00:00 | 8k |
chinhsuanwu/ifusion-threestudio | threestudio/models/renderers/nerf_volume_renderer.py | [
{
"identifier": "BaseBackground",
"path": "threestudio/models/background/base.py",
"snippet": "class BaseBackground(BaseModule):\n @dataclass\n class Config(BaseModule.Config):\n pass\n\n cfg: Config\n\n def configure(self):\n pass\n\n def forward(self, dirs: Float[Tensor, \... | from dataclasses import dataclass, field
from functools import partial
from threestudio.models.background.base import BaseBackground
from threestudio.models.estimators import ImportanceEstimator
from threestudio.models.geometry.base import BaseImplicitGeometry
from threestudio.models.materials.base import BaseMaterial
from threestudio.models.networks import create_network_with_input_encoding
from threestudio.models.renderers.base import VolumeRenderer
from threestudio.systems.utils import parse_optimizer, parse_scheduler_to_instance
from threestudio.utils.ops import chunk_batch, get_activation, validate_empty_rays
from threestudio.utils.typing import *
import nerfacc
import torch
import torch.nn.functional as F
import threestudio | 5,569 | proposal_network_config: Optional[dict] = None
prop_optimizer_config: Optional[dict] = None
prop_scheduler_config: Optional[dict] = None
num_samples_per_ray_proposal: int = 64
# for importance
num_samples_per_ray_importance: int = 64
cfg: Config
def configure(
self,
geometry: BaseImplicitGeometry,
material: BaseMaterial,
background: BaseBackground,
) -> None:
super().configure(geometry, material, background)
if self.cfg.estimator == "occgrid":
self.estimator = nerfacc.OccGridEstimator(
roi_aabb=self.bbox.view(-1), resolution=32, levels=1
)
if not self.cfg.grid_prune:
self.estimator.occs.fill_(True)
self.estimator.binaries.fill_(True)
self.render_step_size = (
1.732 * 2 * self.cfg.radius / self.cfg.num_samples_per_ray
)
self.randomized = self.cfg.randomized
elif self.cfg.estimator == "importance":
self.estimator = ImportanceEstimator()
elif self.cfg.estimator == "proposal":
self.prop_net = create_network_with_input_encoding(
**self.cfg.proposal_network_config
)
self.prop_optim = parse_optimizer(
self.cfg.prop_optimizer_config, self.prop_net
)
self.prop_scheduler = (
parse_scheduler_to_instance(
self.cfg.prop_scheduler_config, self.prop_optim
)
if self.cfg.prop_scheduler_config is not None
else None
)
self.estimator = nerfacc.PropNetEstimator(
self.prop_optim, self.prop_scheduler
)
def get_proposal_requires_grad_fn(
target: float = 5.0, num_steps: int = 1000
):
schedule = lambda s: min(s / num_steps, 1.0) * target
steps_since_last_grad = 0
def proposal_requires_grad_fn(step: int) -> bool:
nonlocal steps_since_last_grad
target_steps_since_last_grad = schedule(step)
requires_grad = steps_since_last_grad > target_steps_since_last_grad
if requires_grad:
steps_since_last_grad = 0
steps_since_last_grad += 1
return requires_grad
return proposal_requires_grad_fn
self.proposal_requires_grad_fn = get_proposal_requires_grad_fn()
self.randomized = self.cfg.randomized
else:
raise NotImplementedError(
"Unknown estimator, should be one of ['occgrid', 'proposal', 'importance']."
)
# for proposal
self.vars_in_forward = {}
def forward(
self,
rays_o: Float[Tensor, "B H W 3"],
rays_d: Float[Tensor, "B H W 3"],
light_positions: Float[Tensor, "B 3"],
bg_color: Optional[Tensor] = None,
**kwargs
) -> Dict[str, Float[Tensor, "..."]]:
batch_size, height, width = rays_o.shape[:3]
rays_o_flatten: Float[Tensor, "Nr 3"] = rays_o.reshape(-1, 3)
rays_d_flatten: Float[Tensor, "Nr 3"] = rays_d.reshape(-1, 3)
light_positions_flatten: Float[Tensor, "Nr 3"] = (
light_positions.reshape(-1, 1, 1, 3)
.expand(-1, height, width, -1)
.reshape(-1, 3)
)
n_rays = rays_o_flatten.shape[0]
if self.cfg.estimator == "occgrid":
if not self.cfg.grid_prune:
with torch.no_grad():
ray_indices, t_starts_, t_ends_ = self.estimator.sampling(
rays_o_flatten,
rays_d_flatten,
sigma_fn=None,
near_plane=self.cfg.near_plane,
far_plane=self.cfg.far_plane,
render_step_size=self.render_step_size,
alpha_thre=0.0,
stratified=self.randomized,
cone_angle=0.0,
early_stop_eps=0,
)
else:
def sigma_fn(t_starts, t_ends, ray_indices):
t_starts, t_ends = t_starts[..., None], t_ends[..., None]
t_origins = rays_o_flatten[ray_indices]
t_positions = (t_starts + t_ends) / 2.0
t_dirs = rays_d_flatten[ray_indices]
positions = t_origins + t_dirs * t_positions
if self.training:
sigma = self.geometry.forward_density(positions)[..., 0]
else:
|
@threestudio.register("nerf-volume-renderer")
class NeRFVolumeRenderer(VolumeRenderer):
@dataclass
class Config(VolumeRenderer.Config):
num_samples_per_ray: int = 512
eval_chunk_size: int = 160000
randomized: bool = True
near_plane: float = 0.0
far_plane: float = 1e10
return_comp_normal: bool = False
return_normal_perturb: bool = False
# in ["occgrid", "proposal", "importance"]
estimator: str = "occgrid"
# for occgrid
grid_prune: bool = True
prune_alpha_threshold: bool = True
# for proposal
proposal_network_config: Optional[dict] = None
prop_optimizer_config: Optional[dict] = None
prop_scheduler_config: Optional[dict] = None
num_samples_per_ray_proposal: int = 64
# for importance
num_samples_per_ray_importance: int = 64
cfg: Config
def configure(
self,
geometry: BaseImplicitGeometry,
material: BaseMaterial,
background: BaseBackground,
) -> None:
super().configure(geometry, material, background)
if self.cfg.estimator == "occgrid":
self.estimator = nerfacc.OccGridEstimator(
roi_aabb=self.bbox.view(-1), resolution=32, levels=1
)
if not self.cfg.grid_prune:
self.estimator.occs.fill_(True)
self.estimator.binaries.fill_(True)
self.render_step_size = (
1.732 * 2 * self.cfg.radius / self.cfg.num_samples_per_ray
)
self.randomized = self.cfg.randomized
elif self.cfg.estimator == "importance":
self.estimator = ImportanceEstimator()
elif self.cfg.estimator == "proposal":
self.prop_net = create_network_with_input_encoding(
**self.cfg.proposal_network_config
)
self.prop_optim = parse_optimizer(
self.cfg.prop_optimizer_config, self.prop_net
)
self.prop_scheduler = (
parse_scheduler_to_instance(
self.cfg.prop_scheduler_config, self.prop_optim
)
if self.cfg.prop_scheduler_config is not None
else None
)
self.estimator = nerfacc.PropNetEstimator(
self.prop_optim, self.prop_scheduler
)
def get_proposal_requires_grad_fn(
target: float = 5.0, num_steps: int = 1000
):
schedule = lambda s: min(s / num_steps, 1.0) * target
steps_since_last_grad = 0
def proposal_requires_grad_fn(step: int) -> bool:
nonlocal steps_since_last_grad
target_steps_since_last_grad = schedule(step)
requires_grad = steps_since_last_grad > target_steps_since_last_grad
if requires_grad:
steps_since_last_grad = 0
steps_since_last_grad += 1
return requires_grad
return proposal_requires_grad_fn
self.proposal_requires_grad_fn = get_proposal_requires_grad_fn()
self.randomized = self.cfg.randomized
else:
raise NotImplementedError(
"Unknown estimator, should be one of ['occgrid', 'proposal', 'importance']."
)
# for proposal
self.vars_in_forward = {}
def forward(
self,
rays_o: Float[Tensor, "B H W 3"],
rays_d: Float[Tensor, "B H W 3"],
light_positions: Float[Tensor, "B 3"],
bg_color: Optional[Tensor] = None,
**kwargs
) -> Dict[str, Float[Tensor, "..."]]:
batch_size, height, width = rays_o.shape[:3]
rays_o_flatten: Float[Tensor, "Nr 3"] = rays_o.reshape(-1, 3)
rays_d_flatten: Float[Tensor, "Nr 3"] = rays_d.reshape(-1, 3)
light_positions_flatten: Float[Tensor, "Nr 3"] = (
light_positions.reshape(-1, 1, 1, 3)
.expand(-1, height, width, -1)
.reshape(-1, 3)
)
n_rays = rays_o_flatten.shape[0]
if self.cfg.estimator == "occgrid":
if not self.cfg.grid_prune:
with torch.no_grad():
ray_indices, t_starts_, t_ends_ = self.estimator.sampling(
rays_o_flatten,
rays_d_flatten,
sigma_fn=None,
near_plane=self.cfg.near_plane,
far_plane=self.cfg.far_plane,
render_step_size=self.render_step_size,
alpha_thre=0.0,
stratified=self.randomized,
cone_angle=0.0,
early_stop_eps=0,
)
else:
def sigma_fn(t_starts, t_ends, ray_indices):
t_starts, t_ends = t_starts[..., None], t_ends[..., None]
t_origins = rays_o_flatten[ray_indices]
t_positions = (t_starts + t_ends) / 2.0
t_dirs = rays_d_flatten[ray_indices]
positions = t_origins + t_dirs * t_positions
if self.training:
sigma = self.geometry.forward_density(positions)[..., 0]
else: | sigma = chunk_batch( | 8 | 2023-12-27 20:30:33+00:00 | 8k |
jasursadikov/mud | mud.py | [
{
"identifier": "TEXT",
"path": "utils.py",
"snippet": "TEXT = {\n 'white': '\\033[37m',\n 'gray': '\\033[90m',\n 'black': '\\033[30m',\n 'red': '\\033[31m',\n 'green': '\\033[32m',\n 'yellow': '\\033[33m',\n 'blue': '\\033[34m',\n 'magenta': '\\033[35m',\n 'cyan': '\\033[36m'... | import os
import sys
import asyncio
import argparse
import subprocess
import utils
from argparse import ArgumentParser
from utils import TEXT, RESET, STYLES
from config import Config
from settings import Settings
from commands import Commands | 6,002 | MODIFIED_ATTR = '-m', '--modified'
DIVERGED_ATTR = '-d', '--diverged'
# Commands
COMMANDS = {
'help': ['help', '--help', '-h'],
'version': ['--version'],
'set-global': ['--set-global'],
'init': ['init'],
'add': ['add', 'a'],
'remove': ['remove', 'rm'],
'branches': ['branch', 'branches', 'br'],
'status': ['status', 'st'],
'log': ['log', 'l'],
}
class MudCLI:
def __init__(self):
self.cmd_runner = None
self.config = None
self.parser = self._create_parser()
@staticmethod
def _create_parser() -> ArgumentParser:
parser = argparse.ArgumentParser(description=f'mud allows you to run commands in multiple directories.')
subparsers = parser.add_subparsers(dest='command')
subparsers.add_parser(COMMANDS['init'][0],
aliases=COMMANDS['init'][1:],
help='Initializing .mudconfig, adds all repositories in this directory to .mudconfig')
subparsers.add_parser(COMMANDS['status'][0],
aliases=COMMANDS['status'][1:],
help='Displays git status in a table view')
subparsers.add_parser(COMMANDS['branches'][0],
aliases=COMMANDS['branches'][1:],
help='Displays all branches in a table view')
subparsers.add_parser(COMMANDS['log'][0],
aliases=COMMANDS['log'][1:],
help='Displays log of last commit for all repos in a table view')
add_parser = subparsers.add_parser(COMMANDS['add'][0],
aliases=COMMANDS['add'][1:],
help='Register directory')
add_parser.add_argument('label',
help='The label to add (optional)',
nargs='?',
default='',
type=str)
add_parser.add_argument('path',
help='Directory to add (optional)',
nargs='?',
type=str)
remove_parser = subparsers.add_parser(COMMANDS['remove'][0],
aliases=COMMANDS['remove'][1:],
help='Remove label from directory or directory in .mudconfig')
remove_parser.add_argument('label',
help='Label to remove from directory (optional)',
nargs='?',
default='',
type=str)
remove_parser.add_argument('path', help='Directory to remove (optional)',
nargs='?',
type=str)
parser.add_argument(*LABEL_PREFIX, metavar='LABEL',
nargs='?',
default='',
type=str,
help='Filter repos with provided label')
parser.add_argument(*BRANCH_PREFIX,
metavar='BRANCH',
nargs='?',
default='',
type=str,
help='Filter repos with provided branch')
parser.add_argument(*MODIFIED_ATTR,
action='store_true',
help='Filter modified repos')
parser.add_argument(*DIVERGED_ATTR,
action='store_true',
help='Filter diverged repos')
parser.add_argument(COMMANDS['set-global'][0],
help='Sets \'.mudconfig\' in current directory as your global \'.mudconfig\' so you can '
'use it anywhere',
action='store_true')
parser.add_argument(COMMANDS['version'][0],
help='Displays current version of mud',
action='store_true')
parser.add_argument('catch_all',
nargs='*',
help='Type any commands to execute among repositories.')
return parser
def run(self) -> None:
# Displays default help message
if len(sys.argv) == 1 or sys.argv[1] in COMMANDS['help']:
self.parser.print_help()
return
# Sets global repository in .mudsettings
if sys.argv[1] in COMMANDS['set-global']:
config_path = os.path.join(os.getcwd(), utils.CONFIG_FILE_NAME)
if os.path.exists(config_path):
utils.settings.config.set('mud', 'config_path', config_path)
utils.settings.save()
print('Current .mudconfig set as a global configuration')
return
# Prints version
if sys.argv[1] in COMMANDS['version']:
utils.print_version()
return
current_directory = os.getcwd()
self.config = Config()
self._filter_repos()
if len(self.repos) == 0:
utils.print_error('No repositories are matching this filter')
return
| #!/usr/bin/env python3
# Filters
LABEL_PREFIX = '-l=', '--label='
BRANCH_PREFIX = '-b=', '--branch='
MODIFIED_ATTR = '-m', '--modified'
DIVERGED_ATTR = '-d', '--diverged'
# Commands
COMMANDS = {
'help': ['help', '--help', '-h'],
'version': ['--version'],
'set-global': ['--set-global'],
'init': ['init'],
'add': ['add', 'a'],
'remove': ['remove', 'rm'],
'branches': ['branch', 'branches', 'br'],
'status': ['status', 'st'],
'log': ['log', 'l'],
}
class MudCLI:
def __init__(self):
self.cmd_runner = None
self.config = None
self.parser = self._create_parser()
@staticmethod
def _create_parser() -> ArgumentParser:
parser = argparse.ArgumentParser(description=f'mud allows you to run commands in multiple directories.')
subparsers = parser.add_subparsers(dest='command')
subparsers.add_parser(COMMANDS['init'][0],
aliases=COMMANDS['init'][1:],
help='Initializing .mudconfig, adds all repositories in this directory to .mudconfig')
subparsers.add_parser(COMMANDS['status'][0],
aliases=COMMANDS['status'][1:],
help='Displays git status in a table view')
subparsers.add_parser(COMMANDS['branches'][0],
aliases=COMMANDS['branches'][1:],
help='Displays all branches in a table view')
subparsers.add_parser(COMMANDS['log'][0],
aliases=COMMANDS['log'][1:],
help='Displays log of last commit for all repos in a table view')
add_parser = subparsers.add_parser(COMMANDS['add'][0],
aliases=COMMANDS['add'][1:],
help='Register directory')
add_parser.add_argument('label',
help='The label to add (optional)',
nargs='?',
default='',
type=str)
add_parser.add_argument('path',
help='Directory to add (optional)',
nargs='?',
type=str)
remove_parser = subparsers.add_parser(COMMANDS['remove'][0],
aliases=COMMANDS['remove'][1:],
help='Remove label from directory or directory in .mudconfig')
remove_parser.add_argument('label',
help='Label to remove from directory (optional)',
nargs='?',
default='',
type=str)
remove_parser.add_argument('path', help='Directory to remove (optional)',
nargs='?',
type=str)
parser.add_argument(*LABEL_PREFIX, metavar='LABEL',
nargs='?',
default='',
type=str,
help='Filter repos with provided label')
parser.add_argument(*BRANCH_PREFIX,
metavar='BRANCH',
nargs='?',
default='',
type=str,
help='Filter repos with provided branch')
parser.add_argument(*MODIFIED_ATTR,
action='store_true',
help='Filter modified repos')
parser.add_argument(*DIVERGED_ATTR,
action='store_true',
help='Filter diverged repos')
parser.add_argument(COMMANDS['set-global'][0],
help='Sets \'.mudconfig\' in current directory as your global \'.mudconfig\' so you can '
'use it anywhere',
action='store_true')
parser.add_argument(COMMANDS['version'][0],
help='Displays current version of mud',
action='store_true')
parser.add_argument('catch_all',
nargs='*',
help='Type any commands to execute among repositories.')
return parser
def run(self) -> None:
# Displays default help message
if len(sys.argv) == 1 or sys.argv[1] in COMMANDS['help']:
self.parser.print_help()
return
# Sets global repository in .mudsettings
if sys.argv[1] in COMMANDS['set-global']:
config_path = os.path.join(os.getcwd(), utils.CONFIG_FILE_NAME)
if os.path.exists(config_path):
utils.settings.config.set('mud', 'config_path', config_path)
utils.settings.save()
print('Current .mudconfig set as a global configuration')
return
# Prints version
if sys.argv[1] in COMMANDS['version']:
utils.print_version()
return
current_directory = os.getcwd()
self.config = Config()
self._filter_repos()
if len(self.repos) == 0:
utils.print_error('No repositories are matching this filter')
return
| self.cmd_runner = Commands(self.config) | 5 | 2023-12-28 13:09:31+00:00 | 8k |
RaceCrewAI/gt-telem | gt_telem/turismo_client.py | [
{
"identifier": "PlayStationNotFoundError",
"path": "gt_telem/errors/playstation_errors.py",
"snippet": "class PlayStationNotFoundError(Exception):\n def __init__(self, message=\"Playstation not found on this network.\"):\n super().__init__(message)"
},
{
"identifier": "PlayStatonOnSta... | import asyncio
import copy
import logging
import socket
import threading
from collections import deque
from time import sleep
from gt_telem.errors.playstation_errors import (PlayStationNotFoundError,
PlayStatonOnStandbyError)
from gt_telem.models.helpers import SpanReader
from gt_telem.models.telemetry import Telemetry
from gt_telem.net.crypto import PDEncyption
from gt_telem.net.device_discover import get_ps_ip_type | 6,215 |
class TurismoClient:
RECEIVE_PORT = 33339
BIND_PORT = 33340
def __init__(self, is_gt7: bool=True, ps_ip: str=None):
"""
Initialize TurismoClient.
Parameters:
- is_gt7 (bool): Flag indicating whether it's Gran Turismo 7. Default is True.
- ps_ip (str): PlayStation IP address. If None, it will be discovered.
"""
self._cancellation_token = None
ip, ps = get_ps_ip_type()
ip = ip or ps_ip
if not ip:
raise PlayStationNotFoundError()
if ps and "STANDBY" in ps:
|
class TurismoClient:
RECEIVE_PORT = 33339
BIND_PORT = 33340
def __init__(self, is_gt7: bool=True, ps_ip: str=None):
"""
Initialize TurismoClient.
Parameters:
- is_gt7 (bool): Flag indicating whether it's Gran Turismo 7. Default is True.
- ps_ip (str): PlayStation IP address. If None, it will be discovered.
"""
self._cancellation_token = None
ip, ps = get_ps_ip_type()
ip = ip or ps_ip
if not ip:
raise PlayStationNotFoundError()
if ps and "STANDBY" in ps: | raise PlayStatonOnStandbyError(ip) | 1 | 2023-12-23 03:37:54+00:00 | 8k |
DidacticFishstick/ultrastar-wingman | main.py | [
{
"identifier": "Song",
"path": "song.py",
"snippet": "class Song:\n songs = {}\n usdb_ids = set()\n php_session_id = None\n\n @staticmethod\n def create_valid_dir_name(s):\n # Remove invalid characters\n s = re.sub(r'[<>:\"/\\\\|?*]', '', s)\n\n # Replace spaces with... | import getpass
import os
import asyncio
import json
import logging
import os.path
import platform
import signal
import subprocess
import threading
import websockets
import config
import usdb
import usdx
from flask import render_template, Flask, request, send_file
from song import Song
from websocket_server import WebSocketServer, messages | 4,580 |
return res.content, res.status_code
# headers = {k: v for k, v in request.headers if k.lower() != 'host'}
#
# # let everybody use the same php session key
# global php_session_id
# if php_session_id is None:
# php_session_id = headers.get("Cookie")
# Song.php_session_id = php_session_id
#
# if php_session_id is not None:
# headers["Cookie"] = php_session_id
#
# res = requests.request(
# method=request.method,
# url=request.url.replace(f"{request.host_url}usdb/", "https://usdb.animux.de/"),
# headers=headers,
# data=request.get_data(),
# cookies=request.cookies,
# allow_redirects=False,
# )
#
# excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
# headers = [
# (k, v) for k, v in res.raw.headers.items()
# if k.lower() not in excluded_headers
# ]
#
# response = Response(res.content, res.status_code, headers)
# return response
@app.route('/api/usdb/get_songs', methods=['GET'])
def get_songs_route():
args: dict = request.args.to_dict()
for key in ["golden", "songcheck"]:
if key in args:
args[key] = args[key] == "true"
songs = usdb.get_songs(**args)
for song in songs["songs"]:
song["downloaded"] = song["id"] in Song.usdb_ids
return songs
@app.route('/api/players', methods=['GET', 'POST'])
def names():
if request.method == 'POST':
name = request.form['name']
logging.info(f"Adding player '{name}'")
with open(config.players_file, 'a') as file:
file.write(name + '\n')
return {"success": True}
else:
try:
with open(config.players_file, 'r') as file:
names = file.read().splitlines()
return sorted(set(names))
except FileNotFoundError:
return []
@app.route('/api/players/delete', methods=['POST'])
def delete_name():
name_to_delete = request.form['name']
logging.info(f"Deleting player '{name_to_delete}'")
with open(config.players_file, 'r') as file:
names = file.read().splitlines()
with open(config.players_file, 'w') as file:
for name in names:
if name != name_to_delete:
file.write(name + '\n')
return {"success": True}
@app.route('/api/players/submit', methods=['POST'])
def submit_names():
usdx.enter_names(json.loads(request.form['names']))
return {"success": True}
def main():
username = config.usdb_user
password = config.usdb_pass
if username == "<username>" or password == "<password>":
username = None
password = None
while True:
if username is None or password is None:
print(f"To download songs, you need an account on https://usdb.animux.de. Create an account and enter the credentials below. You can always change these settings in the config file '{config.file_name}'.")
new_username = input("Username: ")
new_password = getpass.getpass("Password: ")
# Windows doing windows things...
while new_password == "\x16":
print("The windows cmd does not allow pasting into password fields using ctrl+V. Instead you can right click in the terminal to paste your password")
new_password = getpass.getpass("Password: ")
if new_username != username or new_password != password:
config.save_usdb_credentials(new_username, new_password)
username, password = new_username, new_password
if usdb.login(username, password):
print("Login on https://usdb.animux.de successful")
break
else:
print("Invalid credentials. Please try again.")
username = None
password = None
usdx.change_config(config.setup_colors)
restart_usdx()
threading.Thread(target=app.run, kwargs={"host": "0.0.0.0", "port": 8080}).start()
Song.load_songs()
|
SCRIPT_BASE_PATH = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__, static_folder=os.path.join(SCRIPT_BASE_PATH, "static"), template_folder=os.path.join(SCRIPT_BASE_PATH, "templates"))
usdx_process = None
download_queue = asyncio.Queue()
event_loop = asyncio.get_event_loop()
php_session_id = None
def restart_usdx():
global usdx_process
if usdx_process is not None:
logging.info("Stopping USDX")
if platform.system() == "Windows":
subprocess.call(['taskkill', '/F', '/T', '/PID', str(usdx_process.pid)])
else:
os.kill(usdx_process.pid, signal.SIGKILL)
logging.info("Starting USDX")
usdx_process = subprocess.Popen(str(config.usdx_path))
@app.route('/')
def index():
return render_template('index.html', messages=messages)
@app.route('/songs')
def songs():
return render_template('songs.html', songs=Song.song_list(), messages=messages)
@app.route('/song/<song_id>/cover', methods=['GET'])
def cover(song_id):
song = Song.get_song_by_id(song_id)
if song.cover_path:
return send_file(song.cover_path, mimetype=f'image/{song.cover_path.rsplit(".", 1)[-1].lower()}')
else:
# TODO: default cover
return "", 404
@app.route('/avatars/<avatar>', methods=['GET'])
def avatar(avatar):
try:
return send_file(os.path.join(SCRIPT_BASE_PATH, "avatars", f"cat_{avatar}"), mimetype=f'image/jpg')
except FileNotFoundError:
return send_file(os.path.join(SCRIPT_BASE_PATH, "avatars", "cat_rainbow.jpg"), mimetype=f'image/jpg')
@app.route('/download')
def download():
if request.args.get("view", "list") == "usdb":
return render_template('download.html', messages=messages)
else:
return render_template('download_list.html', messages=messages)
@app.route('/scores')
def scores():
return render_template('scores.html', messages=messages)
@app.route('/players')
def players():
return render_template('players.html', messages=messages, colors=config.setup_colors)
@app.route('/api/restart', methods=['POST'])
def api_restart():
restart_usdx()
return {"success": True}, 200
@app.route('/api/usdb_ids', methods=['GET'])
def api_ausdb_ids():
return list(Song.usdb_ids), 200
@app.route('/api/download', methods=['POST'])
def api_download_post():
id = request.json.get('id', '')
if not id:
return {"success": False, "error": "missing id"}, 400
id = int(id)
asyncio.run_coroutine_threadsafe(download_queue.put(id), event_loop)
return {"success": True}, 200
@app.route('/usdb/', defaults={'path': ''}, methods=['GET', 'POST', 'PUT', 'DELETE'])
@app.route('/usdb/<path:path>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def proxy(path):
# TODO: data does not work correctly
res = usdb.session.request(
method=request.method,
url=request.url.replace(f"{request.host_url}usdb/", "https://usdb.animux.de/"),
data=request.get_data(),
)
return res.content, res.status_code
# headers = {k: v for k, v in request.headers if k.lower() != 'host'}
#
# # let everybody use the same php session key
# global php_session_id
# if php_session_id is None:
# php_session_id = headers.get("Cookie")
# Song.php_session_id = php_session_id
#
# if php_session_id is not None:
# headers["Cookie"] = php_session_id
#
# res = requests.request(
# method=request.method,
# url=request.url.replace(f"{request.host_url}usdb/", "https://usdb.animux.de/"),
# headers=headers,
# data=request.get_data(),
# cookies=request.cookies,
# allow_redirects=False,
# )
#
# excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
# headers = [
# (k, v) for k, v in res.raw.headers.items()
# if k.lower() not in excluded_headers
# ]
#
# response = Response(res.content, res.status_code, headers)
# return response
@app.route('/api/usdb/get_songs', methods=['GET'])
def get_songs_route():
args: dict = request.args.to_dict()
for key in ["golden", "songcheck"]:
if key in args:
args[key] = args[key] == "true"
songs = usdb.get_songs(**args)
for song in songs["songs"]:
song["downloaded"] = song["id"] in Song.usdb_ids
return songs
@app.route('/api/players', methods=['GET', 'POST'])
def names():
if request.method == 'POST':
name = request.form['name']
logging.info(f"Adding player '{name}'")
with open(config.players_file, 'a') as file:
file.write(name + '\n')
return {"success": True}
else:
try:
with open(config.players_file, 'r') as file:
names = file.read().splitlines()
return sorted(set(names))
except FileNotFoundError:
return []
@app.route('/api/players/delete', methods=['POST'])
def delete_name():
name_to_delete = request.form['name']
logging.info(f"Deleting player '{name_to_delete}'")
with open(config.players_file, 'r') as file:
names = file.read().splitlines()
with open(config.players_file, 'w') as file:
for name in names:
if name != name_to_delete:
file.write(name + '\n')
return {"success": True}
@app.route('/api/players/submit', methods=['POST'])
def submit_names():
usdx.enter_names(json.loads(request.form['names']))
return {"success": True}
def main():
username = config.usdb_user
password = config.usdb_pass
if username == "<username>" or password == "<password>":
username = None
password = None
while True:
if username is None or password is None:
print(f"To download songs, you need an account on https://usdb.animux.de. Create an account and enter the credentials below. You can always change these settings in the config file '{config.file_name}'.")
new_username = input("Username: ")
new_password = getpass.getpass("Password: ")
# Windows doing windows things...
while new_password == "\x16":
print("The windows cmd does not allow pasting into password fields using ctrl+V. Instead you can right click in the terminal to paste your password")
new_password = getpass.getpass("Password: ")
if new_username != username or new_password != password:
config.save_usdb_credentials(new_username, new_password)
username, password = new_username, new_password
if usdb.login(username, password):
print("Login on https://usdb.animux.de successful")
break
else:
print("Invalid credentials. Please try again.")
username = None
password = None
usdx.change_config(config.setup_colors)
restart_usdx()
threading.Thread(target=app.run, kwargs={"host": "0.0.0.0", "port": 8080}).start()
Song.load_songs() | server = WebSocketServer(download_queue) | 1 | 2023-12-23 15:29:44+00:00 | 8k |
Q-MM/PureMM | model/language_model/PureMM_llama.py | [
{
"identifier": "PureMMMetaModel",
"path": "model/PureMM_arch.py",
"snippet": "class PureMMMetaModel:\n\n def __init__(self, config):\n super(PureMMMetaModel, self).__init__(config)\n\n if hasattr(config, \"mm_vision_tower\"):\n self.vision_tower = build_vision_tower(config, ... | from typing import List, Optional, Tuple, Union
from torch.nn import CrossEntropyLoss
from transformers import AutoConfig, AutoModelForCausalLM, \
LlamaConfig, LlamaModel, LlamaForCausalLM
from transformers.modeling_outputs import CausalLMOutputWithPast
from ..PureMM_arch import PureMMMetaModel, PureMMMetaForCausalLM
import torch
import torch.nn as nn | 3,717 | # Copyright 2023 Haotian Liu
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class PureMMConfig(LlamaConfig):
model_type = "PureMM"
class PureMMLlamaModel(PureMMMetaModel, LlamaModel):
config_class = PureMMConfig
def __init__(self, config: LlamaConfig):
super(PureMMLlamaModel, self).__init__(config)
| # Copyright 2023 Haotian Liu
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
class PureMMConfig(LlamaConfig):
model_type = "PureMM"
class PureMMLlamaModel(PureMMMetaModel, LlamaModel):
config_class = PureMMConfig
def __init__(self, config: LlamaConfig):
super(PureMMLlamaModel, self).__init__(config)
| class PureMMLlamaForCausalLM(LlamaForCausalLM, PureMMMetaForCausalLM): | 1 | 2023-12-27 09:54:09+00:00 | 8k |
gardenifi/server | tests/api/discover_wifi_test.py | [
{
"identifier": "discover_wifi",
"path": "app/main_app.py",
"snippet": "@app.get(\"/api/discover_wifi\")\nasync def discover_wifi(chunked: int = None, page: int = None):\n \"\"\"WIFI discovery API call.\"\"\"\n try:\n if chunked is not None:\n if page is None:\n re... | import json
import pytest
from app.main_app import discover_wifi
from app.raspi.services import Services | 4,669 | """MIT License
Copyright (c) 2023, Marios Karagiannopoulos
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.
**Attribution Requirement:**
When using or distributing the software, an attribution to Marios Karagiannopoulos must be included.
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.
"""
services = Services()
class TestDiscoverWifi:
"""
Test class for the discover_wifi function.
"""
@pytest.mark.asyncio
async def test_no_parameters(self):
"""
Test case for discover_wifi with no parameters.
"""
| """MIT License
Copyright (c) 2023, Marios Karagiannopoulos
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.
**Attribution Requirement:**
When using or distributing the software, an attribution to Marios Karagiannopoulos must be included.
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.
"""
services = Services()
class TestDiscoverWifi:
"""
Test class for the discover_wifi function.
"""
@pytest.mark.asyncio
async def test_no_parameters(self):
"""
Test case for discover_wifi with no parameters.
""" | response = await discover_wifi() | 0 | 2023-12-22 08:06:09+00:00 | 8k |
bclavie/RAGatouille | ragatouille/RAGTrainer.py | [
{
"identifier": "LateInteractionModel",
"path": "ragatouille/models/base.py",
"snippet": "class LateInteractionModel(ABC):\n @abstractmethod\n def __init__(\n self,\n pretrained_model_name_or_path: Union[str, Path],\n n_gpu,\n ):\n ...\n\n @abstractmethod\n def... | from pathlib import Path
from typing import Union, Literal, Optional
from colbert.infra import ColBERTConfig
from ragatouille.models import LateInteractionModel, ColBERT
from ragatouille.negative_miners import HardNegativeMiner, SimpleMiner
from ragatouille.utils import seeded_shuffle
from ragatouille.data import TrainingDataProcessor | 6,723 |
class RAGTrainer:
"""Main trainer to fine-tune/train ColBERT models with a few lines."""
model: Union[LateInteractionModel, None] = None
negative_miner: Union[HardNegativeMiner, None] = None
collection: list[str] = []
queries: Union[list[str], None] = None
raw_data: Union[list[tuple], list[list], None] = None
training_triplets: list[list[int]] = list()
def __init__(
self,
model_name: str,
pretrained_model_name: str,
language_code: str = "en",
n_usable_gpus: int = -1,
):
"""
Initialise a RAGTrainer instance. This will load a base model: either an existing ColBERT model to fine-tune or a BERT/RoBERTa-like model to build a new ColBERT model from.
Parameters:
model_name: str - Name of the model to train. This will be used to name the checkpoints and the index.
pretrained_model_name: str - Name of the pretrained model to use as a base. Can be a local path to a checkpoint or a huggingface model name.
language_code: str - Language code of the model to train. This will be used to name the checkpoints and the index.
n_usable_gpus: int - Number of GPUs to use. By default, value is -1, which means use all available GPUs or none if no GPU is available.
Returns:
self (RAGTrainer): The current instance of RAGTrainer, with the base model initialised.
"""
self.model_name = model_name
self.pretrained_model_name = pretrained_model_name
self.language_code = language_code
self.model = ColBERT(
pretrained_model_name_or_path=pretrained_model_name, n_gpu=n_usable_gpus
)
def add_documents(self, documents: list[str]):
self.collection += documents
|
class RAGTrainer:
"""Main trainer to fine-tune/train ColBERT models with a few lines."""
model: Union[LateInteractionModel, None] = None
negative_miner: Union[HardNegativeMiner, None] = None
collection: list[str] = []
queries: Union[list[str], None] = None
raw_data: Union[list[tuple], list[list], None] = None
training_triplets: list[list[int]] = list()
def __init__(
self,
model_name: str,
pretrained_model_name: str,
language_code: str = "en",
n_usable_gpus: int = -1,
):
"""
Initialise a RAGTrainer instance. This will load a base model: either an existing ColBERT model to fine-tune or a BERT/RoBERTa-like model to build a new ColBERT model from.
Parameters:
model_name: str - Name of the model to train. This will be used to name the checkpoints and the index.
pretrained_model_name: str - Name of the pretrained model to use as a base. Can be a local path to a checkpoint or a huggingface model name.
language_code: str - Language code of the model to train. This will be used to name the checkpoints and the index.
n_usable_gpus: int - Number of GPUs to use. By default, value is -1, which means use all available GPUs or none if no GPU is available.
Returns:
self (RAGTrainer): The current instance of RAGTrainer, with the base model initialised.
"""
self.model_name = model_name
self.pretrained_model_name = pretrained_model_name
self.language_code = language_code
self.model = ColBERT(
pretrained_model_name_or_path=pretrained_model_name, n_gpu=n_usable_gpus
)
def add_documents(self, documents: list[str]):
self.collection += documents | seeded_shuffle(self.collection) | 4 | 2023-12-29 16:26:42+00:00 | 8k |
Caipengzhou/BRAU-Netplusplus | networks/bra_unet_system.py | [
{
"identifier": "Block",
"path": "networks/bra_block.py",
"snippet": "class Block(nn.Module):\n def __init__(self, dim, input_resolution, drop_path=0., layer_scale_init_value=-1,num_heads=8, n_win=7, qk_dim=None, qk_scale=None,\n kv_per_win=4, kv_downsample_ratio=4, kv_downsample_kern... | import math
import torch
import torch.nn as nn
from timm.models.layers import trunc_normal_
from networks.bra_block import Block
from einops import rearrange
from fairscale.nn.checkpoint import checkpoint_wrapper
from networks.bra_decoder_expandx4 import BasicLayer_up | 3,991 | nn.BatchNorm2d(out_channels)
)
def forward(self, x):
b, c, h, w = x.shape
x_permute = x.permute(0, 2, 3, 1).view(b, -1, c)
x_att_permute = self.channel_attention(x_permute).view(b, h, w, c)
x_channel_att = x_att_permute.permute(0, 3, 1, 2)
x = x * x_channel_att
x_spatial_att = self.spatial_attention(x).sigmoid()
out = x * x_spatial_att
return out
class PatchExpand(nn.Module):
def __init__(self, input_resolution, dim, dim_scale=2, norm_layer=nn.LayerNorm):
super().__init__()
self.input_resolution = input_resolution
self.dim = dim
self.expand = nn.Linear(dim, 2 * dim, bias=False) if dim_scale == 2 else nn.Identity()
self.norm = norm_layer(dim // dim_scale)
def forward(self, x):
"""
x: B, H*W, C
"""
H, W = self.input_resolution
x = x.permute(0,2,3,1)
x = self.expand(x)
B, H, W, C = x.shape
x = x.view(B, H, W, C)
x = rearrange(x, 'b h w (p1 p2 c)-> b (h p1) (w p2) c', p1=2, p2=2, c=C // 4)
x = x.view(B, -1, C // 4)
x = self.norm(x)
return x
class FinalPatchExpand_X4(nn.Module):
def __init__(self, input_resolution, dim, dim_scale=4, norm_layer=nn.LayerNorm):
super().__init__()
self.input_resolution = input_resolution
self.dim = dim
self.dim_scale = dim_scale
self.expand = nn.Linear(dim, 16 * dim, bias=False)
self.output_dim = dim
self.norm = norm_layer(self.output_dim)
def forward(self, x):
H, W = self.input_resolution
x = self.expand(x)
B, L, C = x.shape
assert L == H * W, "input feature has wrong size"
x = x.view(B, H, W, C)
x = rearrange(x, 'b h w (p1 p2 c)-> b (h p1) (w p2) c', p1=self.dim_scale, p2=self.dim_scale,
c=C // (self.dim_scale ** 2))
x = x.view(B, -1, self.output_dim)
x = self.norm(x)
return x
class BRAUnetSystem(nn.Module):
def __init__(self, img_size=256,depth=[3, 4, 8, 3],depths_decoder=[2,2,2,2], in_chans=3, num_classes=1000, embed_dim=[64, 128, 320, 512],
head_dim=64, qk_scale=None, representation_size=None,
drop_path_rate=0.,
use_checkpoint_stages=[],
norm_layer=nn.LayerNorm,
########
n_win=7,
kv_downsample_mode='identity',
kv_per_wins=[2, 2, -1, -1],
topks=[8, 8, -1, -1],
side_dwconv=5,
layer_scale_init_value=-1,
qk_dims=[None, None, None, None],
param_routing=False, diff_routing=False, soft_routing=False,
pre_norm=True,
pe=None,
pe_stages=[0],
before_attn_dwconv=3,
auto_pad=False,
#-----------------------
kv_downsample_kernels=[4, 2, 1, 1],
kv_downsample_ratios=[4, 2, 1, 1], # -> kv_per_win = [2, 2, 2, 1]
mlp_ratios=[4, 4, 4, 4],
param_attention='qkvo',
final_upsample = "expand_first",
mlp_dwconv=False):
super().__init__()
self.num_classes = num_classes
self.num_features = embed_dim[0] # num_features for consistency with other models
patches_resolution = [img_size // 4, img_size // 4]
self.num_layers = len(depth)
self.patches_resolution = patches_resolution
self.final_upsample = final_upsample
self.sccsa1 = SCCSA(in_channels=embed_dim[1],out_channels=embed_dim[1])
self.sccsa2 = SCCSA(in_channels=embed_dim[2],out_channels=embed_dim[2])
self.sccsa3 = SCCSA(in_channels=embed_dim[3],out_channels=embed_dim[3])
############ downsample layers (patch embeddings) ######################
self.downsample_layers = nn.ModuleList()
# NOTE: uniformer uses two 3*3 conv, while in many other transformers this is one 7*7 conv
stem = nn.Sequential(
nn.Conv2d(in_chans, embed_dim[0] // 2, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
nn.BatchNorm2d(embed_dim[0] // 2),
nn.GELU(),
nn.Conv2d(embed_dim[0] // 2, embed_dim[0], kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
nn.BatchNorm2d(embed_dim[0]),
)
self.downsample_layers.append(stem)
for i in range(3):
downsample_layer = nn.Sequential(
nn.Conv2d(embed_dim[i], embed_dim[i+1], kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
nn.BatchNorm2d(embed_dim[i+1])
)
self.downsample_layers.append(downsample_layer)
##########################################################################
self.stages = nn.ModuleList() # 4 feature resolution stages, each consisting of multiple residual blocks
nheads = [dim // head_dim for dim in qk_dims]
dp_rates = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depth))]
cur = 0
for i in range(4):
stage = nn.Sequential(
|
class SCCSA(nn.Module):
def __init__(self, in_channels, out_channels, rate=4):
super(SCCSA, self).__init__()
self.channel_attention = nn.Sequential(
nn.Linear(in_channels, int(in_channels / rate)),
nn.ReLU(inplace=True),
nn.Linear(int(in_channels / rate), in_channels)
)
self.spatial_attention = nn.Sequential(
nn.Conv2d(in_channels, int(in_channels / rate), kernel_size=7, padding=3),
nn.BatchNorm2d(int(in_channels / rate)),
nn.ReLU(inplace=True),
nn.Conv2d(int(in_channels / rate), out_channels, kernel_size=7, padding=3),
nn.BatchNorm2d(out_channels)
)
def forward(self, x):
b, c, h, w = x.shape
x_permute = x.permute(0, 2, 3, 1).view(b, -1, c)
x_att_permute = self.channel_attention(x_permute).view(b, h, w, c)
x_channel_att = x_att_permute.permute(0, 3, 1, 2)
x = x * x_channel_att
x_spatial_att = self.spatial_attention(x).sigmoid()
out = x * x_spatial_att
return out
class PatchExpand(nn.Module):
def __init__(self, input_resolution, dim, dim_scale=2, norm_layer=nn.LayerNorm):
super().__init__()
self.input_resolution = input_resolution
self.dim = dim
self.expand = nn.Linear(dim, 2 * dim, bias=False) if dim_scale == 2 else nn.Identity()
self.norm = norm_layer(dim // dim_scale)
def forward(self, x):
"""
x: B, H*W, C
"""
H, W = self.input_resolution
x = x.permute(0,2,3,1)
x = self.expand(x)
B, H, W, C = x.shape
x = x.view(B, H, W, C)
x = rearrange(x, 'b h w (p1 p2 c)-> b (h p1) (w p2) c', p1=2, p2=2, c=C // 4)
x = x.view(B, -1, C // 4)
x = self.norm(x)
return x
class FinalPatchExpand_X4(nn.Module):
def __init__(self, input_resolution, dim, dim_scale=4, norm_layer=nn.LayerNorm):
super().__init__()
self.input_resolution = input_resolution
self.dim = dim
self.dim_scale = dim_scale
self.expand = nn.Linear(dim, 16 * dim, bias=False)
self.output_dim = dim
self.norm = norm_layer(self.output_dim)
def forward(self, x):
H, W = self.input_resolution
x = self.expand(x)
B, L, C = x.shape
assert L == H * W, "input feature has wrong size"
x = x.view(B, H, W, C)
x = rearrange(x, 'b h w (p1 p2 c)-> b (h p1) (w p2) c', p1=self.dim_scale, p2=self.dim_scale,
c=C // (self.dim_scale ** 2))
x = x.view(B, -1, self.output_dim)
x = self.norm(x)
return x
class BRAUnetSystem(nn.Module):
def __init__(self, img_size=256,depth=[3, 4, 8, 3],depths_decoder=[2,2,2,2], in_chans=3, num_classes=1000, embed_dim=[64, 128, 320, 512],
head_dim=64, qk_scale=None, representation_size=None,
drop_path_rate=0.,
use_checkpoint_stages=[],
norm_layer=nn.LayerNorm,
########
n_win=7,
kv_downsample_mode='identity',
kv_per_wins=[2, 2, -1, -1],
topks=[8, 8, -1, -1],
side_dwconv=5,
layer_scale_init_value=-1,
qk_dims=[None, None, None, None],
param_routing=False, diff_routing=False, soft_routing=False,
pre_norm=True,
pe=None,
pe_stages=[0],
before_attn_dwconv=3,
auto_pad=False,
#-----------------------
kv_downsample_kernels=[4, 2, 1, 1],
kv_downsample_ratios=[4, 2, 1, 1], # -> kv_per_win = [2, 2, 2, 1]
mlp_ratios=[4, 4, 4, 4],
param_attention='qkvo',
final_upsample = "expand_first",
mlp_dwconv=False):
super().__init__()
self.num_classes = num_classes
self.num_features = embed_dim[0] # num_features for consistency with other models
patches_resolution = [img_size // 4, img_size // 4]
self.num_layers = len(depth)
self.patches_resolution = patches_resolution
self.final_upsample = final_upsample
self.sccsa1 = SCCSA(in_channels=embed_dim[1],out_channels=embed_dim[1])
self.sccsa2 = SCCSA(in_channels=embed_dim[2],out_channels=embed_dim[2])
self.sccsa3 = SCCSA(in_channels=embed_dim[3],out_channels=embed_dim[3])
############ downsample layers (patch embeddings) ######################
self.downsample_layers = nn.ModuleList()
# NOTE: uniformer uses two 3*3 conv, while in many other transformers this is one 7*7 conv
stem = nn.Sequential(
nn.Conv2d(in_chans, embed_dim[0] // 2, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
nn.BatchNorm2d(embed_dim[0] // 2),
nn.GELU(),
nn.Conv2d(embed_dim[0] // 2, embed_dim[0], kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
nn.BatchNorm2d(embed_dim[0]),
)
self.downsample_layers.append(stem)
for i in range(3):
downsample_layer = nn.Sequential(
nn.Conv2d(embed_dim[i], embed_dim[i+1], kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
nn.BatchNorm2d(embed_dim[i+1])
)
self.downsample_layers.append(downsample_layer)
##########################################################################
self.stages = nn.ModuleList() # 4 feature resolution stages, each consisting of multiple residual blocks
nheads = [dim // head_dim for dim in qk_dims]
dp_rates = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depth))]
cur = 0
for i in range(4):
stage = nn.Sequential( | *[Block(dim=embed_dim[i], | 0 | 2023-12-29 05:45:26+00:00 | 8k |
shibing624/chatgpt-webui | src/base_model.py | [
{
"identifier": "shared",
"path": "src/shared.py",
"snippet": "class State:\n def interrupt(self):\n def recover(self):\n def set_api_host(self, api_host: str):\n def reset_api_host(self):\n def reset_all(self):\n def set_api_key_queue(self, api_key_list):\n def switching_api_key(se... | import os
import shutil
import traceback
import commentjson as json
import gradio as gr
import tiktoken
import urllib3
from enum import Enum
from itertools import islice
from loguru import logger
from src import shared
from src.config import retrieve_proxy
from src.index_func import construct_index
from src.presets import (
MODEL_TOKEN_LIMIT,
DEFAULT_TOKEN_LIMIT,
TOKEN_OFFSET,
REDUCE_TOKEN_FACTOR,
STANDARD_ERROR_MSG,
NO_APIKEY_MSG,
BILLING_NOT_APPLICABLE_MSG,
NO_INPUT_MSG,
HISTORY_DIR,
INITIAL_SYSTEM_PROMPT,
PROMPT_TEMPLATE,
WEBSEARCH_PTOMPT_TEMPLATE,
)
from src.utils import (
i18n,
construct_assistant,
construct_user,
save_file,
hide_middle_chars,
count_token,
new_auto_history_filename,
get_history_names,
get_history_filepath,
init_history_list,
get_history_list,
replace_special_symbols,
get_first_history_name,
add_source_numbers,
add_details,
replace_today,
chinese_preprocessing_func,
)
from langchain.vectorstores.base import VectorStoreRetriever
from langchain.retrievers import BM25Retriever, EnsembleRetriever
from duckduckgo_search import DDGS | 5,381 | logit_bias = self.logit_bias.split()
bias_map = {}
encoding = tiktoken.get_encoding("cl100k_base")
for line in logit_bias:
word, bias_amount = line.split(":")
if word:
for token in encoding.encode(word):
bias_map[token] = float(bias_amount)
return bias_map
def set_user_identifier(self, new_user_identifier):
self.user_identifier = new_user_identifier
self.auto_save()
def set_system_prompt(self, new_system_prompt):
self.system_prompt = new_system_prompt
self.auto_save()
def set_key(self, new_access_key):
self.api_key = new_access_key.strip()
msg = i18n("API密钥更改为了") + hide_middle_chars(self.api_key)
logger.info(msg)
return self.api_key, msg
def set_single_turn(self, new_single_turn):
self.single_turn = new_single_turn
self.auto_save()
def reset(self, remain_system_prompt=False):
self.history = []
self.all_token_counts = []
self.interrupted = False
self.history_file_path = new_auto_history_filename(self.user_name)
history_name = self.history_file_path[:-5]
choices = [history_name] + get_history_names(self.user_name)
system_prompt = self.system_prompt if remain_system_prompt else ""
self.single_turn = self.default_single_turn
self.temperature = self.default_temperature
self.top_p = self.default_top_p
self.n_choices = self.default_n_choices
self.stop_sequence = self.default_stop_sequence
self.max_generation_token = self.default_max_generation_token
self.presence_penalty = self.default_presence_penalty
self.frequency_penalty = self.default_frequency_penalty
self.logit_bias = self.default_logit_bias
self.user_identifier = self.default_user_identifier
return (
[],
self.token_message([0]),
gr.Radio.update(choices=choices, value=history_name),
system_prompt,
self.single_turn,
self.temperature,
self.top_p,
self.n_choices,
self.stop_sequence,
self.token_upper_limit,
self.max_generation_token,
self.presence_penalty,
self.frequency_penalty,
self.logit_bias,
self.user_identifier,
)
def delete_first_conversation(self):
if self.history:
del self.history[:2]
del self.all_token_counts[0]
return self.token_message()
def delete_last_conversation(self, chatbot):
if len(chatbot) > 0 and STANDARD_ERROR_MSG in chatbot[-1][1]:
msg = "由于包含报错信息,只删除chatbot记录"
chatbot = chatbot[:-1]
return chatbot, self.history
if len(self.history) > 0:
self.history = self.history[:-2]
if len(chatbot) > 0:
msg = "删除了一组chatbot对话"
chatbot = chatbot[:-1]
if len(self.all_token_counts) > 0:
msg = "删除了一组对话的token计数记录"
self.all_token_counts.pop()
msg = "删除了一组对话"
self.chatbot = chatbot
self.auto_save(chatbot)
return chatbot, msg
def token_message(self, token_lst=None):
if token_lst is None:
token_lst = self.all_token_counts
token_sum = 0
for i in range(len(token_lst)):
token_sum += sum(token_lst[: i + 1])
return (
i18n("Token 计数: ")
+ f"{sum(token_lst)}"
+ i18n(",本次对话累计消耗了 ")
+ f"{token_sum} tokens"
)
def rename_chat_history(self, filename, chatbot):
if filename == "":
return gr.update()
if not filename.endswith(".json"):
filename += ".json"
self.delete_chat_history(self.history_file_path)
# 命名重复检测
repeat_file_index = 2
full_path = os.path.join(HISTORY_DIR, self.user_name, filename)
while os.path.exists(full_path):
full_path = os.path.join(
HISTORY_DIR, self.user_name, f"{repeat_file_index}_{filename}"
)
repeat_file_index += 1
filename = os.path.basename(full_path)
self.history_file_path = filename
|
class ModelType(Enum):
Unknown = -1
OpenAI = 0
ChatGLM = 1
OpenAIInstruct = 2
OpenAIVision = 3
Claude = 4
Qwen = 5
LLaMA = 6
@classmethod
def get_type(cls, model_name: str):
model_name_lower = model_name.lower()
if "gpt" in model_name_lower:
if "instruct" in model_name_lower:
model_type = ModelType.OpenAIInstruct
elif "vision" in model_name_lower:
model_type = ModelType.OpenAIVision
else:
model_type = ModelType.OpenAI
elif "chatglm" in model_name_lower:
model_type = ModelType.ChatGLM
elif "llama" in model_name_lower or "alpaca" in model_name_lower or "yi" in model_name_lower:
model_type = ModelType.LLaMA
else:
model_type = ModelType.Unknown
return model_type
class BaseLLMModel:
def __init__(
self,
model_name,
system_prompt=INITIAL_SYSTEM_PROMPT,
temperature=1.0,
top_p=1.0,
n_choices=1,
stop="",
max_generation_token=None,
presence_penalty=0,
frequency_penalty=0,
logit_bias=None,
user="",
single_turn=False,
) -> None:
self.history = []
self.all_token_counts = []
self.model_name = model_name
self.model_type = ModelType.get_type(model_name)
try:
self.token_upper_limit = MODEL_TOKEN_LIMIT[model_name]
except KeyError:
self.token_upper_limit = DEFAULT_TOKEN_LIMIT
self.interrupted = False
self.system_prompt = system_prompt
self.api_key = None
self.need_api_key = False
self.history_file_path = get_first_history_name(user)
self.user_name = user
self.chatbot = []
self.default_single_turn = single_turn
self.default_temperature = temperature
self.default_top_p = top_p
self.default_n_choices = n_choices
self.default_stop_sequence = stop
self.default_max_generation_token = max_generation_token
self.default_presence_penalty = presence_penalty
self.default_frequency_penalty = frequency_penalty
self.default_logit_bias = logit_bias
self.default_user_identifier = user
self.single_turn = single_turn
self.temperature = temperature
self.top_p = top_p
self.n_choices = n_choices
self.stop_sequence = stop
self.max_generation_token = max_generation_token
self.presence_penalty = presence_penalty
self.frequency_penalty = frequency_penalty
self.logit_bias = logit_bias
self.user_identifier = user
self.metadata = {}
def get_answer_stream_iter(self):
"""stream predict, need to be implemented
conversations are stored in self.history, with the most recent question, in OpenAI format
should return a generator, each time give the next word (str) in the answer
"""
logger.warning("stream predict not implemented, using at once predict instead")
response, _ = self.get_answer_at_once()
yield response
def get_answer_at_once(self):
"""predict at once, need to be implemented
conversations are stored in history, with the most recent question, in OpenAI format
Should return:
the answer (str)
total token count (int)
"""
logger.warning("at once predict not implemented, using stream predict instead")
response_iter = self.get_answer_stream_iter()
count = 0
response = ''
for response in response_iter:
count += 1
return response, sum(self.all_token_counts) + count
def billing_info(self):
"""get billing infomation, inplement if needed"""
return BILLING_NOT_APPLICABLE_MSG
def count_token(self, user_input):
"""get token count from input, implement if needed"""
return len(user_input)
def stream_next_chatbot(self, inputs, chatbot, fake_input=None, display_append=""):
def get_return_value():
return chatbot, status_text
status_text = i18n("开始实时传输回答……")
if fake_input:
chatbot.append((fake_input, ""))
else:
chatbot.append((inputs, ""))
user_token_count = self.count_token(inputs)
self.all_token_counts.append(user_token_count)
logger.debug(f"输入token计数: {user_token_count}")
stream_iter = self.get_answer_stream_iter()
if display_append:
display_append = (
'\n\n<hr class="append-display no-in-raw" />' + display_append
)
partial_text = ""
token_increment = 1
for partial_text in stream_iter:
if type(partial_text) == tuple:
partial_text, token_increment = partial_text
chatbot[-1] = (chatbot[-1][0], partial_text + display_append)
self.all_token_counts[-1] += token_increment
status_text = self.token_message()
yield get_return_value()
if self.interrupted:
self.recover()
break
self.history.append(construct_assistant(partial_text))
def next_chatbot_at_once(self, inputs, chatbot, fake_input=None, display_append=""):
if fake_input:
chatbot.append((fake_input, ""))
else:
chatbot.append((inputs, ""))
if fake_input is not None:
user_token_count = self.count_token(fake_input)
else:
user_token_count = self.count_token(inputs)
self.all_token_counts.append(user_token_count)
ai_reply, total_token_count = self.get_answer_at_once()
self.history.append(construct_assistant(ai_reply))
if fake_input is not None:
self.history[-2] = construct_user(fake_input)
chatbot[-1] = (chatbot[-1][0], ai_reply + display_append)
if fake_input is not None:
self.all_token_counts[-1] += count_token(construct_assistant(ai_reply))
else:
self.all_token_counts[-1] = total_token_count - sum(self.all_token_counts)
status_text = self.token_message()
return chatbot, status_text
def handle_file_upload(self, files, chatbot, language):
"""if the model accepts modal input, implement this function"""
status = gr.Markdown.update()
if files:
construct_index(self.api_key, files=files)
status = i18n("索引构建完成")
return gr.Files.update(), chatbot, status
def prepare_inputs(
self, real_inputs, use_websearch,
files, reply_language, chatbot,
load_from_cache_if_possible=True,
):
display_append = []
limited_context = False
if type(real_inputs) == list:
fake_inputs = real_inputs[0]["text"]
else:
fake_inputs = real_inputs
if files:
limited_context = True
msg = "加载索引中……"
logger.info(msg)
index, documents = construct_index(
self.api_key,
files=files,
load_from_cache_if_possible=load_from_cache_if_possible,
)
assert index is not None, "获取索引失败"
msg = "索引获取成功,生成回答中……"
logger.info(msg)
k = 3
score_threshold = 0.6
with retrieve_proxy():
vec_retriever = VectorStoreRetriever(
vectorstore=index,
search_type="similarity_score_threshold",
search_kwargs={"k": k, "score_threshold": score_threshold}
)
bm25_retriever = BM25Retriever.from_documents(documents, preprocess_func=chinese_preprocessing_func)
bm25_retriever.k = k
ensemble_retriever = EnsembleRetriever(
retrievers=[bm25_retriever, vec_retriever],
weights=[0.5, 0.5],
)
try:
relevant_documents = ensemble_retriever.get_relevant_documents(fake_inputs)
except:
return self.prepare_inputs(
fake_inputs,
use_websearch,
files,
reply_language,
chatbot,
load_from_cache_if_possible=False,
)
reference_results = [
[d.page_content.strip("�"), os.path.basename(d.metadata["source"])]
for d in relevant_documents
]
reference_results = add_source_numbers(reference_results)
display_append = add_details(reference_results)
display_append = "\n\n" + "".join(display_append)
if type(real_inputs) == list:
real_inputs[0]["text"] = (
replace_today(PROMPT_TEMPLATE)
.replace("{query_str}", fake_inputs)
.replace("{context_str}", "\n\n".join(reference_results))
.replace("{reply_language}", reply_language)
)
else:
real_inputs = (
replace_today(PROMPT_TEMPLATE)
.replace("{query_str}", real_inputs)
.replace("{context_str}", "\n\n".join(reference_results))
.replace("{reply_language}", reply_language)
)
elif use_websearch:
search_results = []
with DDGS() as ddgs:
ddgs_gen = ddgs.text(fake_inputs, backend="lite")
for r in islice(ddgs_gen, 10):
search_results.append(r)
reference_results = []
for idx, result in enumerate(search_results):
logger.debug(f"搜索结果{idx + 1}:{result}")
domain_name = urllib3.util.parse_url(result["href"]).host
reference_results.append([result["body"], result["href"]])
display_append.append(
# f"{idx+1}. [{domain_name}]({result['href']})\n"
f"<a href=\"{result['href']}\" target=\"_blank\">{idx + 1}. {result['title']}</a>"
)
reference_results = add_source_numbers(reference_results)
# display_append = "<ol>\n\n" + "".join(display_append) + "</ol>"
display_append = (
'<div class = "source-a">' + "".join(display_append) + "</div>"
)
if type(real_inputs) == list:
real_inputs[0]["text"] = (
replace_today(WEBSEARCH_PTOMPT_TEMPLATE)
.replace("{query}", fake_inputs)
.replace("{web_results}", "\n\n".join(reference_results))
.replace("{reply_language}", reply_language)
)
else:
real_inputs = (
replace_today(WEBSEARCH_PTOMPT_TEMPLATE)
.replace("{query}", fake_inputs)
.replace("{web_results}", "\n\n".join(reference_results))
.replace("{reply_language}", reply_language)
)
else:
display_append = ""
return limited_context, fake_inputs, display_append, real_inputs, chatbot
def predict(
self,
inputs,
chatbot,
stream=False,
use_websearch=False,
files=None,
reply_language="中文",
should_check_token_count=True,
): # repetition_penalty, top_k
status_text = "开始生成回答……"
if type(inputs) == list:
logger.info(
"用户"
+ f"{self.user_name}"
+ "的输入为:"
+ "("
+ str(len(inputs) - 1)
+ " images) "
+ f"{inputs[0]['text']}"
)
else:
logger.info(
"用户"
+ f"{self.user_name}"
+ "的输入为:"
+ f"{inputs}"
)
if should_check_token_count:
if type(inputs) == list:
yield chatbot + [(inputs[0]["text"], "")], status_text
else:
yield chatbot + [(inputs, "")], status_text
if reply_language == "跟随问题语言(不稳定)":
reply_language = "the same language as the question, such as English, 中文, 日本語, Español, Français, or Deutsch."
limited_context, fake_inputs, display_append, inputs, chatbot = self.prepare_inputs(
real_inputs=inputs,
use_websearch=use_websearch,
files=files,
reply_language=reply_language,
chatbot=chatbot
)
yield chatbot + [(fake_inputs, "")], status_text
if (
self.need_api_key and
self.api_key is None
and not shared.state.multi_api_key
):
status_text = STANDARD_ERROR_MSG + NO_APIKEY_MSG
logger.info(status_text)
chatbot.append((inputs, ""))
if len(self.history) == 0:
self.history.append(construct_user(inputs))
self.history.append("")
self.all_token_counts.append(0)
else:
self.history[-2] = construct_user(inputs)
yield chatbot + [(inputs, "")], status_text
return
elif len(inputs.strip()) == 0:
status_text = STANDARD_ERROR_MSG + NO_INPUT_MSG
logger.info(status_text)
yield chatbot + [(inputs, "")], status_text
return
if self.single_turn:
self.history = []
self.all_token_counts = []
if type(inputs) == list:
self.history.append(inputs)
else:
self.history.append(construct_user(inputs))
try:
if stream:
logger.debug("使用流式传输")
iter = self.stream_next_chatbot(
inputs,
chatbot,
fake_input=fake_inputs,
display_append=display_append,
)
for chatbot, status_text in iter:
yield chatbot, status_text
else:
logger.debug("不使用流式传输")
chatbot, status_text = self.next_chatbot_at_once(
inputs,
chatbot,
fake_input=fake_inputs,
display_append=display_append,
)
yield chatbot, status_text
except Exception as e:
traceback.print_exc()
status_text = STANDARD_ERROR_MSG + str(e)
yield chatbot, status_text
if len(self.history) > 1 and self.history[-1]["content"] != inputs:
logger.info("回答为:" + f"{self.history[-1]['content']}")
if limited_context:
self.history = []
self.all_token_counts = []
max_token = self.token_upper_limit - TOKEN_OFFSET
if sum(self.all_token_counts) > max_token and should_check_token_count:
count = 0
while (
sum(self.all_token_counts)
> self.token_upper_limit * REDUCE_TOKEN_FACTOR
and sum(self.all_token_counts) > 0
):
count += 1
del self.all_token_counts[0]
del self.history[:2]
logger.info(status_text)
status_text = f"为了防止token超限,模型忘记了早期的 {count} 轮对话"
yield chatbot, status_text
def retry(
self,
chatbot,
stream=False,
use_websearch=False,
files=None,
reply_language="中文",
):
logger.debug("重试中……")
if len(self.history) > 1:
inputs = self.history[-2]["content"]
del self.history[-2:]
if len(self.all_token_counts) > 0:
self.all_token_counts.pop()
elif len(chatbot) > 0:
inputs = chatbot[-1][0]
if '<div class="user-message">' in inputs:
inputs = inputs.split('<div class="user-message">')[1]
inputs = inputs.split("</div>")[0]
elif len(self.history) == 1:
inputs = self.history[-1]["content"]
del self.history[-1]
else:
yield chatbot, f"{STANDARD_ERROR_MSG}上下文是空的"
return
iter = self.predict(
inputs,
chatbot,
stream=stream,
use_websearch=use_websearch,
files=files,
reply_language=reply_language,
)
for x in iter:
yield x
logger.debug("重试完毕")
def interrupt(self):
self.interrupted = True
def recover(self):
self.interrupted = False
def set_token_upper_limit(self, new_upper_limit):
self.token_upper_limit = new_upper_limit
logger.info(f"token上限设置为{new_upper_limit}")
self.auto_save()
def set_temperature(self, new_temperature):
self.temperature = new_temperature
self.auto_save()
def set_top_p(self, new_top_p):
self.top_p = new_top_p
self.auto_save()
def set_n_choices(self, new_n_choices):
self.n_choices = new_n_choices
self.auto_save()
def set_stop_sequence(self, new_stop_sequence: str):
new_stop_sequence = new_stop_sequence.split(",")
self.stop_sequence = new_stop_sequence
self.auto_save()
def set_max_tokens(self, new_max_tokens):
self.max_generation_token = new_max_tokens
self.auto_save()
def set_presence_penalty(self, new_presence_penalty):
self.presence_penalty = new_presence_penalty
self.auto_save()
def set_frequency_penalty(self, new_frequency_penalty):
self.frequency_penalty = new_frequency_penalty
self.auto_save()
def set_logit_bias(self, logit_bias):
self.logit_bias = logit_bias
self.auto_save()
def encoded_logit_bias(self):
if self.logit_bias is None:
return {}
logit_bias = self.logit_bias.split()
bias_map = {}
encoding = tiktoken.get_encoding("cl100k_base")
for line in logit_bias:
word, bias_amount = line.split(":")
if word:
for token in encoding.encode(word):
bias_map[token] = float(bias_amount)
return bias_map
def set_user_identifier(self, new_user_identifier):
self.user_identifier = new_user_identifier
self.auto_save()
def set_system_prompt(self, new_system_prompt):
self.system_prompt = new_system_prompt
self.auto_save()
def set_key(self, new_access_key):
self.api_key = new_access_key.strip()
msg = i18n("API密钥更改为了") + hide_middle_chars(self.api_key)
logger.info(msg)
return self.api_key, msg
def set_single_turn(self, new_single_turn):
self.single_turn = new_single_turn
self.auto_save()
def reset(self, remain_system_prompt=False):
self.history = []
self.all_token_counts = []
self.interrupted = False
self.history_file_path = new_auto_history_filename(self.user_name)
history_name = self.history_file_path[:-5]
choices = [history_name] + get_history_names(self.user_name)
system_prompt = self.system_prompt if remain_system_prompt else ""
self.single_turn = self.default_single_turn
self.temperature = self.default_temperature
self.top_p = self.default_top_p
self.n_choices = self.default_n_choices
self.stop_sequence = self.default_stop_sequence
self.max_generation_token = self.default_max_generation_token
self.presence_penalty = self.default_presence_penalty
self.frequency_penalty = self.default_frequency_penalty
self.logit_bias = self.default_logit_bias
self.user_identifier = self.default_user_identifier
return (
[],
self.token_message([0]),
gr.Radio.update(choices=choices, value=history_name),
system_prompt,
self.single_turn,
self.temperature,
self.top_p,
self.n_choices,
self.stop_sequence,
self.token_upper_limit,
self.max_generation_token,
self.presence_penalty,
self.frequency_penalty,
self.logit_bias,
self.user_identifier,
)
def delete_first_conversation(self):
if self.history:
del self.history[:2]
del self.all_token_counts[0]
return self.token_message()
def delete_last_conversation(self, chatbot):
if len(chatbot) > 0 and STANDARD_ERROR_MSG in chatbot[-1][1]:
msg = "由于包含报错信息,只删除chatbot记录"
chatbot = chatbot[:-1]
return chatbot, self.history
if len(self.history) > 0:
self.history = self.history[:-2]
if len(chatbot) > 0:
msg = "删除了一组chatbot对话"
chatbot = chatbot[:-1]
if len(self.all_token_counts) > 0:
msg = "删除了一组对话的token计数记录"
self.all_token_counts.pop()
msg = "删除了一组对话"
self.chatbot = chatbot
self.auto_save(chatbot)
return chatbot, msg
def token_message(self, token_lst=None):
if token_lst is None:
token_lst = self.all_token_counts
token_sum = 0
for i in range(len(token_lst)):
token_sum += sum(token_lst[: i + 1])
return (
i18n("Token 计数: ")
+ f"{sum(token_lst)}"
+ i18n(",本次对话累计消耗了 ")
+ f"{token_sum} tokens"
)
def rename_chat_history(self, filename, chatbot):
if filename == "":
return gr.update()
if not filename.endswith(".json"):
filename += ".json"
self.delete_chat_history(self.history_file_path)
# 命名重复检测
repeat_file_index = 2
full_path = os.path.join(HISTORY_DIR, self.user_name, filename)
while os.path.exists(full_path):
full_path = os.path.join(
HISTORY_DIR, self.user_name, f"{repeat_file_index}_{filename}"
)
repeat_file_index += 1
filename = os.path.basename(full_path)
self.history_file_path = filename | save_file(filename, self, chatbot) | 15 | 2023-12-27 12:14:26+00:00 | 8k |
camenduru/DiffMorpher-hf | morph_attn.py | [
{
"identifier": "train_lora",
"path": "lora_utils.py",
"snippet": "def train_lora(image, prompt, save_lora_dir, model_path=None, tokenizer=None, text_encoder=None, vae=None, unet=None, noise_scheduler=None, lora_steps=200, lora_lr=2e-4, lora_rank=16, weight_name=None, safe_serialization=False, progress=... | import os
import torch
import torch.nn.functional as F
import tqdm
import numpy as np
import safetensors
from diffusers.models import AutoencoderKL, UNet2DConditionModel
from diffusers.models.attention_processor import AttnProcessor
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import KarrasDiffusionSchedulers
from PIL import Image
from torchvision import transforms
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
from lora_utils import train_lora, load_lora
from diffusers import StableDiffusionPipeline
from argparse import ArgumentParser
from alpha_scheduler import AlphaScheduler | 5,076 | for k in self.unet.attn_processors.keys():
if do_replace_attn(k):
attn_processor_dict[k] = StoreProcessor(self.unet.attn_processors[k],
self.img0_dict, k)
else:
attn_processor_dict[k] = self.unet.attn_processors[k]
self.unet.set_attn_processor(attn_processor_dict)
latents = self.cal_latent(
num_inference_steps,
guidance_scale,
unconditioning,
img_noise_0,
img_noise_1,
text_embeddings_0,
text_embeddings_1,
lora_0,
lora_1,
alpha_list[0],
False,
fix_lora
)
first_image = self.latent2image(latents)
first_image = Image.fromarray(first_image)
if save:
first_image.save(f"{self.output_path}/{0:02d}.png")
self.unet = load_lora(self.unet, lora_0, lora_1, 1 if fix_lora is None else fix_lora)
attn_processor_dict = {}
for k in self.unet.attn_processors.keys():
if do_replace_attn(k):
attn_processor_dict[k] = StoreProcessor(self.unet.attn_processors[k],
self.img1_dict, k)
else:
attn_processor_dict[k] = self.unet.attn_processors[k]
self.unet.set_attn_processor(attn_processor_dict)
latents = self.cal_latent(
num_inference_steps,
guidance_scale,
unconditioning,
img_noise_0,
img_noise_1,
text_embeddings_0,
text_embeddings_1,
lora_0,
lora_1,
alpha_list[-1],
False,
fix_lora
)
last_image = self.latent2image(latents)
last_image = Image.fromarray(last_image)
if save:
last_image.save(
f"{self.output_path}/{num_frames - 1:02d}.png")
for i in progress.tqdm(range(1, num_frames - 1), desc=desc):
alpha = alpha_list[i]
self.unet = load_lora(self.unet, lora_0, lora_1, alpha if fix_lora is None else fix_lora)
attn_processor_dict = {}
for k in self.unet.attn_processors.keys():
if do_replace_attn(k):
attn_processor_dict[k] = LoadProcessor(
self.unet.attn_processors[k], k, self.img0_dict, self.img1_dict, alpha, attn_beta, lamb)
else:
attn_processor_dict[k] = self.unet.attn_processors[k]
self.unet.set_attn_processor(attn_processor_dict)
latents = self.cal_latent(
num_inference_steps,
guidance_scale,
unconditioning,
img_noise_0,
img_noise_1,
text_embeddings_0,
text_embeddings_1,
lora_0,
lora_1,
alpha_list[i],
False,
fix_lora
)
image = self.latent2image(latents)
image = Image.fromarray(image)
if save:
image.save(f"{self.output_path}/{i:02d}.png")
images.append(image)
images = [first_image] + images + [last_image]
else:
for k, alpha in enumerate(alpha_list):
latents = self.cal_latent(
num_inference_steps,
guidance_scale,
unconditioning,
img_noise_0,
img_noise_1,
text_embeddings_0,
text_embeddings_1,
lora_0,
lora_1,
alpha_list[k],
self.use_lora,
fix_lora
)
image = self.latent2image(latents)
image = Image.fromarray(image)
if save:
image.save(f"{self.output_path}/{k:02d}.png")
images.append(image)
return images
with torch.no_grad():
if self.use_reschedule:
|
parser = ArgumentParser()
parser.add_argument(
'--image_path_0', type=str, default='',
help='Path of the image to be processed (default: %(default)s)')
parser.add_argument(
'--prompt_0', type=str, default='',
help='Prompt of the image (default: %(default)s)')
parser.add_argument(
'--image_path_1', type=str, default='',
help='Path of the 2nd image to be processed, used in "morphing" mode (default: %(default)s)')
parser.add_argument(
'--prompt_1', type=str, default='',
help='Prompt of the 2nd image, used in "morphing" mode (default: %(default)s)')
parser.add_argument(
'--output_path', type=str, default='',
help='Path of the output image (default: %(default)s)'
)
parser.add_argument(
'--num_frames', type=int, default=50,
help='Number of frames to generate (default: %(default)s)'
)
parser.add_argument(
'--duration', type=int, default=50,
help='Duration of each frame (default: %(default)s)'
)
parser.add_argument(
'--use_lora', action='store_true',
help='Use LORA to generate images (default: False)'
)
parser.add_argument(
'--guidance_scale', type=float, default=1.,
help='CFG guidace (default: %(default)s)'
)
parser.add_argument(
'--attn_beta', type=float, default=None,
)
parser.add_argument(
'-reschedule', action='store_true',
)
parser.add_argument(
'--lamd', type=float, default=0.6,
)
parser.add_argument(
'--use_adain', action='store_true'
)
args = parser.parse_args()
# name = args.output_path.split('/')[-1]
# attn_beta = args.attn_beta
# num_frames = args.num_frames
# use_alpha_scheduler = args.reschedule
# attn_step = 50 * args.lamd
def calc_mean_std(feat, eps=1e-5):
# eps is a small value added to the variance to avoid divide-by-zero.
size = feat.size()
N, C = size[:2]
feat_var = feat.view(N, C, -1).var(dim=2) + eps
if len(size) == 3:
feat_std = feat_var.sqrt().view(N, C, 1)
feat_mean = feat.view(N, C, -1).mean(dim=2).view(N, C, 1)
else:
feat_std = feat_var.sqrt().view(N, C, 1, 1)
feat_mean = feat.view(N, C, -1).mean(dim=2).view(N, C, 1, 1)
return feat_mean, feat_std
def get_img(img, resolution=512):
norm_mean = [0.5, 0.5, 0.5]
norm_std = [0.5, 0.5, 0.5]
transform = transforms.Compose([
transforms.Resize((resolution, resolution)),
transforms.ToTensor(),
transforms.Normalize(norm_mean, norm_std)
])
img = transform(img)
return img.unsqueeze(0)
@torch.no_grad()
def slerp(p0, p1, fract_mixing: float, adain=True):
r""" Copied from lunarring/latentblending
Helper function to correctly mix two random variables using spherical interpolation.
The function will always cast up to float64 for sake of extra 4.
Args:
p0:
First tensor for interpolation
p1:
Second tensor for interpolation
fract_mixing: float
Mixing coefficient of interval [0, 1].
0 will return in p0
1 will return in p1
0.x will return a mix between both preserving angular velocity.
"""
if p0.dtype == torch.float16:
recast_to = 'fp16'
else:
recast_to = 'fp32'
p0 = p0.double()
p1 = p1.double()
if adain:
mean1, std1 = calc_mean_std(p0)
mean2, std2 = calc_mean_std(p1)
mean = mean1 * (1 - fract_mixing) + mean2 * fract_mixing
std = std1 * (1 - fract_mixing) + std2 * fract_mixing
norm = torch.linalg.norm(p0) * torch.linalg.norm(p1)
epsilon = 1e-7
dot = torch.sum(p0 * p1) / norm
dot = dot.clamp(-1+epsilon, 1-epsilon)
theta_0 = torch.arccos(dot)
sin_theta_0 = torch.sin(theta_0)
theta_t = theta_0 * fract_mixing
s0 = torch.sin(theta_0 - theta_t) / sin_theta_0
s1 = torch.sin(theta_t) / sin_theta_0
interp = p0*s0 + p1*s1
if adain:
interp = F.instance_norm(interp) * std + mean
if recast_to == 'fp16':
interp = interp.half()
elif recast_to == 'fp32':
interp = interp.float()
return interp
def do_replace_attn(key: str):
# return key.startswith('up_blocks.2') or key.startswith('up_blocks.3')
return key.startswith('up')
class StoreProcessor():
def __init__(self, original_processor, value_dict, name):
self.original_processor = original_processor
self.value_dict = value_dict
self.name = name
self.value_dict[self.name] = dict()
self.id = 0
def __call__(self, attn, hidden_states, *args, encoder_hidden_states=None, attention_mask=None, **kwargs):
# Is self attention
if encoder_hidden_states is None:
self.value_dict[self.name][self.id] = hidden_states.detach()
self.id += 1
res = self.original_processor(attn, hidden_states, *args,
encoder_hidden_states=encoder_hidden_states,
attention_mask=attention_mask,
**kwargs)
return res
class LoadProcessor():
def __init__(self, original_processor, name, img0_dict, img1_dict, alpha, beta=0, lamb=0.6):
super().__init__()
self.original_processor = original_processor
self.name = name
self.img0_dict = img0_dict
self.img1_dict = img1_dict
self.alpha = alpha
self.beta = beta
self.lamb = lamb
self.id = 0
def parent_call(
self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, scale=1.0
):
residual = hidden_states
if attn.spatial_norm is not None:
hidden_states = attn.spatial_norm(hidden_states)
input_ndim = hidden_states.ndim
if input_ndim == 4:
batch_size, channel, height, width = hidden_states.shape
hidden_states = hidden_states.view(
batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = (
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
)
attention_mask = attn.prepare_attention_mask(
attention_mask, sequence_length, batch_size)
if attn.group_norm is not None:
hidden_states = attn.group_norm(
hidden_states.transpose(1, 2)).transpose(1, 2)
query = attn.to_q(hidden_states) + scale * \
self.original_processor.to_q_lora(hidden_states)
query = attn.head_to_batch_dim(query)
if encoder_hidden_states is None:
encoder_hidden_states = hidden_states
elif attn.norm_cross:
encoder_hidden_states = attn.norm_encoder_hidden_states(
encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) + scale * \
self.original_processor.to_k_lora(encoder_hidden_states)
value = attn.to_v(encoder_hidden_states) + scale * \
self.original_processor.to_v_lora(encoder_hidden_states)
key = attn.head_to_batch_dim(key)
value = attn.head_to_batch_dim(value)
attention_probs = attn.get_attention_scores(
query, key, attention_mask)
hidden_states = torch.bmm(attention_probs, value)
hidden_states = attn.batch_to_head_dim(hidden_states)
# linear proj
hidden_states = attn.to_out[0](
hidden_states) + scale * self.original_processor.to_out_lora(hidden_states)
# dropout
hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4:
hidden_states = hidden_states.transpose(
-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection:
hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states
def __call__(self, attn, hidden_states, *args, encoder_hidden_states=None, attention_mask=None, **kwargs):
# Is self attention
if encoder_hidden_states is None:
# hardcode timestep
if self.id < 50 * self.lamb:
map0 = self.img0_dict[self.name][self.id]
map1 = self.img1_dict[self.name][self.id]
cross_map = self.beta * hidden_states + \
(1 - self.beta) * ((1 - self.alpha) * map0 + self.alpha * map1)
# cross_map = self.beta * hidden_states + \
# (1 - self.beta) * slerp(map0, map1, self.alpha)
# cross_map = slerp(slerp(map0, map1, self.alpha),
# hidden_states, self.beta)
# cross_map = hidden_states
# cross_map = torch.cat(
# ((1 - self.alpha) * map0, self.alpha * map1), dim=1)
# res = self.original_processor(attn, hidden_states, *args,
# encoder_hidden_states=cross_map,
# attention_mask=attention_mask,
# temb=temb, **kwargs)
res = self.parent_call(attn, hidden_states, *args,
encoder_hidden_states=cross_map,
attention_mask=attention_mask,
**kwargs)
else:
res = self.original_processor(attn, hidden_states, *args,
encoder_hidden_states=encoder_hidden_states,
attention_mask=attention_mask,
**kwargs)
self.id += 1
# if self.id == len(self.img0_dict[self.name]):
if self.id == len(self.img0_dict[self.name]):
self.id = 0
else:
res = self.original_processor(attn, hidden_states, *args,
encoder_hidden_states=encoder_hidden_states,
attention_mask=attention_mask,
**kwargs)
return res
class DiffMorpherPipeline(StableDiffusionPipeline):
def __init__(self,
vae: AutoencoderKL,
text_encoder: CLIPTextModel,
tokenizer: CLIPTokenizer,
unet: UNet2DConditionModel,
scheduler: KarrasDiffusionSchedulers,
safety_checker: StableDiffusionSafetyChecker,
feature_extractor: CLIPImageProcessor,
requires_safety_checker: bool = True,
):
super().__init__(vae, text_encoder, tokenizer, unet, scheduler,
safety_checker, feature_extractor, requires_safety_checker)
self.img0_dict = dict()
self.img1_dict = dict()
def inv_step(
self,
model_output: torch.FloatTensor,
timestep: int,
x: torch.FloatTensor,
eta=0.,
verbose=False
):
"""
Inverse sampling for DDIM Inversion
"""
if verbose:
print("timestep: ", timestep)
next_step = timestep
timestep = min(timestep - self.scheduler.config.num_train_timesteps //
self.scheduler.num_inference_steps, 999)
alpha_prod_t = self.scheduler.alphas_cumprod[
timestep] if timestep >= 0 else self.scheduler.final_alpha_cumprod
alpha_prod_t_next = self.scheduler.alphas_cumprod[next_step]
beta_prod_t = 1 - alpha_prod_t
pred_x0 = (x - beta_prod_t**0.5 * model_output) / alpha_prod_t**0.5
pred_dir = (1 - alpha_prod_t_next)**0.5 * model_output
x_next = alpha_prod_t_next**0.5 * pred_x0 + pred_dir
return x_next, pred_x0
@torch.no_grad()
def invert(
self,
image: torch.Tensor,
prompt,
num_inference_steps=50,
num_actual_inference_steps=None,
guidance_scale=1.,
eta=0.0,
**kwds):
"""
invert a real image into noise map with determinisc DDIM inversion
"""
DEVICE = torch.device(
"cuda") if torch.cuda.is_available() else torch.device("cpu")
batch_size = image.shape[0]
if isinstance(prompt, list):
if batch_size == 1:
image = image.expand(len(prompt), -1, -1, -1)
elif isinstance(prompt, str):
if batch_size > 1:
prompt = [prompt] * batch_size
# text embeddings
text_input = self.tokenizer(
prompt,
padding="max_length",
max_length=77,
return_tensors="pt"
)
text_embeddings = self.text_encoder(text_input.input_ids.to(DEVICE))[0]
print("input text embeddings :", text_embeddings.shape)
# define initial latents
latents = self.image2latent(image)
# unconditional embedding for classifier free guidance
if guidance_scale > 1.:
max_length = text_input.input_ids.shape[-1]
unconditional_input = self.tokenizer(
[""] * batch_size,
padding="max_length",
max_length=77,
return_tensors="pt"
)
unconditional_embeddings = self.text_encoder(
unconditional_input.input_ids.to(DEVICE))[0]
text_embeddings = torch.cat(
[unconditional_embeddings, text_embeddings], dim=0)
print("latents shape: ", latents.shape)
# interative sampling
self.scheduler.set_timesteps(num_inference_steps)
print("Valid timesteps: ", reversed(self.scheduler.timesteps))
# print("attributes: ", self.scheduler.__dict__)
latents_list = [latents]
pred_x0_list = [latents]
for i, t in enumerate(tqdm.tqdm(reversed(self.scheduler.timesteps), desc="DDIM Inversion")):
if num_actual_inference_steps is not None and i >= num_actual_inference_steps:
continue
if guidance_scale > 1.:
model_inputs = torch.cat([latents] * 2)
else:
model_inputs = latents
# predict the noise
noise_pred = self.unet(
model_inputs, t, encoder_hidden_states=text_embeddings).sample
if guidance_scale > 1.:
noise_pred_uncon, noise_pred_con = noise_pred.chunk(2, dim=0)
noise_pred = noise_pred_uncon + guidance_scale * \
(noise_pred_con - noise_pred_uncon)
# compute the previous noise sample x_t-1 -> x_t
latents, pred_x0 = self.inv_step(noise_pred, t, latents)
latents_list.append(latents)
pred_x0_list.append(pred_x0)
return latents
@torch.no_grad()
def ddim_inversion(self, latent, cond):
timesteps = reversed(self.scheduler.timesteps)
with torch.autocast(device_type='cuda', dtype=torch.float32):
for i, t in enumerate(tqdm.tqdm(timesteps, desc="DDIM inversion")):
cond_batch = cond.repeat(latent.shape[0], 1, 1)
alpha_prod_t = self.scheduler.alphas_cumprod[t]
alpha_prod_t_prev = (
self.scheduler.alphas_cumprod[timesteps[i - 1]]
if i > 0 else self.scheduler.final_alpha_cumprod
)
mu = alpha_prod_t ** 0.5
mu_prev = alpha_prod_t_prev ** 0.5
sigma = (1 - alpha_prod_t) ** 0.5
sigma_prev = (1 - alpha_prod_t_prev) ** 0.5
eps = self.unet(
latent, t, encoder_hidden_states=cond_batch).sample
pred_x0 = (latent - sigma_prev * eps) / mu_prev
latent = mu * pred_x0 + sigma * eps
# if save_latents:
# torch.save(latent, os.path.join(save_path, f'noisy_latents_{t}.pt'))
# torch.save(latent, os.path.join(save_path, f'noisy_latents_{t}.pt'))
return latent
def step(
self,
model_output: torch.FloatTensor,
timestep: int,
x: torch.FloatTensor,
):
"""
predict the sample of the next step in the denoise process.
"""
prev_timestep = timestep - \
self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
alpha_prod_t = self.scheduler.alphas_cumprod[timestep]
alpha_prod_t_prev = self.scheduler.alphas_cumprod[
prev_timestep] if prev_timestep > 0 else self.scheduler.final_alpha_cumprod
beta_prod_t = 1 - alpha_prod_t
pred_x0 = (x - beta_prod_t**0.5 * model_output) / alpha_prod_t**0.5
pred_dir = (1 - alpha_prod_t_prev)**0.5 * model_output
x_prev = alpha_prod_t_prev**0.5 * pred_x0 + pred_dir
return x_prev, pred_x0
@torch.no_grad()
def image2latent(self, image):
DEVICE = torch.device(
"cuda") if torch.cuda.is_available() else torch.device("cpu")
if type(image) is Image:
image = np.array(image)
image = torch.from_numpy(image).float() / 127.5 - 1
image = image.permute(2, 0, 1).unsqueeze(0)
# input image density range [-1, 1]
latents = self.vae.encode(image.to(DEVICE))['latent_dist'].mean
latents = latents * 0.18215
return latents
@torch.no_grad()
def latent2image(self, latents, return_type='np'):
latents = 1 / 0.18215 * latents.detach()
image = self.vae.decode(latents)['sample']
if return_type == 'np':
image = (image / 2 + 0.5).clamp(0, 1)
image = image.cpu().permute(0, 2, 3, 1).numpy()[0]
image = (image * 255).astype(np.uint8)
elif return_type == "pt":
image = (image / 2 + 0.5).clamp(0, 1)
return image
def latent2image_grad(self, latents):
latents = 1 / 0.18215 * latents
image = self.vae.decode(latents)['sample']
return image # range [-1, 1]
@torch.no_grad()
def cal_latent(self, num_inference_steps, guidance_scale, unconditioning, img_noise_0, img_noise_1, text_embeddings_0, text_embeddings_1, lora_0, lora_1, alpha, use_lora, fix_lora=None):
# latents = torch.cos(alpha * torch.pi / 2) * img_noise_0 + \
# torch.sin(alpha * torch.pi / 2) * img_noise_1
# latents = (1 - alpha) * img_noise_0 + alpha * img_noise_1
# latents = latents / ((1 - alpha) ** 2 + alpha ** 2)
latents = slerp(img_noise_0, img_noise_1, alpha, self.use_adain)
text_embeddings = (1 - alpha) * text_embeddings_0 + \
alpha * text_embeddings_1
self.scheduler.set_timesteps(num_inference_steps)
if use_lora:
if fix_lora is not None:
self.unet = load_lora(self.unet, lora_0, lora_1, fix_lora)
else:
self.unet = load_lora(self.unet, lora_0, lora_1, alpha)
for i, t in enumerate(tqdm.tqdm(self.scheduler.timesteps, desc=f"DDIM Sampler, alpha={alpha}")):
if guidance_scale > 1.:
model_inputs = torch.cat([latents] * 2)
else:
model_inputs = latents
if unconditioning is not None and isinstance(unconditioning, list):
_, text_embeddings = text_embeddings.chunk(2)
text_embeddings = torch.cat(
[unconditioning[i].expand(*text_embeddings.shape), text_embeddings])
# predict the noise
noise_pred = self.unet(
model_inputs, t, encoder_hidden_states=text_embeddings).sample
if guidance_scale > 1.0:
noise_pred_uncon, noise_pred_con = noise_pred.chunk(
2, dim=0)
noise_pred = noise_pred_uncon + guidance_scale * \
(noise_pred_con - noise_pred_uncon)
# compute the previous noise sample x_t -> x_t-1
# YUJUN: right now, the only difference between step here and step in scheduler
# is that scheduler version would clamp pred_x0 between [-1,1]
# don't know if that's gonna have huge impact
latents = self.scheduler.step(
noise_pred, t, latents, return_dict=False)[0]
return latents
@torch.no_grad()
def get_text_embeddings(self, prompt, guidance_scale, neg_prompt, batch_size):
DEVICE = torch.device(
"cuda") if torch.cuda.is_available() else torch.device("cpu")
# text embeddings
text_input = self.tokenizer(
prompt,
padding="max_length",
max_length=77,
return_tensors="pt"
)
text_embeddings = self.text_encoder(text_input.input_ids.cuda())[0]
if guidance_scale > 1.:
if neg_prompt:
uc_text = neg_prompt
else:
uc_text = ""
unconditional_input = self.tokenizer(
[uc_text] * batch_size,
padding="max_length",
max_length=77,
return_tensors="pt"
)
unconditional_embeddings = self.text_encoder(
unconditional_input.input_ids.to(DEVICE))[0]
text_embeddings = torch.cat(
[unconditional_embeddings, text_embeddings], dim=0)
return text_embeddings
def __call__(
self,
img_0=None,
img_1=None,
img_path_0=None,
img_path_1=None,
prompt_0="",
prompt_1="",
save_lora_dir="./lora",
load_lora_path_0=None,
load_lora_path_1=None,
lora_steps=200,
lora_lr=2e-4,
lora_rank=16,
batch_size=1,
height=512,
width=512,
num_inference_steps=50,
num_actual_inference_steps=None,
guidance_scale=1,
attn_beta=0,
lamb=0.6,
use_lora = True,
use_adain = True,
use_reschedule = True,
output_path = "./results",
num_frames=50,
fix_lora=None,
progress=tqdm,
unconditioning=None,
neg_prompt=None,
**kwds):
# if isinstance(prompt, list):
# batch_size = len(prompt)
# elif isinstance(prompt, str):
# if batch_size > 1:
# prompt = [prompt] * batch_size
self.scheduler.set_timesteps(num_inference_steps)
self.use_lora = use_lora
self.use_adain = use_adain
self.use_reschedule = use_reschedule
self.output_path = output_path
if img_0 is None:
img_0 = Image.open(img_path_0).convert("RGB")
# else:
# img_0 = Image.fromarray(img_0).convert("RGB")
if img_1 is None:
img_1 = Image.open(img_path_1).convert("RGB")
# else:
# img_1 = Image.fromarray(img_1).convert("RGB")
if self.use_lora:
print("Loading lora...")
if not load_lora_path_0:
weight_name = f"{output_path.split('/')[-1]}_lora_0.ckpt"
load_lora_path_0 = save_lora_dir + "/" + weight_name
if not os.path.exists(load_lora_path_0):
train_lora(img_0, prompt_0, save_lora_dir, None, self.tokenizer, self.text_encoder,
self.vae, self.unet, self.scheduler, lora_steps, lora_lr, lora_rank, weight_name=weight_name)
print(f"Load from {load_lora_path_0}.")
if load_lora_path_0.endswith(".safetensors"):
lora_0 = safetensors.torch.load_file(
load_lora_path_0, device="cpu")
else:
lora_0 = torch.load(load_lora_path_0, map_location="cpu")
if not load_lora_path_1:
weight_name = f"{output_path.split('/')[-1]}_lora_1.ckpt"
load_lora_path_1 = save_lora_dir + "/" + weight_name
if not os.path.exists(load_lora_path_1):
train_lora(img_1, prompt_1, save_lora_dir, None, self.tokenizer, self.text_encoder,
self.vae, self.unet, self.scheduler, lora_steps, lora_lr, lora_rank, weight_name=weight_name)
print(f"Load from {load_lora_path_1}.")
if load_lora_path_1.endswith(".safetensors"):
lora_1 = safetensors.torch.load_file(
load_lora_path_1, device="cpu")
else:
lora_1 = torch.load(load_lora_path_1, map_location="cpu")
text_embeddings_0 = self.get_text_embeddings(
prompt_0, guidance_scale, neg_prompt, batch_size)
text_embeddings_1 = self.get_text_embeddings(
prompt_1, guidance_scale, neg_prompt, batch_size)
img_0 = get_img(img_0)
img_1 = get_img(img_1)
if self.use_lora:
self.unet = load_lora(self.unet, lora_0, lora_1, 0)
img_noise_0 = self.ddim_inversion(
self.image2latent(img_0), text_embeddings_0)
if self.use_lora:
self.unet = load_lora(self.unet, lora_0, lora_1, 1)
img_noise_1 = self.ddim_inversion(
self.image2latent(img_1), text_embeddings_1)
print("latents shape: ", img_noise_0.shape)
def morph(alpha_list, progress, desc, save=False):
images = []
if attn_beta is not None:
self.unet = load_lora(self.unet, lora_0, lora_1, 0 if fix_lora is None else fix_lora)
attn_processor_dict = {}
for k in self.unet.attn_processors.keys():
if do_replace_attn(k):
attn_processor_dict[k] = StoreProcessor(self.unet.attn_processors[k],
self.img0_dict, k)
else:
attn_processor_dict[k] = self.unet.attn_processors[k]
self.unet.set_attn_processor(attn_processor_dict)
latents = self.cal_latent(
num_inference_steps,
guidance_scale,
unconditioning,
img_noise_0,
img_noise_1,
text_embeddings_0,
text_embeddings_1,
lora_0,
lora_1,
alpha_list[0],
False,
fix_lora
)
first_image = self.latent2image(latents)
first_image = Image.fromarray(first_image)
if save:
first_image.save(f"{self.output_path}/{0:02d}.png")
self.unet = load_lora(self.unet, lora_0, lora_1, 1 if fix_lora is None else fix_lora)
attn_processor_dict = {}
for k in self.unet.attn_processors.keys():
if do_replace_attn(k):
attn_processor_dict[k] = StoreProcessor(self.unet.attn_processors[k],
self.img1_dict, k)
else:
attn_processor_dict[k] = self.unet.attn_processors[k]
self.unet.set_attn_processor(attn_processor_dict)
latents = self.cal_latent(
num_inference_steps,
guidance_scale,
unconditioning,
img_noise_0,
img_noise_1,
text_embeddings_0,
text_embeddings_1,
lora_0,
lora_1,
alpha_list[-1],
False,
fix_lora
)
last_image = self.latent2image(latents)
last_image = Image.fromarray(last_image)
if save:
last_image.save(
f"{self.output_path}/{num_frames - 1:02d}.png")
for i in progress.tqdm(range(1, num_frames - 1), desc=desc):
alpha = alpha_list[i]
self.unet = load_lora(self.unet, lora_0, lora_1, alpha if fix_lora is None else fix_lora)
attn_processor_dict = {}
for k in self.unet.attn_processors.keys():
if do_replace_attn(k):
attn_processor_dict[k] = LoadProcessor(
self.unet.attn_processors[k], k, self.img0_dict, self.img1_dict, alpha, attn_beta, lamb)
else:
attn_processor_dict[k] = self.unet.attn_processors[k]
self.unet.set_attn_processor(attn_processor_dict)
latents = self.cal_latent(
num_inference_steps,
guidance_scale,
unconditioning,
img_noise_0,
img_noise_1,
text_embeddings_0,
text_embeddings_1,
lora_0,
lora_1,
alpha_list[i],
False,
fix_lora
)
image = self.latent2image(latents)
image = Image.fromarray(image)
if save:
image.save(f"{self.output_path}/{i:02d}.png")
images.append(image)
images = [first_image] + images + [last_image]
else:
for k, alpha in enumerate(alpha_list):
latents = self.cal_latent(
num_inference_steps,
guidance_scale,
unconditioning,
img_noise_0,
img_noise_1,
text_embeddings_0,
text_embeddings_1,
lora_0,
lora_1,
alpha_list[k],
self.use_lora,
fix_lora
)
image = self.latent2image(latents)
image = Image.fromarray(image)
if save:
image.save(f"{self.output_path}/{k:02d}.png")
images.append(image)
return images
with torch.no_grad():
if self.use_reschedule: | alpha_scheduler = AlphaScheduler() | 2 | 2023-12-25 04:51:41+00:00 | 8k |
camenduru/AnyDoor-online-hf | app.py | [
{
"identifier": "create_model",
"path": "cldm/model.py",
"snippet": "def create_model(config_path):\n config = OmegaConf.load(config_path)\n model = instantiate_from_config(config.model).cpu()\n print(f'Loaded model config from [{config_path}]')\n return model"
},
{
"identifier": "lo... | import os
import sys
import cv2
import einops
import numpy as np
import torch
import random
import gradio as gr
import albumentations as A
import torchvision.transforms as T
from PIL import Image
from mydatasets.data_utils import *
from cldm.model import create_model, load_state_dict
from cldm.ddim_hacked import DDIMSampler
from omegaconf import OmegaConf
from cldm.hack import disable_verbosity, enable_sliced_attention
from huggingface_hub import snapshot_download
from iseg.coarse_mask_refine_util import BaselineModel | 4,411 | #sys.path.append('.')
snapshot_download(repo_id="xichenhku/AnyDoor_models", local_dir="./AnyDoor_models")
snapshot_download(repo_id="xichenhku/mask_refine", local_dir="./mask_refine")
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
save_memory = False
disable_verbosity()
if save_memory:
enable_sliced_attention()
config = OmegaConf.load('./configs/demo.yaml')
model_ckpt = config.pretrained_model
model_config = config.config_file
use_interactive_seg = config.config_file
model = create_model(model_config ).cpu()
model.load_state_dict(load_state_dict(model_ckpt, location='cuda'))
model = model.cuda()
| #sys.path.append('.')
snapshot_download(repo_id="xichenhku/AnyDoor_models", local_dir="./AnyDoor_models")
snapshot_download(repo_id="xichenhku/mask_refine", local_dir="./mask_refine")
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
save_memory = False
disable_verbosity()
if save_memory:
enable_sliced_attention()
config = OmegaConf.load('./configs/demo.yaml')
model_ckpt = config.pretrained_model
model_config = config.config_file
use_interactive_seg = config.config_file
model = create_model(model_config ).cpu()
model.load_state_dict(load_state_dict(model_ckpt, location='cuda'))
model = model.cuda() | ddim_sampler = DDIMSampler(model) | 2 | 2023-12-25 04:48:34+00:00 | 8k |
pangxincheng/TaskManager | task_manager/manager/core.py | [
{
"identifier": "GPUManager",
"path": "task_manager/manager/gpu.py",
"snippet": "class GPUManager(mp.Process):\n\n def __init__(\n self,\n identity: str,\n device_id: int,\n gpu_manager_addr: str\n ) -> None:\n mp.Process.__init__(self, daemon=True)\n asse... | import os
import time
import multiprocessing as mp
import pycuda.driver as pycuda_drv
import task_manager.utils.zmq_utils as zmq_utils
import task_manager.utils.common_utils as common_utils
from typing import Dict, List, Any
from task_manager.manager.gpu import GPUManager
from task_manager.manager.task import TaskManager | 6,008 | )
identity_, msg = self._task_manager.recv_binary()
identity_ = identity_.decode("utf-8")
msg = common_utils.byte_msg_to_dict(msg)
assert identity == identity_, "identity mismatch"
return_msg["watched_tasks"][identity] = msg
return {
"status": 200,
"result": {
"msg": "👋bye~",
"watched_gpus": return_msg
}
}
def get_gpus_info_by_identities(self, identities: List[str], info_level: str="simple") -> Dict[str, Any]:
if len(identities) == 0:
identities = list(self.watched_gpus.keys())
assert len(identities) == len(set(identities)), "identities should not contain duplicate elements"
return_msg = {}
for identity in identities:
if identity not in self.watched_gpus.keys():
return_msg[identity] = {
"status": 400,
"result": f"Could not find a watch dog with identity {identity}"
}
else:
self._gpu_manager.send_binary(
any=common_utils.dict_to_byte_msg({
"function": "get_gpu_info",
"kwargs": {
"info_level": info_level
}
}),
identity=identity
)
identity_, msg = self._gpu_manager.recv_binary()
identity_ = identity_.decode("utf-8")
msg = common_utils.byte_msg_to_dict(msg)
assert identity == identity_, "identity mismatch"
return_msg[identity] = msg
return {
"status": 200,
"result": return_msg
}
def get_gpus_info_by_device_ids(self, device_ids: List[int], info_level: str="simple") -> Dict[str, Any]:
if len(device_ids) == 0:
device_ids = list(range(pycuda_drv.Device.count()))
assert len(device_ids) == len(set(device_ids)), "device_ids should not contain duplicate elements"
assert all([device_id >= 0 and device_id < pycuda_drv.Device.count() for device_id in device_ids]), \
"The device_id should be in the valid range"
watched_gpu_device_ids = {
self.watched_gpus[identity]["device_id"]: identity
for identity in self.watched_gpus.keys()
if self.watched_gpus[identity]["device_id"] in device_ids
}
unwatched_gpus = sorted(list(set(device_ids) - watched_gpu_device_ids.keys()))
return_msg = {}
for device_id in watched_gpu_device_ids.keys():
identity = watched_gpu_device_ids[device_id]
self._gpu_manager.send_binary(
any=common_utils.dict_to_byte_msg({
"function": "get_gpu_info",
"kwargs": {
"info_level": info_level
}
}),
identity=identity
)
identity_, msg = self._gpu_manager.recv_binary()
identity_ = identity_.decode("utf-8")
msg = common_utils.byte_msg_to_dict(msg)
assert identity == identity_, "identity mismatch"
return_msg[identity] = msg
return_msg["unwatched"] = []
for device_id in unwatched_gpus:
gpu_device = pycuda_drv.Device(device_id)
device_msg = {
"device_id": device_id,
"device_name": gpu_device.name(),
"total_memory": common_utils.fmt_bytes(gpu_device.total_memory()),
"compute_capability": float("%d.%d" % gpu_device.compute_capability()),
}
if info_level != "simple":
device_attributes_tuples = gpu_device.get_attributes().items()
device_attributes = {}
for k, v in device_attributes_tuples:
device_attributes[str(k)] = v
device_msg["device_attributes"] = device_attributes
return_msg["unwatched"].append(device_msg)
return {
"status": 200,
"result": return_msg
}
def start_watch_dog_by_device_ids(self, device_ids: List[int]) -> Dict[str, Any]:
assert len(device_ids) > 0, "device_ids should not be empty"
assert len(device_ids) == len(set(device_ids)), "device_ids should not contain duplicate elements"
assert all([device_id >= 0 and device_id < pycuda_drv.Device.count() for device_id in device_ids]), \
"The device_id should be in the valid range"
watched_gpu_device_ids = {
self.watched_gpus[identity]["device_id"]: identity
for identity in self.watched_gpus.keys()
if self.watched_gpus[identity]["device_id"] in device_ids
}
return_msg = {}
for device_id in device_ids:
if device_id in watched_gpu_device_ids.keys():
return_msg[watched_gpu_device_ids[device_id]] = {
"status": 400,
"result": f"GPU{device_id} is already being watched by {watched_gpu_device_ids[device_id]}"
}
else:
timestamp = str(time.time())
identity = common_utils.md5(f"watch_dog_{device_id}_{timestamp}")
|
class CoreManager(mp.Process):
def __init__(
self,
core_manager_addr: str,
gpu_manager_addr: str="ipc://gpu_manager",
task_manager_addr: str="ipc://task_manager",
log_dir: str="logs",
log_level: str="INFO",
) -> None:
mp.Process.__init__(self)
assert core_manager_addr.startswith("tcp://") or core_manager_addr.startswith("ipc://"), \
"core manager address must start with tcp:// or ipc://"
assert gpu_manager_addr.startswith("tcp://") or gpu_manager_addr.startswith("ipc://"), \
"gpu manager address must start with tcp:// or ipc://"
assert task_manager_addr.startswith("tcp://") or task_manager_addr.startswith("ipc://"), \
"task manager address must start with tcp:// or ipc://"
self.core_manager_addr = core_manager_addr
self.gpu_manager_addr = gpu_manager_addr
self.task_manager_addr = task_manager_addr
self.log_dir = log_dir
self.log_level = log_level
def _init_manager(self) -> None:
self.logger = common_utils.get_logger(
logger_name="core_manager",
log_level=self.log_level,
handler=os.path.join(self.log_dir, "core_manager.log")
)
self.logger.info(f"CoreManager is listening on {self.core_manager_addr}")
self._core_manager = zmq_utils.ZMQServer(
addr=self.core_manager_addr,
)
time.sleep(1)
self.logger.info(f"GPUManager is listening on {self.gpu_manager_addr}")
self._gpu_manager = zmq_utils.ZMQServer(
addr=self.gpu_manager_addr,
)
self.logger.info(f"TaskManager is listening on {self.task_manager_addr}")
self._task_manager = zmq_utils.ZMQServer(
addr=self.task_manager_addr,
)
self.watched_gpus = {}
self.watched_tasks = {}
pycuda_drv.init()
self.running = True
def run(self) -> None:
self._init_manager()
while self.running:
identity, msg = self._core_manager.recv_binary()
command = common_utils.byte_msg_to_dict(msg)
self.logger.info(f"receive command to call {command['function']}")
return_msg = self.exception_wrapper(
fn=getattr(self, command["function"], self._default_fn),
*command.get("args", {}),
**command.get("kwargs", {})
)
self._core_manager.send_binary(
any=common_utils.dict_to_byte_msg(return_msg),
identity=identity
)
def exception_wrapper(self, fn, *args, **kwargs) -> Dict[str, Any]:
try:
return fn(*args, **kwargs)
except Exception as e:
self.logger.error(f"Exception when call {fn.__name__}")
self.logger.exception(e)
return {
"status": 400,
"result": f"Exception when call {fn.__name__}, the excption is " + str(e)
}
def _default_fn(self, *args, **kwargs) -> None:
raise NotImplementedError("This function is not implemented")
def exit(self) -> Dict[str, Any]:
self.logger.info("=> [info] exit core server...")
self.running = False
return_msg = {
"watched_gpus": {},
"watched_tasks": {}
}
for identity in self.watched_gpus.keys():
self._gpu_manager.send_binary(
any=common_utils.dict_to_byte_msg({
"function": "exit"
}),
identity=identity
)
identity_, msg = self._gpu_manager.recv_binary()
identity_ = identity_.decode("utf-8")
msg = common_utils.byte_msg_to_dict(msg)
assert identity == identity_, "identity mismatch"
return_msg["watched_gpus"][identity] = msg
for identity in self.watched_tasks.keys():
self._task_manager.send_binary(
any=common_utils.dict_to_byte_msg({
"function": "exit"
}),
identity=identity
)
identity_, msg = self._task_manager.recv_binary()
identity_ = identity_.decode("utf-8")
msg = common_utils.byte_msg_to_dict(msg)
assert identity == identity_, "identity mismatch"
return_msg["watched_tasks"][identity] = msg
return {
"status": 200,
"result": {
"msg": "👋bye~",
"watched_gpus": return_msg
}
}
def get_gpus_info_by_identities(self, identities: List[str], info_level: str="simple") -> Dict[str, Any]:
if len(identities) == 0:
identities = list(self.watched_gpus.keys())
assert len(identities) == len(set(identities)), "identities should not contain duplicate elements"
return_msg = {}
for identity in identities:
if identity not in self.watched_gpus.keys():
return_msg[identity] = {
"status": 400,
"result": f"Could not find a watch dog with identity {identity}"
}
else:
self._gpu_manager.send_binary(
any=common_utils.dict_to_byte_msg({
"function": "get_gpu_info",
"kwargs": {
"info_level": info_level
}
}),
identity=identity
)
identity_, msg = self._gpu_manager.recv_binary()
identity_ = identity_.decode("utf-8")
msg = common_utils.byte_msg_to_dict(msg)
assert identity == identity_, "identity mismatch"
return_msg[identity] = msg
return {
"status": 200,
"result": return_msg
}
def get_gpus_info_by_device_ids(self, device_ids: List[int], info_level: str="simple") -> Dict[str, Any]:
if len(device_ids) == 0:
device_ids = list(range(pycuda_drv.Device.count()))
assert len(device_ids) == len(set(device_ids)), "device_ids should not contain duplicate elements"
assert all([device_id >= 0 and device_id < pycuda_drv.Device.count() for device_id in device_ids]), \
"The device_id should be in the valid range"
watched_gpu_device_ids = {
self.watched_gpus[identity]["device_id"]: identity
for identity in self.watched_gpus.keys()
if self.watched_gpus[identity]["device_id"] in device_ids
}
unwatched_gpus = sorted(list(set(device_ids) - watched_gpu_device_ids.keys()))
return_msg = {}
for device_id in watched_gpu_device_ids.keys():
identity = watched_gpu_device_ids[device_id]
self._gpu_manager.send_binary(
any=common_utils.dict_to_byte_msg({
"function": "get_gpu_info",
"kwargs": {
"info_level": info_level
}
}),
identity=identity
)
identity_, msg = self._gpu_manager.recv_binary()
identity_ = identity_.decode("utf-8")
msg = common_utils.byte_msg_to_dict(msg)
assert identity == identity_, "identity mismatch"
return_msg[identity] = msg
return_msg["unwatched"] = []
for device_id in unwatched_gpus:
gpu_device = pycuda_drv.Device(device_id)
device_msg = {
"device_id": device_id,
"device_name": gpu_device.name(),
"total_memory": common_utils.fmt_bytes(gpu_device.total_memory()),
"compute_capability": float("%d.%d" % gpu_device.compute_capability()),
}
if info_level != "simple":
device_attributes_tuples = gpu_device.get_attributes().items()
device_attributes = {}
for k, v in device_attributes_tuples:
device_attributes[str(k)] = v
device_msg["device_attributes"] = device_attributes
return_msg["unwatched"].append(device_msg)
return {
"status": 200,
"result": return_msg
}
def start_watch_dog_by_device_ids(self, device_ids: List[int]) -> Dict[str, Any]:
assert len(device_ids) > 0, "device_ids should not be empty"
assert len(device_ids) == len(set(device_ids)), "device_ids should not contain duplicate elements"
assert all([device_id >= 0 and device_id < pycuda_drv.Device.count() for device_id in device_ids]), \
"The device_id should be in the valid range"
watched_gpu_device_ids = {
self.watched_gpus[identity]["device_id"]: identity
for identity in self.watched_gpus.keys()
if self.watched_gpus[identity]["device_id"] in device_ids
}
return_msg = {}
for device_id in device_ids:
if device_id in watched_gpu_device_ids.keys():
return_msg[watched_gpu_device_ids[device_id]] = {
"status": 400,
"result": f"GPU{device_id} is already being watched by {watched_gpu_device_ids[device_id]}"
}
else:
timestamp = str(time.time())
identity = common_utils.md5(f"watch_dog_{device_id}_{timestamp}") | watchdog = GPUManager( | 0 | 2023-12-30 11:47:06+00:00 | 8k |
yixinNB/pyscrcpy | pyscrcpy/core.py | [
{
"identifier": "EVENT_DISCONNECT",
"path": "pyscrcpy/const.py",
"snippet": "EVENT_DISCONNECT = \"disconnect\""
},
{
"identifier": "EVENT_FRAME",
"path": "pyscrcpy/const.py",
"snippet": "EVENT_FRAME = \"frame\""
},
{
"identifier": "EVENT_INIT",
"path": "pyscrcpy/const.py",
... | import os
import abc
import socket
import struct
import threading
import time
import numpy as np
import numpy.typing as npt
import cv2 as cv
import cv2
from pathlib import Path
from time import sleep
from typing import Any, Callable, Optional, Tuple, Union
from adbutils import AdbConnection, AdbDevice, AdbError, Network, adb
from av.codec import CodecContext # type: ignore
from av.error import InvalidDataError # type: ignore
from loguru import logger
from .const import EVENT_DISCONNECT, EVENT_FRAME, EVENT_INIT, LOCK_SCREEN_ORIENTATION_UNLOCKED, EVENT_ONCHANGE
from .control import ControlSender | 3,923 |
def __deploy_server(self) -> None:
"""
Deploy server to android device.
Push the scrcpy-server.jar into the Android device using
the adb.push(...). Then a basic connection between client and server
is established.
"""
cmd = [
"CLASSPATH=/data/local/tmp/scrcpy-server.jar",
"app_process",
"/",
"com.genymobile.scrcpy.Server",
VERSION, # Scrcpy server version
"info", # Log level: info, verbose...
f"{self.max_size}", # Max screen width (long side)
f"{self.bitrate}", # Bitrate of video
f"{self.max_fps}", # Max frame per second
f"{self.lock_screen_orientation}", # Lock screen orientation
"true", # Tunnel forward
"-", # Crop screen
"false", # Send frame rate to client
"true", # Control enabled
"0", # Display id
"false", # Show touches
"true" if self.stay_awake else "false", # Stay awake
"-", # Codec (video encoding) options
"-", # Encoder name
"false", # Power off screen after server closed
]
self.device.push(JAR, "/data/local/tmp/")
self.__server_stream: AdbConnection = self.device.shell(cmd, stream=True)
def start(self, threaded: bool = False) -> None:
"""
Start the client-server connection.
In order to avoid unpredictable behaviors, this method must be called
after the on_init and on_frame callback are specify.
Args:
threaded : If set to True the stream loop willl run in a separated
thread. This mean that the code after client.strart() will be
run. Otherwise the client.start() method starts a endless loop
and the code after this method will never run. todo new_thread
"""
assert self.alive is False
self.__deploy_server()
self.__init_server_connection()
self.alive = True
for func in self.listeners[EVENT_INIT]:
func(self)
if threaded: # 不阻塞当前thread
threading.Thread(target=self.__stream_loop).start()
else:
self.__stream_loop()
def stop(self) -> None:
"""
[ok]Close the various socket connection.
Stop listening (both threaded and blocked)
"""
self.alive = False
try:
self.__server_stream.close()
except Exception:
pass
try:
self.control_socket.close()
except Exception:
pass
try:
self.__video_socket.close()
except Exception:
pass
def __del__(self):
self.stop()
def __calculate_diff(self, img1, img2):
if img1 is None:
return 1
gray1 = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)
gray2 = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)
# 计算两张灰度图像的差异
diff = cv2.absdiff(gray1, gray2)
# 设置阈值,忽略差异值较小的像素
threshold = 30
_, thresholded_diff = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)
# 计算差异像素的总数
total_diff_pixels = np.sum(thresholded_diff / 255) # 除以255得到二值图像中白色像素的数量
# 计算图像的总像素数
total_pixels = gray1.size
# 计算变化率
change_rate = total_diff_pixels / total_pixels
return change_rate
def __stream_loop(self) -> None:
"""
Core loop for video parsing.
While the connection is open (self.alive == True) recive raw h264 video
stream and decode it into frames. These frame are those passed to
on_frame callbacks.
"""
codec = CodecContext.create("h264", "r")
while self.alive:
try:
raw = self.__video_socket.recv(0x10000)
if raw == b"":
raise ConnectionError("Video stream is disconnected")
for packet in codec.parse(raw):
for frame in codec.decode(packet): # codec.decode(packet)包含多帧
frame = frame.to_ndarray(format="bgr24")
|
Frame = npt.NDArray[np.int8]
VERSION = "1.20"
HERE = Path(__file__).resolve().parent
JAR = HERE / f"scrcpy-server.jar"
class Client:
def __init__(
self,
device: Optional[Union[AdbDevice, str]] = None,
max_size: int = 0,
bitrate: int = 8000000,
max_fps: int = 0,
block_frame: bool = True,
stay_awake: bool = True,
lock_screen_orientation: int = LOCK_SCREEN_ORIENTATION_UNLOCKED,
skip_same_frame=False
):
"""
[ok]Create a scrcpy client. The client won't be started until you call .start()
Args:
device: Android device to coennect to. Colud be also specify by
serial string. If device is None the client try to connect
to the first available device in adb deamon.
max_size: Specify the maximum dimension of the video stream. This
dimensioin refer both to width and hight.0: no limit[已校验, max size of width or height]
bitrate: bitrate
max_fps: Maximum FPS (Frame Per Second) of the video stream. If it
is set to 0 it means that there is not limit to FPS.
This feature is supported by android 10 or newer.
[flip]: 没有这个参数, 会自动处理
block_frame: If set to true, the on_frame callbacks will be only
apply on not empty frames. Otherwise try to apply on_frame
callbacks on every frame, but this could raise exceptions in
callbacks if they are not able to handle None value for frame.
True:跳过空白帧
stay_awake: keep Android device awake while the client-server
connection is alive.
lock_screen_orientation: lock screen in a particular orientation.
The available screen orientation are specify in const.py
in variables LOCK_SCREEN_ORIENTATION*
"""
# Params挪到后面去
self.max_size = max_size
self.bitrate = bitrate
self.max_fps = max_fps
self.block_frame = block_frame
self.stay_awake = stay_awake
self.lock_screen_orientation = lock_screen_orientation
self.skip_same_frame = skip_same_frame
self.min_frame_interval = 1 / max_fps
if device is None:
try:
device = adb.device_list()[0]
except IndexError:
raise Exception("Cannot connect to phone")
elif isinstance(device, str):
device = adb.device(serial=device)
self.device = device
self.listeners = dict(frame=[], init=[], disconnect=[], onchange=[])
# User accessible
self.last_frame: Optional[np.ndarray] = None
self.resolution: Optional[Tuple[int, int]] = None
self.device_name: Optional[str] = None
self.control = ControlSender(self)
# Need to destroy
self.alive = False
self.__server_stream: Optional[AdbConnection] = None
self.__video_socket: Optional[socket.socket] = None
self.control_socket: Optional[socket.socket] = None
self.control_socket_lock = threading.Lock()
def __init_server_connection(self) -> None:
"""
Connect to android server, there will be two sockets: video and control socket.
This method will also set resolution property.
"""
for _ in range(30): # 超时 写死
try:
self.__video_socket = self.device.create_connection(
Network.LOCAL_ABSTRACT, "scrcpy"
)
break
except AdbError:
sleep(0.1)
pass
else:
raise ConnectionError("Failed to connect scrcpy-server after 3 seconds")
dummy_byte = self.__video_socket.recv(1)
if not len(dummy_byte):
raise ConnectionError("Did not receive Dummy Byte!")
self.control_socket = self.device.create_connection(
Network.LOCAL_ABSTRACT, "scrcpy"
)
self.device_name = self.__video_socket.recv(64).decode("utf-8").rstrip("\x00")
if not len(self.device_name):
raise ConnectionError("Did not receive Device Name!")
res = self.__video_socket.recv(4)
self.resolution = struct.unpack(">HH", res)
self.__video_socket.setblocking(False)
def __deploy_server(self) -> None:
"""
Deploy server to android device.
Push the scrcpy-server.jar into the Android device using
the adb.push(...). Then a basic connection between client and server
is established.
"""
cmd = [
"CLASSPATH=/data/local/tmp/scrcpy-server.jar",
"app_process",
"/",
"com.genymobile.scrcpy.Server",
VERSION, # Scrcpy server version
"info", # Log level: info, verbose...
f"{self.max_size}", # Max screen width (long side)
f"{self.bitrate}", # Bitrate of video
f"{self.max_fps}", # Max frame per second
f"{self.lock_screen_orientation}", # Lock screen orientation
"true", # Tunnel forward
"-", # Crop screen
"false", # Send frame rate to client
"true", # Control enabled
"0", # Display id
"false", # Show touches
"true" if self.stay_awake else "false", # Stay awake
"-", # Codec (video encoding) options
"-", # Encoder name
"false", # Power off screen after server closed
]
self.device.push(JAR, "/data/local/tmp/")
self.__server_stream: AdbConnection = self.device.shell(cmd, stream=True)
def start(self, threaded: bool = False) -> None:
"""
Start the client-server connection.
In order to avoid unpredictable behaviors, this method must be called
after the on_init and on_frame callback are specify.
Args:
threaded : If set to True the stream loop willl run in a separated
thread. This mean that the code after client.strart() will be
run. Otherwise the client.start() method starts a endless loop
and the code after this method will never run. todo new_thread
"""
assert self.alive is False
self.__deploy_server()
self.__init_server_connection()
self.alive = True
for func in self.listeners[EVENT_INIT]:
func(self)
if threaded: # 不阻塞当前thread
threading.Thread(target=self.__stream_loop).start()
else:
self.__stream_loop()
def stop(self) -> None:
"""
[ok]Close the various socket connection.
Stop listening (both threaded and blocked)
"""
self.alive = False
try:
self.__server_stream.close()
except Exception:
pass
try:
self.control_socket.close()
except Exception:
pass
try:
self.__video_socket.close()
except Exception:
pass
def __del__(self):
self.stop()
def __calculate_diff(self, img1, img2):
if img1 is None:
return 1
gray1 = cv.cvtColor(img1, cv.COLOR_BGR2GRAY)
gray2 = cv.cvtColor(img2, cv.COLOR_BGR2GRAY)
# 计算两张灰度图像的差异
diff = cv2.absdiff(gray1, gray2)
# 设置阈值,忽略差异值较小的像素
threshold = 30
_, thresholded_diff = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)
# 计算差异像素的总数
total_diff_pixels = np.sum(thresholded_diff / 255) # 除以255得到二值图像中白色像素的数量
# 计算图像的总像素数
total_pixels = gray1.size
# 计算变化率
change_rate = total_diff_pixels / total_pixels
return change_rate
def __stream_loop(self) -> None:
"""
Core loop for video parsing.
While the connection is open (self.alive == True) recive raw h264 video
stream and decode it into frames. These frame are those passed to
on_frame callbacks.
"""
codec = CodecContext.create("h264", "r")
while self.alive:
try:
raw = self.__video_socket.recv(0x10000)
if raw == b"":
raise ConnectionError("Video stream is disconnected")
for packet in codec.parse(raw):
for frame in codec.decode(packet): # codec.decode(packet)包含多帧
frame = frame.to_ndarray(format="bgr24")
| if len(self.listeners[EVENT_ONCHANGE]) == 0 and not self.skip_same_frame: | 4 | 2023-12-23 12:52:58+00:00 | 8k |
andreafailla/pix2beats | ui.py | [
{
"identifier": "resize_and_convert",
"path": "backend.py",
"snippet": "def resize_and_convert(filename, tmpdir, n_pixels=None):\n \"\"\"\n Resize the image, convert to hsv, and save as png\n\n :param filename:\n :param tmpdir:\n :param n_pixels:\n :return:\n \"\"\"\n # Saves\n ... | import json # io
import tempfile
import streamlit as st # UI
from PIL import Image # image processing
from backend import resize_and_convert, trackmaker # processing
from backend import rolling_title # animation
from constants import SCALES, NOTES, HARMONIES, SAMPLE_IMAGES # constants
from my_presets import PRESETS | 4,694 | step=0.1,
key="wet_level",
help="The wet_level parameter controls the amount of wet signal. ",
)
with rev4:
dry_level = st.slider(
"dry_level",
min_value=0.1,
max_value=1.0,
step=0.1,
key="dry_level",
help="The dry_level parameter controls the amount of dry signal. ",
)
with rev5:
width = st.slider(
"width",
min_value=0.0,
max_value=1.0,
step=0.1,
key="width",
help="The width parameter controls the width of the stereo image. ",
)
st.markdown("### Ladder Filter")
lf1, lf2, lf3 = st.columns(3)
# Ladder Filter Parameters
with lf1:
cutoff_hz = st.slider(
"cutoff_hz",
min_value=0.0,
max_value=1000.0,
step=1.0,
key="cutoff_hz",
help="The cutoff_hz parameter controls the cutoff frequency of the filter. ",
)
with lf2:
resonance_lad = st.slider(
"resonance",
min_value=0.0,
max_value=1.0,
step=0.1,
key="resonance_lad",
help="The resonance parameter controls the resonance of the filter. ",
)
with lf3:
drive_lad = st.slider(
"drive",
min_value=1.0,
max_value=100.0,
step=0.1,
key="drive_lad",
help="The drive parameter controls the drive of the filter. ",
)
return {
"scale": scale,
"key": key,
"octave": octave,
"harmony": harmony,
"randomize_octaves": randomize_octaves,
"resize_to_n_pixels": resize_to_n_pixels,
"t_value": t_value,
"n_pixels": n_pixels,
"gain_db": gain_db,
"drive_db": drive_db,
"cutoff_hz": cutoff_hz,
"resonance_lad": resonance_lad,
"drive_lad": drive_lad,
"delay_seconds": delay_seconds,
"room_size": room_size,
"damping": damping,
"wet_level": wet_level,
"dry_level": dry_level,
"width": width,
"rate_hz_chorus": rate_hz_chorus,
}
def export_buttons(filename, param_dict, track, tmpdir):
b0, b1, _ = st.columns([1, 1, 2], gap="small")
with b0:
exp_track_name = (
filename[len(tmpdir) + 1 :] if filename.startswith(tmpdir) else filename
)
st.download_button(
"Download Track",
data=track,
file_name=f"{exp_track_name}.wav",
mime="audio/wav",
)
with b1:
exp_preset_name = (
filename.split("/")[-1] if filename.startswith(tmpdir) else filename
)
st.download_button(
"Export Preset",
data=json.dumps(param_dict),
file_name=f"{exp_preset_name}.json",
mime="application/json",
)
if __name__ == "__main__":
# all newly created files will be deleted when the context manager exits
with tempfile.TemporaryDirectory() as tmpdir:
init_session_state() # tells to use the default parameters
plh = write_intro() # returns placeholder for the rolling title
handle_presets() # load/upload presets
filename = make_sidebar_and_select_file() # select an image
param_dict = make_widgets_and_get_parameters()
if filename is not None:
# convert the image to RGB and resize it if necessary
|
def init_session_state():
for k, v in PRESETS["None"].items():
if k not in st.session_state:
if k != "octave":
st.session_state[k] = v
else:
octave_options = ["Low", "Mid", "High"]
st.session_state[k] = octave_options[v - 1]
def update_session_state(preset):
for k, v in preset.items():
if k != "octave":
st.session_state[k] = v
else:
octave_options = ["Low", "Mid", "High"]
st.session_state[k] = octave_options[v - 1]
def write_intro():
"""Defines general settings and introduces the app.
:return: placeholder for the rolling title
"""
st.set_page_config(
page_title="Pix2Beats",
page_icon=":musical_note:",
layout="centered",
initial_sidebar_state="expanded",
)
st.markdown(
"""
<style>
.stApp {
background: url("https://images.unsplash.com/photo-1557695126-fa2ce36f6828?q=80&w=2670&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D");
background-size: cover;
background-opacity: 0;
}
</style>""",
unsafe_allow_html=True,
)
st.title(":blue[Pix]2:red[Beats]")
plh = st.empty()
# Display the description
st.markdown(
"""
Welcome to :blue[Pix]2:red[Beats]—a web application at the intersection of visual art and musical expression.
Harnessing the power of Artificial Intelligence, :blue[Pix]2:red[Beats] transforms your images into sounds,
unlocking a fascinating synergy between the realms of visual and auditory creativity.
At the heart of :blue[Pix]2:red[Beats] lies the intuition that both images and sound can be effortlessly
represented as matrices of numbers.
This unique foundation allows us to create a one-of-a-kind mapping between color spaces and musical scales.
Choose an image, tinker with the parameters, and let :blue[Pix]2:red[Beats] do the rest :musical_note:
"""
)
return plh
def handle_presets():
presetsel, presetupl, _ = st.columns([1, 1, 2])
with presetsel:
preset_name = st.selectbox(
"***Choose a preset***",
PRESETS.keys(),
key="preset_select",
help="Tip: you can modify an existing preset by selecting it and then selecting "
"*None* from this list.",
)
if preset_name is not None:
if preset_name != "None":
update_session_state(PRESETS[preset_name])
with presetupl:
uploaded_preset = st.file_uploader(
"***...or upload your own!***", type=["json"]
)
css = """
<style>
[data-testid='stFileUploader'] {
width: max-content;
}
[data-testid='stFileUploader'] section {
padding: 0;
float: left;
}
[data-testid='stFileUploader'] section > input + div {
display: none;
}
[data-testid='stFileUploader'] section + div {
float: right;
padding-top: 0;
}
</style>
"""
st.markdown(css, unsafe_allow_html=True)
if uploaded_preset is not None:
preset_name = uploaded_preset.name.split(".")[0]
preset = json.load(uploaded_preset)
PRESETS[preset_name] = preset
update_session_state(preset)
def make_sidebar_and_select_file():
"""
Create the sidebar for the app
The sidebar lets the user select an image to use
:return: the image filename
"""
filename = None
if (
st.sidebar.radio(
"Image to use",
("Use Example Image", "Upload Image"),
label_visibility="hidden",
)
== "Use Example Image"
):
filename = st.sidebar.selectbox("Choose a sample image", SAMPLE_IMAGES)
img = Image.open(filename)
else:
img = st.sidebar.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])
if img is not None:
filename = img.name
img = Image.open(img)
filename = tmpdir + "/" + filename
img.save(filename)
# Display the image
if filename is not None:
st.sidebar.image(img)
return filename
def make_widgets_and_get_parameters():
"""
UI to get the parameters required to generate the track
:return: list of parameters
"""
col1, col2, col3 = st.columns([1, 1, 2])
with col1:
scale_options = list(SCALES.keys())
scale = st.selectbox("***Choose the scale***", scale_options, key="scale")
key = st.selectbox("***Choose the key***", NOTES, key="key")
with col2:
octave_options = ["Low", "Mid", "High"]
octave = st.selectbox("***Choose the octave***", octave_options, key="octave")
octave = octave_options.index(octave) + 1
harmony_options = list(HARMONIES.keys())
harmony = st.selectbox(
"*Choose how to harmonize*", harmony_options, key="harmony"
)
with col3:
t_value = st.slider(
"***Note duration (seconds)***",
min_value=0.10,
max_value=1.0,
step=0.01,
key="t_value",
)
n_pixels = st.slider(
"***Pixels to sample***",
min_value=64,
max_value=320,
step=1,
key="n_pixels",
)
randomize_octaves = st.checkbox(
"***Randomize octaves***",
key="randomize_octaves",
help="If checked, the octaves of the notes will be randomized. "
"Otherwise, the notes will be played in the same octave.",
)
resize_to_n_pixels = st.checkbox(
"***Resize image to N pixels***",
key="resize_to_n_pixels",
help="If checked, the image will be resized to N pixels. "
"Otherwise, the image will be used as is. "
"N is the number of pixels selected above.",
)
# ***Start Pedalboard Definitions***
st.markdown("## Pedalboard")
with st.expander("###### Click here to see the pedalboard"):
col4, col5, col6, col7 = st.columns(4)
# Chorus Parameters
with col4:
st.markdown("### Chorus")
rate_hz_chorus = st.slider(
"rate_hz",
min_value=0.0,
max_value=100.0,
step=0.1,
key="rate_hz_chorus",
help="The rate_hz parameter controls the rate of the chorus effect. ",
)
# Delay Parameters
with col5:
st.markdown("### Delay")
delay_seconds = st.slider(
"delay_seconds",
key="delay_seconds",
min_value=0.0,
max_value=2.0,
step=0.1,
help="The delay_seconds parameter controls the delay of the effect. ",
)
# Distortion Parameters
with col6:
st.markdown("### Distortion")
drive_db = st.slider(
"drive_db",
min_value=0.0,
max_value=100.0,
step=1.0,
key="drive_db",
help="The drive_db parameter controls the amount of distortion. ",
)
# Gain Parameters
with col7:
st.markdown("### Gain")
gain_db = st.slider(
"gain_db",
min_value=0.0,
max_value=100.0,
step=1.0,
key="gain_db",
help="The gain_db parameter controls the gain of the effect. ",
)
st.markdown("### Reverb")
rev1, rev2, rev3, rev4, rev5 = st.columns(5)
# Reverb Parameters
with rev1:
room_size = st.slider(
"room_size",
min_value=0.0,
max_value=1.0,
step=0.1,
key="room_size",
help="The room_size parameter controls the size of the reverbing room. ",
)
with rev2:
damping = st.slider(
"damping", min_value=0.0, max_value=1.0, step=0.1, key="damping"
)
with rev3:
wet_level = st.slider(
"wet_level",
min_value=0.0,
max_value=1.0,
step=0.1,
key="wet_level",
help="The wet_level parameter controls the amount of wet signal. ",
)
with rev4:
dry_level = st.slider(
"dry_level",
min_value=0.1,
max_value=1.0,
step=0.1,
key="dry_level",
help="The dry_level parameter controls the amount of dry signal. ",
)
with rev5:
width = st.slider(
"width",
min_value=0.0,
max_value=1.0,
step=0.1,
key="width",
help="The width parameter controls the width of the stereo image. ",
)
st.markdown("### Ladder Filter")
lf1, lf2, lf3 = st.columns(3)
# Ladder Filter Parameters
with lf1:
cutoff_hz = st.slider(
"cutoff_hz",
min_value=0.0,
max_value=1000.0,
step=1.0,
key="cutoff_hz",
help="The cutoff_hz parameter controls the cutoff frequency of the filter. ",
)
with lf2:
resonance_lad = st.slider(
"resonance",
min_value=0.0,
max_value=1.0,
step=0.1,
key="resonance_lad",
help="The resonance parameter controls the resonance of the filter. ",
)
with lf3:
drive_lad = st.slider(
"drive",
min_value=1.0,
max_value=100.0,
step=0.1,
key="drive_lad",
help="The drive parameter controls the drive of the filter. ",
)
return {
"scale": scale,
"key": key,
"octave": octave,
"harmony": harmony,
"randomize_octaves": randomize_octaves,
"resize_to_n_pixels": resize_to_n_pixels,
"t_value": t_value,
"n_pixels": n_pixels,
"gain_db": gain_db,
"drive_db": drive_db,
"cutoff_hz": cutoff_hz,
"resonance_lad": resonance_lad,
"drive_lad": drive_lad,
"delay_seconds": delay_seconds,
"room_size": room_size,
"damping": damping,
"wet_level": wet_level,
"dry_level": dry_level,
"width": width,
"rate_hz_chorus": rate_hz_chorus,
}
def export_buttons(filename, param_dict, track, tmpdir):
b0, b1, _ = st.columns([1, 1, 2], gap="small")
with b0:
exp_track_name = (
filename[len(tmpdir) + 1 :] if filename.startswith(tmpdir) else filename
)
st.download_button(
"Download Track",
data=track,
file_name=f"{exp_track_name}.wav",
mime="audio/wav",
)
with b1:
exp_preset_name = (
filename.split("/")[-1] if filename.startswith(tmpdir) else filename
)
st.download_button(
"Export Preset",
data=json.dumps(param_dict),
file_name=f"{exp_preset_name}.json",
mime="application/json",
)
if __name__ == "__main__":
# all newly created files will be deleted when the context manager exits
with tempfile.TemporaryDirectory() as tmpdir:
init_session_state() # tells to use the default parameters
plh = write_intro() # returns placeholder for the rolling title
handle_presets() # load/upload presets
filename = make_sidebar_and_select_file() # select an image
param_dict = make_widgets_and_get_parameters()
if filename is not None:
# convert the image to RGB and resize it if necessary | img = resize_and_convert( | 0 | 2023-12-30 13:12:10+00:00 | 8k |
AbstractUmbra/GreatAsset | great_asset/save_file.py | [
{
"identifier": "decrypt",
"path": "great_asset/crypt.py",
"snippet": "def decrypt(\n *, path: str | PathLike[str] | Path | None = None, data: bytes | None = None\n) -> Any: # it returns the type of file we decrypt but alas\n if not path and not data:\n raise ValueError(\"Either `path` or ... | import random
from pathlib import Path
from typing import TYPE_CHECKING, Any, Generic, Self, TypeVar
from .crypt import decrypt, encrypt
from .enums import BestiaryEntry, ExtraUnlock, Item, Moon, Scrap, ShipUnlock
from .item import GrabbableScrap
from .utils import MISSING, SaveValue, _to_json, resolve_save_path # type: ignore[reportPrivateUsage] we allow this here.
from .vector import Vector
from os import PathLike
from types import TracebackType
from .types_.config_file import ConfigFile as ConfigFileType
from .types_.save_file import (
SaveFile as SaveFileType,
)
from .types_.shared import * | 4,862 | self._upsert_value(key, value)
if dump_to_file:
self._dump(overwrite=overwrite)
self._written = True
def _dump(self, overwrite: bool) -> None:
decrypted_result = _to_json(self._inner_data)
with TEMP_FILE.open("wb") as fp:
fp.write(decrypted_result.encode("utf-8"))
encrypted_result = encrypt(TEMP_FILE)
p = self.path if overwrite else self.path.with_suffix(".over")
with p.open("wb") as fp:
fp.write(encrypted_result)
class SaveFile(_BaseSaveFile["SaveFileType"]):
# late init variable types
_extra_data: dict[str, Any]
_credits: int
_current_planet_id: int
_deadline: float
_deaths: int
_elapsed_days: int
_quotas_met: int
_quota_threshold: int
_seed: int
_steps_taken: int
__slots__ = (
"_inner_data",
"_extra_data",
"_credits",
"_current_planet_id",
"_current_quota_progress",
"_deadline",
"_deaths",
"_elapsed_days",
"_quotas_met",
"_quota_threshold",
"_seed",
"_steps_taken",
# these values need a richer interface
"_enemy_scans",
"_ship_item_save_data",
"_unlocked_ship_objects",
"_scrap",
"__ship_grabbable_items",
"__ship_grabbable_item_positions",
"__ship_scrap",
"path",
)
@classmethod
def resolve_from_file(cls, save_file_number: SaveValue, /) -> SaveFile:
path = resolve_save_path(save_file_number)
return cls(path)
def validate_contents(self, data: SaveFileType, /) -> None: # type: ignore # we narrowed the type in the subclass
if not any(
[
data.get("GroupCredits"),
data.get("DeadlineTime"),
data.get("Stats_StepsTaken"),
data.get("Stats_DaysSpent"),
data.get("ProfitQuota"),
data.get("CurrentPlanetID"),
]
):
raise ValueError("This doesn't appear to be a valid Lethal Company save file!")
def _parse_file(self) -> None:
super()._parse_file()
self._credits = self._inner_data["GroupCredits"]["value"]
self._current_planet_id = self._inner_data["CurrentPlanetID"]["value"]
self._current_quota_progress = self._inner_data["QuotaFulfilled"]["value"]
self._deadline = self._inner_data["DeadlineTime"]["value"]
self._deaths = self._inner_data["Stats_Deaths"]["value"]
self._elapsed_days = self._inner_data["Stats_DaysSpent"]["value"]
self._quotas_met = self._inner_data["QuotasPassed"]["value"]
self._quota_threshold = self._inner_data["ProfitQuota"]["value"]
self._seed = self._inner_data["RandomSeed"]["value"]
self._steps_taken = self._inner_data["Stats_StepsTaken"]["value"]
# TODO: richer interface here.
self._enemy_scans = self._inner_data.get("EnemyScans", {"__type": "System.Int32[],mscorlib", "value": []})
self._ship_item_save_data = self._inner_data.get(
"shipItemSaveData", {"__type": "System.Int32[],mscorlib", "value": []}
)
self._unlocked_ship_objects = self._inner_data.get(
"UnlockedShipObjects", {"__type": "System.Int32[],mscorlib", "value": []}
)
self.__ship_grabbable_items = self._inner_data.get(
"shipGrabbableItemIDs", {"__type": "System.Int32[],mscorlib", "value": []}
)
self.__ship_grabbable_item_positions = self._inner_data.get(
"shipGrabbableItemPos", {"__type": "UnityEngine.Vector3[],UnityEngine.CoreModule", "value": []}
)
self.__ship_scrap = self._inner_data.get("shipScrapValues", {"__type": "System.Int32[],mscorlib", "value": []})
self._parse_scrap_mapping()
# this key is mostly laziness for now
# we'll serialise anything in here into the final payload
# for now this will just be how we add the UnlockedStored_X keys
self._extra_data = {}
def _parse_scrap_mapping(self) -> None:
# shipGrabbableItems contains all touchable items on the ship, including tools which have no value
# shipScrapValues are an array of values assigned to each piece of scrap
# it works because GrabbableItems[1]: ScrapValues[1], each index aligns and that's how the values are assigned, like a zip
# once the scrapvalues runs out of elements, the rest of the items are treated as no value, like tools
| """
The MIT License (MIT)
Copyright (c) 2023-present AbstractUmbra
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.
"""
from __future__ import annotations
if TYPE_CHECKING:
SaveT = TypeVar("SaveT", "SaveFileType", "ConfigFileType")
TEMP_FILE = Path("./_previously_decrypted_file.json")
TIPS = [
"LC_MoveObjectsTip",
"LC_StorageTip",
"LC_LightningTip",
"LCTip_SecureDoors",
"LC_EclipseTip",
"LCTip_SellScrap",
"LCTip_UseManual",
"LC_IntroTip1",
]
__all__ = (
"SaveFile",
"ConfigFile",
)
class _BaseSaveFile(Generic[SaveT]):
_inner_data: SaveT
_file_type: str
_extra_data: dict[str, Any]
_written: bool
_skip_parsing: bool
__slots__ = (
"_inner_data",
"_file_type",
"_extra_data",
"_written",
"_skip_parsing",
"path",
)
def __init__(self, path: str | PathLike[str] | Path, /) -> None:
self._skip_parsing = False
self._written = False
if not isinstance(path, Path):
path = Path(path)
if not path.exists():
raise ValueError("The path given does not exist")
self.path: Path = path
self._parse_file()
@classmethod
def from_data(cls, *, data: bytes, path: Path | None = None, save_number: SaveValue | None = None) -> Self:
_number = save_number or ""
path = path or Path(f"./LCSaveFile{_number}")
file = cls.__new__(cls)
file._skip_parsing = True
decrypted: SaveT = decrypt(data=data)
file.validate_contents(decrypted)
file._inner_data = decrypted
file.path = path
file._parse_file()
return file
def __enter__(self) -> Self:
return self
def __exit__(
self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None
) -> None:
if not self._written and not exc_type:
self.write()
def validate_contents(self, data: SaveFileType | ConfigFileType, /) -> None:
raise NotImplementedError
def _parse_file(self) -> None:
if self._skip_parsing:
return
data = decrypt(path=self.path)
self.validate_contents(data)
self._inner_data = data
def _upsert_value(self, key_name: str, value: Any) -> None:
if value is MISSING:
return # If the value is the sentinel type, do nothing and move onto the next
if isinstance(value, int):
_type = "int"
elif isinstance(value, list):
if value and isinstance(value[0], int):
_type = "System.Int32[],mscorlib"
elif value and isinstance(value[0], dict):
_type = "UnityEngine.Vector3[],UnityEngine.CoreModule"
else:
raise ValueError("Unexpected or unknown array type passed for `value`")
elif isinstance(value, bool):
_type = "bool"
else:
raise ValueError("Unexpected type passed for `value`: %r (%s)", value, type(value))
try:
self._inner_data[key_name]["value"] = value
except KeyError:
self._inner_data[key_name] = {"__type": _type, "value": value}
def write(self, *, dump_to_file: bool = True, overwrite: bool = True) -> None:
for key, value in self._extra_data.items():
self._upsert_value(key, value)
if dump_to_file:
self._dump(overwrite=overwrite)
self._written = True
def _dump(self, overwrite: bool) -> None:
decrypted_result = _to_json(self._inner_data)
with TEMP_FILE.open("wb") as fp:
fp.write(decrypted_result.encode("utf-8"))
encrypted_result = encrypt(TEMP_FILE)
p = self.path if overwrite else self.path.with_suffix(".over")
with p.open("wb") as fp:
fp.write(encrypted_result)
class SaveFile(_BaseSaveFile["SaveFileType"]):
# late init variable types
_extra_data: dict[str, Any]
_credits: int
_current_planet_id: int
_deadline: float
_deaths: int
_elapsed_days: int
_quotas_met: int
_quota_threshold: int
_seed: int
_steps_taken: int
__slots__ = (
"_inner_data",
"_extra_data",
"_credits",
"_current_planet_id",
"_current_quota_progress",
"_deadline",
"_deaths",
"_elapsed_days",
"_quotas_met",
"_quota_threshold",
"_seed",
"_steps_taken",
# these values need a richer interface
"_enemy_scans",
"_ship_item_save_data",
"_unlocked_ship_objects",
"_scrap",
"__ship_grabbable_items",
"__ship_grabbable_item_positions",
"__ship_scrap",
"path",
)
@classmethod
def resolve_from_file(cls, save_file_number: SaveValue, /) -> SaveFile:
path = resolve_save_path(save_file_number)
return cls(path)
def validate_contents(self, data: SaveFileType, /) -> None: # type: ignore # we narrowed the type in the subclass
if not any(
[
data.get("GroupCredits"),
data.get("DeadlineTime"),
data.get("Stats_StepsTaken"),
data.get("Stats_DaysSpent"),
data.get("ProfitQuota"),
data.get("CurrentPlanetID"),
]
):
raise ValueError("This doesn't appear to be a valid Lethal Company save file!")
def _parse_file(self) -> None:
super()._parse_file()
self._credits = self._inner_data["GroupCredits"]["value"]
self._current_planet_id = self._inner_data["CurrentPlanetID"]["value"]
self._current_quota_progress = self._inner_data["QuotaFulfilled"]["value"]
self._deadline = self._inner_data["DeadlineTime"]["value"]
self._deaths = self._inner_data["Stats_Deaths"]["value"]
self._elapsed_days = self._inner_data["Stats_DaysSpent"]["value"]
self._quotas_met = self._inner_data["QuotasPassed"]["value"]
self._quota_threshold = self._inner_data["ProfitQuota"]["value"]
self._seed = self._inner_data["RandomSeed"]["value"]
self._steps_taken = self._inner_data["Stats_StepsTaken"]["value"]
# TODO: richer interface here.
self._enemy_scans = self._inner_data.get("EnemyScans", {"__type": "System.Int32[],mscorlib", "value": []})
self._ship_item_save_data = self._inner_data.get(
"shipItemSaveData", {"__type": "System.Int32[],mscorlib", "value": []}
)
self._unlocked_ship_objects = self._inner_data.get(
"UnlockedShipObjects", {"__type": "System.Int32[],mscorlib", "value": []}
)
self.__ship_grabbable_items = self._inner_data.get(
"shipGrabbableItemIDs", {"__type": "System.Int32[],mscorlib", "value": []}
)
self.__ship_grabbable_item_positions = self._inner_data.get(
"shipGrabbableItemPos", {"__type": "UnityEngine.Vector3[],UnityEngine.CoreModule", "value": []}
)
self.__ship_scrap = self._inner_data.get("shipScrapValues", {"__type": "System.Int32[],mscorlib", "value": []})
self._parse_scrap_mapping()
# this key is mostly laziness for now
# we'll serialise anything in here into the final payload
# for now this will just be how we add the UnlockedStored_X keys
self._extra_data = {}
def _parse_scrap_mapping(self) -> None:
# shipGrabbableItems contains all touchable items on the ship, including tools which have no value
# shipScrapValues are an array of values assigned to each piece of scrap
# it works because GrabbableItems[1]: ScrapValues[1], each index aligns and that's how the values are assigned, like a zip
# once the scrapvalues runs out of elements, the rest of the items are treated as no value, like tools | self._scrap: list[GrabbableScrap] = [] | 8 | 2023-12-25 11:03:20+00:00 | 8k |
Shaokang-Agent/S2L | marlgrid/envs/doorkey.py | [
{
"identifier": "MultiGridEnv",
"path": "marlgrid/base.py",
"snippet": "class MultiGridEnv(gym.Env):\n def __init__(\n self,\n agents = [],\n grid_size=None,\n width=None,\n height=None,\n max_steps=100,\n reward_decay=True,\n seed=1337,\n ... | from ..base import MultiGridEnv, MultiGrid
from ..objects import * | 7,087 |
class DoorKeyEnv(MultiGridEnv):
"""
Environment with a door and key, sparse reward.
Similar to DoorKeyEnv in
https://github.com/maximecb/gym-minigrid/blob/master/gym_minigrid/envs/doorkey.py
"""
mission = "use the key to open the door and then get to the goal"
metadata = {}
def _gen_grid(self, width, height):
# Create an empty grid
|
class DoorKeyEnv(MultiGridEnv):
"""
Environment with a door and key, sparse reward.
Similar to DoorKeyEnv in
https://github.com/maximecb/gym-minigrid/blob/master/gym_minigrid/envs/doorkey.py
"""
mission = "use the key to open the door and then get to the goal"
metadata = {}
def _gen_grid(self, width, height):
# Create an empty grid | self.grid = MultiGrid((width, height)) | 1 | 2023-12-24 06:50:38+00:00 | 8k |
gh-PonyM/textual-jsonschema-form | textual_jsonschema_form/converter.py | [
{
"identifier": "JSONFieldParametersBase",
"path": "textual_jsonschema_form/core.py",
"snippet": "def strip_cmp_path(ref: str) -> str:\n def get_factory(self):\n def field_label(self):\n def get_options(self):\n def used_imports(self) -> Generator[str, None, None]:\n def default(self) -> ... | from collections.abc import Iterable
from dataclasses import dataclass
from typing import ClassVar
from textual.suggester import SuggestFromList
from textual.validation import Integer, Number, Validator
from .core import JSONFieldParametersBase, ValidatorType, strip_cmp_path
from .fields import ArrayField, FormInput, FormStrMultiSelect, FormStrSelect, FormSwitch
from .registry import textual_converter
from .validators import NumberRange | 4,149 | from __future__ import annotations
class InputBase(JSONFieldParametersBase[FormInput, Validator]):
factory: ClassVar[type[FormInput]] = FormInput
@classmethod
def extract(cls, params: dict, available: set[str]) -> tuple[list[Validator], dict]:
attrs = {}
if "default" in available:
attrs["default"] = params.get("default")
return [], attrs
def get_options(self):
"""These are all kwargs that the default input field takes"""
value = self.attrs.get("default", "")
return {
"valid_empty": not (self.required or value),
"value": str(value),
"name": self.field_name,
"placeholder": self.description,
"restrict": self.attrs.get("restrict"),
"validate_on": ("changed", "submitted"),
"password": self.attrs.get("password", False),
"max_length": self.attrs.get("max_length", 0),
"suggester": self.attrs.get("suggester"),
"validators": self.validators,
"type": {"string": "text"}.get(self.type, self.type),
}
def get_factory(self) -> type[FormInput]:
return self.factory
@textual_converter.register("string")
@dataclass
class TextualStringParam(InputBase):
supported = {"string"}
allowed = {
"format",
"pattern",
"enum",
"default",
}
ignore = JSONFieldParametersBase.ignore | {"minLength", "maxLength", "writeOnly"}
SUGGESTER_FOR_ENUM: ClassVar[bool] = False
@classmethod
def extract(cls, params: dict, available: set[str]):
validators, attrs = InputBase.extract(params, available)
if "enum" in available:
if cls.SUGGESTER_FOR_ENUM:
attrs["suggester"] = SuggestFromList(
params["enum"], case_sensitive=False
)
attrs["choices"] = params["enum"]
if "maxLength" in available:
attrs["max_length"] = int(params["maxLength"])
if "pattern" in available:
attrs["restrict"] = params["pattern"]
if "format" in available:
fmt = attrs["format"] = params["format"]
if fmt == "password":
attrs["password"] = True
return validators, attrs
def get_factory(self):
return (
| from __future__ import annotations
class InputBase(JSONFieldParametersBase[FormInput, Validator]):
factory: ClassVar[type[FormInput]] = FormInput
@classmethod
def extract(cls, params: dict, available: set[str]) -> tuple[list[Validator], dict]:
attrs = {}
if "default" in available:
attrs["default"] = params.get("default")
return [], attrs
def get_options(self):
"""These are all kwargs that the default input field takes"""
value = self.attrs.get("default", "")
return {
"valid_empty": not (self.required or value),
"value": str(value),
"name": self.field_name,
"placeholder": self.description,
"restrict": self.attrs.get("restrict"),
"validate_on": ("changed", "submitted"),
"password": self.attrs.get("password", False),
"max_length": self.attrs.get("max_length", 0),
"suggester": self.attrs.get("suggester"),
"validators": self.validators,
"type": {"string": "text"}.get(self.type, self.type),
}
def get_factory(self) -> type[FormInput]:
return self.factory
@textual_converter.register("string")
@dataclass
class TextualStringParam(InputBase):
supported = {"string"}
allowed = {
"format",
"pattern",
"enum",
"default",
}
ignore = JSONFieldParametersBase.ignore | {"minLength", "maxLength", "writeOnly"}
SUGGESTER_FOR_ENUM: ClassVar[bool] = False
@classmethod
def extract(cls, params: dict, available: set[str]):
validators, attrs = InputBase.extract(params, available)
if "enum" in available:
if cls.SUGGESTER_FOR_ENUM:
attrs["suggester"] = SuggestFromList(
params["enum"], case_sensitive=False
)
attrs["choices"] = params["enum"]
if "maxLength" in available:
attrs["max_length"] = int(params["maxLength"])
if "pattern" in available:
attrs["restrict"] = params["pattern"]
if "format" in available:
fmt = attrs["format"] = params["format"]
if fmt == "password":
attrs["password"] = True
return validators, attrs
def get_factory(self):
return ( | FormStrSelect | 4 | 2023-12-26 17:05:27+00:00 | 8k |
smonsays/modular-hyperteacher | tests/data/envs/test_grid.py | [
{
"identifier": "MOVES",
"path": "metax/data/envs/grid.py",
"snippet": "class MOVES(enum.Enum):\n UP = 0\n RIGHT = 1\n DOWN = 2\n LEFT = 3"
},
{
"identifier": "CompositionalGrid",
"path": "metax/data/envs/grid.py",
"snippet": "class CompositionalGrid(Environment):\n def __... | import unittest
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
from functools import partial
from metax.data.envs.grid import (MOVES, CompositionalGrid,
CompositionalGridGoal)
from mpl_toolkits.axes_grid1 import ImageGrid | 5,368 | """
Copyright (c) Simon Schug
All rights reserved.
MIT License
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.
"""
class CompositionalGridTestCase(unittest.TestCase):
rng = jax.random.PRNGKey(0)
def test_reset(self):
env = CompositionalGrid(
grid_size := 7,
num_interactions := 4,
num_mazes := 2,
num_objects := 3,
num_distractors := 2,
frac_ood := 0.2,
task_support := "1_hot",
seed := 2022,
)
state, emission = env.reset(rng=self.rng)
# state, emission = jax.jit(env.reset)(rng=self.rng)
assert state.timestep == 0
assert emission.observation.shape == (grid_size, grid_size, num_objects + 2)
assert jnp.all(jnp.concatenate((env.tasks_in_dist, env.tasks_out_dist)).shape == env.tasks_all.shape)
assert len(jnp.unique(jnp.concatenate((env.tasks_in_dist, env.tasks_out_dist)), axis=1)) == len(env.tasks_all)
def test_step(self):
env = CompositionalGrid(
grid_size := 7,
num_interactions := 4,
num_mazes := 6,
num_objects := 5,
num_distractors := 2,
frac_ood := 0.2,
task_support := "random",
seed := 2022,
)
| """
Copyright (c) Simon Schug
All rights reserved.
MIT License
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.
"""
class CompositionalGridTestCase(unittest.TestCase):
rng = jax.random.PRNGKey(0)
def test_reset(self):
env = CompositionalGrid(
grid_size := 7,
num_interactions := 4,
num_mazes := 2,
num_objects := 3,
num_distractors := 2,
frac_ood := 0.2,
task_support := "1_hot",
seed := 2022,
)
state, emission = env.reset(rng=self.rng)
# state, emission = jax.jit(env.reset)(rng=self.rng)
assert state.timestep == 0
assert emission.observation.shape == (grid_size, grid_size, num_objects + 2)
assert jnp.all(jnp.concatenate((env.tasks_in_dist, env.tasks_out_dist)).shape == env.tasks_all.shape)
assert len(jnp.unique(jnp.concatenate((env.tasks_in_dist, env.tasks_out_dist)), axis=1)) == len(env.tasks_all)
def test_step(self):
env = CompositionalGrid(
grid_size := 7,
num_interactions := 4,
num_mazes := 6,
num_objects := 5,
num_distractors := 2,
frac_ood := 0.2,
task_support := "random",
seed := 2022,
) | goal = CompositionalGridGoal(direction := 0, interaction := 1, maze := 2, object := 3) | 2 | 2023-12-22 16:35:49+00:00 | 8k |
AContesini/Convert_PDF_to_DOCX_or_vice-versa | venv/Lib/site-packages/tqdm/std.py | [
{
"identifier": "TMonitor",
"path": "venv/Lib/site-packages/tqdm/_monitor.py",
"snippet": "class TMonitor(Thread):\n \"\"\"\n Monitoring thread for tqdm bars.\n Monitors if tqdm bars are taking too much time to display\n and readjusts miniters automatically if necessary.\n\n Parameters\n ... | import sys
from collections import OrderedDict, defaultdict
from contextlib import contextmanager
from datetime import datetime, timedelta
from numbers import Number
from time import time
from warnings import warn
from weakref import WeakSet
from ._monitor import TMonitor
from .utils import (
CallbackIOWrapper, Comparable, DisableOnWriteError, FormatReplace, SimpleTextIOWrapper,
_is_ascii, _screen_shape_wrapper, _supports_unicode, _term_move_up, disp_len, disp_trim,
envwrap)
from threading import RLock
from multiprocessing import RLock
from warnings import catch_warnings, simplefilter
from pandas.core.frame import DataFrame
from pandas.core.series import Series
from pandas import Panel
from pandas.core.window.rolling import _Rolling_and_Expanding
from pandas.core.window import _Rolling_and_Expanding
from pandas.core.window.expanding import Expanding
from pandas.core.window.rolling import Rolling
from pandas.core.groupby.generic import SeriesGroupBy # , NDFrameGroupBy
from pandas.core.groupby.generic import DataFrameGroupBy
from pandas.core.groupby.groupby import DataFrameGroupBy, SeriesGroupBy
from pandas.core.groupby import DataFrameGroupBy, SeriesGroupBy
from pandas.core.groupby.groupby import GroupBy
from pandas.core.groupby import GroupBy
from pandas.core.groupby.groupby import PanelGroupBy
from pandas.core.groupby import PanelGroupBy
from pandas.core.common import is_builtin_func | 5,913 |
tqdm_kwargs = tqdm_kwargs.copy()
deprecated_t = [tqdm_kwargs.pop('deprecated_t', None)]
def inner_generator(df_function='apply'):
def inner(df, func, *args, **kwargs):
"""
Parameters
----------
df : (DataFrame|Series)[GroupBy]
Data (may be grouped).
func : function
To be applied on the (grouped) data.
**kwargs : optional
Transmitted to `df.apply()`.
"""
# Precompute total iterations
total = tqdm_kwargs.pop("total", getattr(df, 'ngroups', None))
if total is None: # not grouped
if df_function == 'applymap':
total = df.size
elif isinstance(df, Series):
total = len(df)
elif (_Rolling_and_Expanding is None or
not isinstance(df, _Rolling_and_Expanding)):
# DataFrame or Panel
axis = kwargs.get('axis', 0)
if axis == 'index':
axis = 0
elif axis == 'columns':
axis = 1
# when axis=0, total is shape[axis1]
total = df.size // df.shape[axis]
# Init bar
if deprecated_t[0] is not None:
t = deprecated_t[0]
deprecated_t[0] = None
else:
t = cls(total=total, **tqdm_kwargs)
if len(args) > 0:
# *args intentionally not supported (see #244, #299)
TqdmDeprecationWarning(
"Except func, normal arguments are intentionally" +
" not supported by" +
" `(DataFrame|Series|GroupBy).progress_apply`." +
" Use keyword arguments instead.",
fp_write=getattr(t.fp, 'write', sys.stderr.write))
try: # pandas>=1.3.0
except ImportError:
is_builtin_func = df._is_builtin_func
try:
func = is_builtin_func(func)
except TypeError:
pass
# Define bar updating wrapper
def wrapper(*args, **kwargs):
# update tbar correctly
# it seems `pandas apply` calls `func` twice
# on the first column/row to decide whether it can
# take a fast or slow code path; so stop when t.total==t.n
t.update(n=1 if not t.total or t.n < t.total else 0)
return func(*args, **kwargs)
# Apply the provided function (in **kwargs)
# on the df using our wrapper (which provides bar updating)
try:
return getattr(df, df_function)(wrapper, **kwargs)
finally:
t.close()
return inner
# Monkeypatch pandas to provide easy methods
# Enable custom tqdm progress in pandas!
Series.progress_apply = inner_generator()
SeriesGroupBy.progress_apply = inner_generator()
Series.progress_map = inner_generator('map')
SeriesGroupBy.progress_map = inner_generator('map')
DataFrame.progress_apply = inner_generator()
DataFrameGroupBy.progress_apply = inner_generator()
DataFrame.progress_applymap = inner_generator('applymap')
if Panel is not None:
Panel.progress_apply = inner_generator()
if PanelGroupBy is not None:
PanelGroupBy.progress_apply = inner_generator()
GroupBy.progress_apply = inner_generator()
GroupBy.progress_aggregate = inner_generator('aggregate')
GroupBy.progress_transform = inner_generator('transform')
if Rolling is not None and Expanding is not None:
Rolling.progress_apply = inner_generator()
Expanding.progress_apply = inner_generator()
elif _Rolling_and_Expanding is not None:
_Rolling_and_Expanding.progress_apply = inner_generator()
# override defaults via env vars
@envwrap("TQDM_", is_method=True, types={'total': float, 'ncols': int, 'miniters': float,
'position': int, 'nrows': int})
def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None,
ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None,
ascii=None, disable=False, unit='it', unit_scale=False,
dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0,
position=None, postfix=None, unit_divisor=1000, write_bytes=False,
lock_args=None, nrows=None, colour=None, delay=0.0, gui=False,
**kwargs):
"""see tqdm.tqdm for arguments"""
if file is None:
file = sys.stderr
if write_bytes:
# Despite coercing unicode into bytes, py2 sys.std* streams
# should have bytes written to them.
| """
Customisable progressbar decorator for iterators.
Includes a default `range` iterator printing to `stderr`.
Usage:
>>> from tqdm import trange, tqdm
>>> for i in trange(10):
... ...
"""
__author__ = "https://github.com/tqdm/tqdm#contributions"
__all__ = ['tqdm', 'trange',
'TqdmTypeError', 'TqdmKeyError', 'TqdmWarning',
'TqdmExperimentalWarning', 'TqdmDeprecationWarning',
'TqdmMonitorWarning']
class TqdmTypeError(TypeError):
pass
class TqdmKeyError(KeyError):
pass
class TqdmWarning(Warning):
"""base class for all tqdm warnings.
Used for non-external-code-breaking errors, such as garbled printing.
"""
def __init__(self, msg, fp_write=None, *a, **k):
if fp_write is not None:
fp_write("\n" + self.__class__.__name__ + ": " + str(msg).rstrip() + '\n')
else:
super(TqdmWarning, self).__init__(msg, *a, **k)
class TqdmExperimentalWarning(TqdmWarning, FutureWarning):
"""beta feature, unstable API and behaviour"""
pass
class TqdmDeprecationWarning(TqdmWarning, DeprecationWarning):
# not suppressed if raised
pass
class TqdmMonitorWarning(TqdmWarning, RuntimeWarning):
"""tqdm monitor errors which do not affect external functionality"""
pass
def TRLock(*args, **kwargs):
"""threading RLock"""
try:
return RLock(*args, **kwargs)
except (ImportError, OSError): # pragma: no cover
pass
class TqdmDefaultWriteLock(object):
"""
Provide a default write lock for thread and multiprocessing safety.
Works only on platforms supporting `fork` (so Windows is excluded).
You must initialise a `tqdm` or `TqdmDefaultWriteLock` instance
before forking in order for the write lock to work.
On Windows, you need to supply the lock from the parent to the children as
an argument to joblib or the parallelism lib you use.
"""
# global thread lock so no setup required for multithreading.
# NB: Do not create multiprocessing lock as it sets the multiprocessing
# context, disallowing `spawn()`/`forkserver()`
th_lock = TRLock()
def __init__(self):
# Create global parallelism locks to avoid racing issues with parallel
# bars works only if fork available (Linux/MacOSX, but not Windows)
cls = type(self)
root_lock = cls.th_lock
if root_lock is not None:
root_lock.acquire()
cls.create_mp_lock()
self.locks = [lk for lk in [cls.mp_lock, cls.th_lock] if lk is not None]
if root_lock is not None:
root_lock.release()
def acquire(self, *a, **k):
for lock in self.locks:
lock.acquire(*a, **k)
def release(self):
for lock in self.locks[::-1]: # Release in inverse order of acquisition
lock.release()
def __enter__(self):
self.acquire()
def __exit__(self, *exc):
self.release()
@classmethod
def create_mp_lock(cls):
if not hasattr(cls, 'mp_lock'):
try:
cls.mp_lock = RLock()
except (ImportError, OSError): # pragma: no cover
cls.mp_lock = None
@classmethod
def create_th_lock(cls):
assert hasattr(cls, 'th_lock')
warn("create_th_lock not needed anymore", TqdmDeprecationWarning, stacklevel=2)
class Bar(object):
"""
`str.format`-able bar with format specifiers: `[width][type]`
- `width`
+ unspecified (default): use `self.default_len`
+ `int >= 0`: overrides `self.default_len`
+ `int < 0`: subtract from `self.default_len`
- `type`
+ `a`: ascii (`charset=self.ASCII` override)
+ `u`: unicode (`charset=self.UTF` override)
+ `b`: blank (`charset=" "` override)
"""
ASCII = " 123456789#"
UTF = u" " + u''.join(map(chr, range(0x258F, 0x2587, -1)))
BLANK = " "
COLOUR_RESET = '\x1b[0m'
COLOUR_RGB = '\x1b[38;2;%d;%d;%dm'
COLOURS = {'BLACK': '\x1b[30m', 'RED': '\x1b[31m', 'GREEN': '\x1b[32m',
'YELLOW': '\x1b[33m', 'BLUE': '\x1b[34m', 'MAGENTA': '\x1b[35m',
'CYAN': '\x1b[36m', 'WHITE': '\x1b[37m'}
def __init__(self, frac, default_len=10, charset=UTF, colour=None):
if not 0 <= frac <= 1:
warn("clamping frac to range [0, 1]", TqdmWarning, stacklevel=2)
frac = max(0, min(1, frac))
assert default_len > 0
self.frac = frac
self.default_len = default_len
self.charset = charset
self.colour = colour
@property
def colour(self):
return self._colour
@colour.setter
def colour(self, value):
if not value:
self._colour = None
return
try:
if value.upper() in self.COLOURS:
self._colour = self.COLOURS[value.upper()]
elif value[0] == '#' and len(value) == 7:
self._colour = self.COLOUR_RGB % tuple(
int(i, 16) for i in (value[1:3], value[3:5], value[5:7]))
else:
raise KeyError
except (KeyError, AttributeError):
warn("Unknown colour (%s); valid choices: [hex (#00ff00), %s]" % (
value, ", ".join(self.COLOURS)),
TqdmWarning, stacklevel=2)
self._colour = None
def __format__(self, format_spec):
if format_spec:
_type = format_spec[-1].lower()
try:
charset = {'a': self.ASCII, 'u': self.UTF, 'b': self.BLANK}[_type]
except KeyError:
charset = self.charset
else:
format_spec = format_spec[:-1]
if format_spec:
N_BARS = int(format_spec)
if N_BARS < 0:
N_BARS += self.default_len
else:
N_BARS = self.default_len
else:
charset = self.charset
N_BARS = self.default_len
nsyms = len(charset) - 1
bar_length, frac_bar_length = divmod(int(self.frac * N_BARS * nsyms), nsyms)
res = charset[-1] * bar_length
if bar_length < N_BARS: # whitespace padding
res = res + charset[frac_bar_length] + charset[0] * (N_BARS - bar_length - 1)
return self.colour + res + self.COLOUR_RESET if self.colour else res
class EMA(object):
"""
Exponential moving average: smoothing to give progressively lower
weights to older values.
Parameters
----------
smoothing : float, optional
Smoothing factor in range [0, 1], [default: 0.3].
Increase to give more weight to recent values.
Ranges from 0 (yields old value) to 1 (yields new value).
"""
def __init__(self, smoothing=0.3):
self.alpha = smoothing
self.last = 0
self.calls = 0
def __call__(self, x=None):
"""
Parameters
----------
x : float
New value to include in EMA.
"""
beta = 1 - self.alpha
if x is not None:
self.last = self.alpha * x + beta * self.last
self.calls += 1
return self.last / (1 - beta ** self.calls) if self.calls else self.last
class tqdm(Comparable):
"""
Decorate an iterable object, returning an iterator which acts exactly
like the original iterable, but prints a dynamically updating
progressbar every time a value is requested.
Parameters
----------
iterable : iterable, optional
Iterable to decorate with a progressbar.
Leave blank to manually manage the updates.
desc : str, optional
Prefix for the progressbar.
total : int or float, optional
The number of expected iterations. If unspecified,
len(iterable) is used if possible. If float("inf") or as a last
resort, only basic progress statistics are displayed
(no ETA, no progressbar).
If `gui` is True and this parameter needs subsequent updating,
specify an initial arbitrary large positive number,
e.g. 9e9.
leave : bool, optional
If [default: True], keeps all traces of the progressbar
upon termination of iteration.
If `None`, will leave only if `position` is `0`.
file : `io.TextIOWrapper` or `io.StringIO`, optional
Specifies where to output the progress messages
(default: sys.stderr). Uses `file.write(str)` and `file.flush()`
methods. For encoding, see `write_bytes`.
ncols : int, optional
The width of the entire output message. If specified,
dynamically resizes the progressbar to stay within this bound.
If unspecified, attempts to use environment width. The
fallback is a meter width of 10 and no limit for the counter and
statistics. If 0, will not print any meter (only stats).
mininterval : float, optional
Minimum progress display update interval [default: 0.1] seconds.
maxinterval : float, optional
Maximum progress display update interval [default: 10] seconds.
Automatically adjusts `miniters` to correspond to `mininterval`
after long display update lag. Only works if `dynamic_miniters`
or monitor thread is enabled.
miniters : int or float, optional
Minimum progress display update interval, in iterations.
If 0 and `dynamic_miniters`, will automatically adjust to equal
`mininterval` (more CPU efficient, good for tight loops).
If > 0, will skip display of specified number of iterations.
Tweak this and `mininterval` to get very efficient loops.
If your progress is erratic with both fast and slow iterations
(network, skipping items, etc) you should set miniters=1.
ascii : bool or str, optional
If unspecified or False, use unicode (smooth blocks) to fill
the meter. The fallback is to use ASCII characters " 123456789#".
disable : bool, optional
Whether to disable the entire progressbar wrapper
[default: False]. If set to None, disable on non-TTY.
unit : str, optional
String that will be used to define the unit of each iteration
[default: it].
unit_scale : bool or int or float, optional
If 1 or True, the number of iterations will be reduced/scaled
automatically and a metric prefix following the
International System of Units standard will be added
(kilo, mega, etc.) [default: False]. If any other non-zero
number, will scale `total` and `n`.
dynamic_ncols : bool, optional
If set, constantly alters `ncols` and `nrows` to the
environment (allowing for window resizes) [default: False].
smoothing : float, optional
Exponential moving average smoothing factor for speed estimates
(ignored in GUI mode). Ranges from 0 (average speed) to 1
(current/instantaneous speed) [default: 0.3].
bar_format : str, optional
Specify a custom bar string formatting. May impact performance.
[default: '{l_bar}{bar}{r_bar}'], where
l_bar='{desc}: {percentage:3.0f}%|' and
r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
'{rate_fmt}{postfix}]'
Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
rate, rate_fmt, rate_noinv, rate_noinv_fmt,
rate_inv, rate_inv_fmt, postfix, unit_divisor,
remaining, remaining_s, eta.
Note that a trailing ": " is automatically removed after {desc}
if the latter is empty.
initial : int or float, optional
The initial counter value. Useful when restarting a progress
bar [default: 0]. If using float, consider specifying `{n:.3f}`
or similar in `bar_format`, or specifying `unit_scale`.
position : int, optional
Specify the line offset to print this bar (starting from 0)
Automatic if unspecified.
Useful to manage multiple bars at once (eg, from threads).
postfix : dict or *, optional
Specify additional stats to display at the end of the bar.
Calls `set_postfix(**postfix)` if possible (dict).
unit_divisor : float, optional
[default: 1000], ignored unless `unit_scale` is True.
write_bytes : bool, optional
Whether to write bytes. If (default: False) will write unicode.
lock_args : tuple, optional
Passed to `refresh` for intermediate output
(initialisation, iterating, and updating).
nrows : int, optional
The screen height. If specified, hides nested bars outside this
bound. If unspecified, attempts to use environment height.
The fallback is 20.
colour : str, optional
Bar colour (e.g. 'green', '#00ff00').
delay : float, optional
Don't display until [default: 0] seconds have elapsed.
gui : bool, optional
WARNING: internal parameter - do not use.
Use tqdm.gui.tqdm(...) instead. If set, will attempt to use
matplotlib animations for a graphical output [default: False].
Returns
-------
out : decorated iterator.
"""
monitor_interval = 10 # set to 0 to disable the thread
monitor = None
_instances = WeakSet()
@staticmethod
def format_sizeof(num, suffix='', divisor=1000):
"""
Formats a number (greater than unity) with SI Order of Magnitude
prefixes.
Parameters
----------
num : float
Number ( >= 1) to format.
suffix : str, optional
Post-postfix [default: ''].
divisor : float, optional
Divisor between prefixes [default: 1000].
Returns
-------
out : str
Number with Order of Magnitude SI unit postfix.
"""
for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 999.5:
if abs(num) < 99.95:
if abs(num) < 9.995:
return '{0:1.2f}'.format(num) + unit + suffix
return '{0:2.1f}'.format(num) + unit + suffix
return '{0:3.0f}'.format(num) + unit + suffix
num /= divisor
return '{0:3.1f}Y'.format(num) + suffix
@staticmethod
def format_interval(t):
"""
Formats a number of seconds as a clock time, [H:]MM:SS
Parameters
----------
t : int
Number of seconds.
Returns
-------
out : str
[H:]MM:SS
"""
mins, s = divmod(int(t), 60)
h, m = divmod(mins, 60)
if h:
return '{0:d}:{1:02d}:{2:02d}'.format(h, m, s)
else:
return '{0:02d}:{1:02d}'.format(m, s)
@staticmethod
def format_num(n):
"""
Intelligent scientific notation (.3g).
Parameters
----------
n : int or float or Numeric
A Number.
Returns
-------
out : str
Formatted number.
"""
f = '{0:.3g}'.format(n).replace('+0', '+').replace('-0', '-')
n = str(n)
return f if len(f) < len(n) else n
@staticmethod
def status_printer(file):
"""
Manage the printing and in-place updating of a line of characters.
Note that if the string is longer than a line, then in-place
updating may not work (it will print a new line at each refresh).
"""
fp = file
fp_flush = getattr(fp, 'flush', lambda: None) # pragma: no cover
if fp in (sys.stderr, sys.stdout):
getattr(sys.stderr, 'flush', lambda: None)()
getattr(sys.stdout, 'flush', lambda: None)()
def fp_write(s):
fp.write(str(s))
fp_flush()
last_len = [0]
def print_status(s):
len_s = disp_len(s)
fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))
last_len[0] = len_s
return print_status
@staticmethod
def format_meter(n, total, elapsed, ncols=None, prefix='', ascii=False, unit='it',
unit_scale=False, rate=None, bar_format=None, postfix=None,
unit_divisor=1000, initial=0, colour=None, **extra_kwargs):
"""
Return a string-based progress bar given some parameters
Parameters
----------
n : int or float
Number of finished iterations.
total : int or float
The expected total number of iterations. If meaningless (None),
only basic progress statistics are displayed (no ETA).
elapsed : float
Number of seconds passed since start.
ncols : int, optional
The width of the entire output message. If specified,
dynamically resizes `{bar}` to stay within this bound
[default: None]. If `0`, will not print any bar (only stats).
The fallback is `{bar:10}`.
prefix : str, optional
Prefix message (included in total width) [default: ''].
Use as {desc} in bar_format string.
ascii : bool, optional or str, optional
If not set, use unicode (smooth blocks) to fill the meter
[default: False]. The fallback is to use ASCII characters
" 123456789#".
unit : str, optional
The iteration unit [default: 'it'].
unit_scale : bool or int or float, optional
If 1 or True, the number of iterations will be printed with an
appropriate SI metric prefix (k = 10^3, M = 10^6, etc.)
[default: False]. If any other non-zero number, will scale
`total` and `n`.
rate : float, optional
Manual override for iteration rate.
If [default: None], uses n/elapsed.
bar_format : str, optional
Specify a custom bar string formatting. May impact performance.
[default: '{l_bar}{bar}{r_bar}'], where
l_bar='{desc}: {percentage:3.0f}%|' and
r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, '
'{rate_fmt}{postfix}]'
Possible vars: l_bar, bar, r_bar, n, n_fmt, total, total_fmt,
percentage, elapsed, elapsed_s, ncols, nrows, desc, unit,
rate, rate_fmt, rate_noinv, rate_noinv_fmt,
rate_inv, rate_inv_fmt, postfix, unit_divisor,
remaining, remaining_s, eta.
Note that a trailing ": " is automatically removed after {desc}
if the latter is empty.
postfix : *, optional
Similar to `prefix`, but placed at the end
(e.g. for additional stats).
Note: postfix is usually a string (not a dict) for this method,
and will if possible be set to postfix = ', ' + postfix.
However other types are supported (#382).
unit_divisor : float, optional
[default: 1000], ignored unless `unit_scale` is True.
initial : int or float, optional
The initial counter value [default: 0].
colour : str, optional
Bar colour (e.g. 'green', '#00ff00').
Returns
-------
out : Formatted meter and stats, ready to display.
"""
# sanity check: total
if total and n >= (total + 0.5): # allow float imprecision (#849)
total = None
# apply custom scale if necessary
if unit_scale and unit_scale not in (True, 1):
if total:
total *= unit_scale
n *= unit_scale
if rate:
rate *= unit_scale # by default rate = self.avg_dn / self.avg_dt
unit_scale = False
elapsed_str = tqdm.format_interval(elapsed)
# if unspecified, attempt to use rate = average speed
# (we allow manual override since predicting time is an arcane art)
if rate is None and elapsed:
rate = (n - initial) / elapsed
inv_rate = 1 / rate if rate else None
format_sizeof = tqdm.format_sizeof
rate_noinv_fmt = ((format_sizeof(rate) if unit_scale else
'{0:5.2f}'.format(rate)) if rate else '?') + unit + '/s'
rate_inv_fmt = (
(format_sizeof(inv_rate) if unit_scale else '{0:5.2f}'.format(inv_rate))
if inv_rate else '?') + 's/' + unit
rate_fmt = rate_inv_fmt if inv_rate and inv_rate > 1 else rate_noinv_fmt
if unit_scale:
n_fmt = format_sizeof(n, divisor=unit_divisor)
total_fmt = format_sizeof(total, divisor=unit_divisor) if total is not None else '?'
else:
n_fmt = str(n)
total_fmt = str(total) if total is not None else '?'
try:
postfix = ', ' + postfix if postfix else ''
except TypeError:
pass
remaining = (total - n) / rate if rate and total else 0
remaining_str = tqdm.format_interval(remaining) if rate else '?'
try:
eta_dt = (datetime.now() + timedelta(seconds=remaining)
if rate and total else datetime.utcfromtimestamp(0))
except OverflowError:
eta_dt = datetime.max
# format the stats displayed to the left and right sides of the bar
if prefix:
# old prefix setup work around
bool_prefix_colon_already = (prefix[-2:] == ": ")
l_bar = prefix if bool_prefix_colon_already else prefix + ": "
else:
l_bar = ''
r_bar = f'| {n_fmt}/{total_fmt} [{elapsed_str}<{remaining_str}, {rate_fmt}{postfix}]'
# Custom bar formatting
# Populate a dict with all available progress indicators
format_dict = {
# slight extension of self.format_dict
'n': n, 'n_fmt': n_fmt, 'total': total, 'total_fmt': total_fmt,
'elapsed': elapsed_str, 'elapsed_s': elapsed,
'ncols': ncols, 'desc': prefix or '', 'unit': unit,
'rate': inv_rate if inv_rate and inv_rate > 1 else rate,
'rate_fmt': rate_fmt, 'rate_noinv': rate,
'rate_noinv_fmt': rate_noinv_fmt, 'rate_inv': inv_rate,
'rate_inv_fmt': rate_inv_fmt,
'postfix': postfix, 'unit_divisor': unit_divisor,
'colour': colour,
# plus more useful definitions
'remaining': remaining_str, 'remaining_s': remaining,
'l_bar': l_bar, 'r_bar': r_bar, 'eta': eta_dt,
**extra_kwargs}
# total is known: we can predict some stats
if total:
# fractional and percentage progress
frac = n / total
percentage = frac * 100
l_bar += '{0:3.0f}%|'.format(percentage)
if ncols == 0:
return l_bar[:-1] + r_bar[1:]
format_dict.update(l_bar=l_bar)
if bar_format:
format_dict.update(percentage=percentage)
# auto-remove colon for empty `{desc}`
if not prefix:
bar_format = bar_format.replace("{desc}: ", '')
else:
bar_format = "{l_bar}{bar}{r_bar}"
full_bar = FormatReplace()
nobar = bar_format.format(bar=full_bar, **format_dict)
if not full_bar.format_called:
return nobar # no `{bar}`; nothing else to do
# Formatting progress bar space available for bar's display
full_bar = Bar(frac,
max(1, ncols - disp_len(nobar)) if ncols else 10,
charset=Bar.ASCII if ascii is True else ascii or Bar.UTF,
colour=colour)
if not _is_ascii(full_bar.charset) and _is_ascii(bar_format):
bar_format = str(bar_format)
res = bar_format.format(bar=full_bar, **format_dict)
return disp_trim(res, ncols) if ncols else res
elif bar_format:
# user-specified bar_format but no total
l_bar += '|'
format_dict.update(l_bar=l_bar, percentage=0)
full_bar = FormatReplace()
nobar = bar_format.format(bar=full_bar, **format_dict)
if not full_bar.format_called:
return nobar
full_bar = Bar(0,
max(1, ncols - disp_len(nobar)) if ncols else 10,
charset=Bar.BLANK, colour=colour)
res = bar_format.format(bar=full_bar, **format_dict)
return disp_trim(res, ncols) if ncols else res
else:
# no total: no progressbar, ETA, just progress stats
return (f'{(prefix + ": ") if prefix else ""}'
f'{n_fmt}{unit} [{elapsed_str}, {rate_fmt}{postfix}]')
def __new__(cls, *_, **__):
instance = object.__new__(cls)
with cls.get_lock(): # also constructs lock if non-existent
cls._instances.add(instance)
# create monitoring thread
if cls.monitor_interval and (cls.monitor is None
or not cls.monitor.report()):
try:
cls.monitor = TMonitor(cls, cls.monitor_interval)
except Exception as e: # pragma: nocover
warn("tqdm:disabling monitor support"
" (monitor_interval = 0) due to:\n" + str(e),
TqdmMonitorWarning, stacklevel=2)
cls.monitor_interval = 0
return instance
@classmethod
def _get_free_pos(cls, instance=None):
"""Skips specified instance."""
positions = {abs(inst.pos) for inst in cls._instances
if inst is not instance and hasattr(inst, "pos")}
return min(set(range(len(positions) + 1)).difference(positions))
@classmethod
def _decr_instances(cls, instance):
"""
Remove from list and reposition another unfixed bar
to fill the new gap.
This means that by default (where all nested bars are unfixed),
order is not maintained but screen flicker/blank space is minimised.
(tqdm<=4.44.1 moved ALL subsequent unfixed bars up.)
"""
with cls._lock:
try:
cls._instances.remove(instance)
except KeyError:
# if not instance.gui: # pragma: no cover
# raise
pass # py2: maybe magically removed already
# else:
if not instance.gui:
last = (instance.nrows or 20) - 1
# find unfixed (`pos >= 0`) overflow (`pos >= nrows - 1`)
instances = list(filter(
lambda i: hasattr(i, "pos") and last <= i.pos,
cls._instances))
# set first found to current `pos`
if instances:
inst = min(instances, key=lambda i: i.pos)
inst.clear(nolock=True)
inst.pos = abs(instance.pos)
@classmethod
def write(cls, s, file=None, end="\n", nolock=False):
"""Print a message via tqdm (without overlap with bars)."""
fp = file if file is not None else sys.stdout
with cls.external_write_mode(file=file, nolock=nolock):
# Write the message
fp.write(s)
fp.write(end)
@classmethod
@contextmanager
def external_write_mode(cls, file=None, nolock=False):
"""
Disable tqdm within context and refresh tqdm when exits.
Useful when writing to standard output stream
"""
fp = file if file is not None else sys.stdout
try:
if not nolock:
cls.get_lock().acquire()
# Clear all bars
inst_cleared = []
for inst in getattr(cls, '_instances', []):
# Clear instance if in the target output file
# or if write output + tqdm output are both either
# sys.stdout or sys.stderr (because both are mixed in terminal)
if hasattr(inst, "start_t") and (inst.fp == fp or all(
f in (sys.stdout, sys.stderr) for f in (fp, inst.fp))):
inst.clear(nolock=True)
inst_cleared.append(inst)
yield
# Force refresh display of bars we cleared
for inst in inst_cleared:
inst.refresh(nolock=True)
finally:
if not nolock:
cls._lock.release()
@classmethod
def set_lock(cls, lock):
"""Set the global lock."""
cls._lock = lock
@classmethod
def get_lock(cls):
"""Get the global lock. Construct it if it does not exist."""
if not hasattr(cls, '_lock'):
cls._lock = TqdmDefaultWriteLock()
return cls._lock
@classmethod
def pandas(cls, **tqdm_kwargs):
"""
Registers the current `tqdm` class with
pandas.core.
( frame.DataFrame
| series.Series
| groupby.(generic.)DataFrameGroupBy
| groupby.(generic.)SeriesGroupBy
).progress_apply
A new instance will be created every time `progress_apply` is called,
and each instance will automatically `close()` upon completion.
Parameters
----------
tqdm_kwargs : arguments for the tqdm instance
Examples
--------
>>> import pandas as pd
>>> import numpy as np
>>> from tqdm import tqdm
>>> from tqdm.gui import tqdm as tqdm_gui
>>>
>>> df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
>>> tqdm.pandas(ncols=50) # can use tqdm_gui, optional kwargs, etc
>>> # Now you can use `progress_apply` instead of `apply`
>>> df.groupby(0).progress_apply(lambda x: x**2)
References
----------
<https://stackoverflow.com/questions/18603270/\
progress-indicator-during-pandas-operations-python>
"""
try:
with catch_warnings():
simplefilter("ignore", category=FutureWarning)
except ImportError: # pandas>=1.2.0
Panel = None
Rolling, Expanding = None, None
try: # pandas>=1.0.0
except ImportError:
try: # pandas>=0.18.0
except ImportError: # pandas>=1.2.0
try: # pandas>=1.2.0
_Rolling_and_Expanding = Rolling, Expanding
except ImportError: # pragma: no cover
_Rolling_and_Expanding = None
try: # pandas>=0.25.0
except ImportError: # pragma: no cover
try: # pandas>=0.23.0
except ImportError:
try: # pandas>=0.23.0
except ImportError: # pragma: no cover
try: # pandas>=0.23.0
except ImportError:
try:
except ImportError: # pandas>=0.25.0
PanelGroupBy = None
tqdm_kwargs = tqdm_kwargs.copy()
deprecated_t = [tqdm_kwargs.pop('deprecated_t', None)]
def inner_generator(df_function='apply'):
def inner(df, func, *args, **kwargs):
"""
Parameters
----------
df : (DataFrame|Series)[GroupBy]
Data (may be grouped).
func : function
To be applied on the (grouped) data.
**kwargs : optional
Transmitted to `df.apply()`.
"""
# Precompute total iterations
total = tqdm_kwargs.pop("total", getattr(df, 'ngroups', None))
if total is None: # not grouped
if df_function == 'applymap':
total = df.size
elif isinstance(df, Series):
total = len(df)
elif (_Rolling_and_Expanding is None or
not isinstance(df, _Rolling_and_Expanding)):
# DataFrame or Panel
axis = kwargs.get('axis', 0)
if axis == 'index':
axis = 0
elif axis == 'columns':
axis = 1
# when axis=0, total is shape[axis1]
total = df.size // df.shape[axis]
# Init bar
if deprecated_t[0] is not None:
t = deprecated_t[0]
deprecated_t[0] = None
else:
t = cls(total=total, **tqdm_kwargs)
if len(args) > 0:
# *args intentionally not supported (see #244, #299)
TqdmDeprecationWarning(
"Except func, normal arguments are intentionally" +
" not supported by" +
" `(DataFrame|Series|GroupBy).progress_apply`." +
" Use keyword arguments instead.",
fp_write=getattr(t.fp, 'write', sys.stderr.write))
try: # pandas>=1.3.0
except ImportError:
is_builtin_func = df._is_builtin_func
try:
func = is_builtin_func(func)
except TypeError:
pass
# Define bar updating wrapper
def wrapper(*args, **kwargs):
# update tbar correctly
# it seems `pandas apply` calls `func` twice
# on the first column/row to decide whether it can
# take a fast or slow code path; so stop when t.total==t.n
t.update(n=1 if not t.total or t.n < t.total else 0)
return func(*args, **kwargs)
# Apply the provided function (in **kwargs)
# on the df using our wrapper (which provides bar updating)
try:
return getattr(df, df_function)(wrapper, **kwargs)
finally:
t.close()
return inner
# Monkeypatch pandas to provide easy methods
# Enable custom tqdm progress in pandas!
Series.progress_apply = inner_generator()
SeriesGroupBy.progress_apply = inner_generator()
Series.progress_map = inner_generator('map')
SeriesGroupBy.progress_map = inner_generator('map')
DataFrame.progress_apply = inner_generator()
DataFrameGroupBy.progress_apply = inner_generator()
DataFrame.progress_applymap = inner_generator('applymap')
if Panel is not None:
Panel.progress_apply = inner_generator()
if PanelGroupBy is not None:
PanelGroupBy.progress_apply = inner_generator()
GroupBy.progress_apply = inner_generator()
GroupBy.progress_aggregate = inner_generator('aggregate')
GroupBy.progress_transform = inner_generator('transform')
if Rolling is not None and Expanding is not None:
Rolling.progress_apply = inner_generator()
Expanding.progress_apply = inner_generator()
elif _Rolling_and_Expanding is not None:
_Rolling_and_Expanding.progress_apply = inner_generator()
# override defaults via env vars
@envwrap("TQDM_", is_method=True, types={'total': float, 'ncols': int, 'miniters': float,
'position': int, 'nrows': int})
def __init__(self, iterable=None, desc=None, total=None, leave=True, file=None,
ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None,
ascii=None, disable=False, unit='it', unit_scale=False,
dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0,
position=None, postfix=None, unit_divisor=1000, write_bytes=False,
lock_args=None, nrows=None, colour=None, delay=0.0, gui=False,
**kwargs):
"""see tqdm.tqdm for arguments"""
if file is None:
file = sys.stderr
if write_bytes:
# Despite coercing unicode into bytes, py2 sys.std* streams
# should have bytes written to them. | file = SimpleTextIOWrapper( | 5 | 2023-12-24 15:46:18+00:00 | 8k |
willfinnigan/RetroBioCat_2 | rbc2/expansion/expanders/chemistry_expanders.py | [
{
"identifier": "Expansion_Config",
"path": "rbc2/configs/expansion_config.py",
"snippet": "class Expansion_Config():\n\n def __init__(self):\n\n # rule application\n self.allow_chiral_symmetry = False\n self.check_chiral_products = True\n self.combine_enantiomers = True\n... | from typing import Optional
from rbc2.configs.expansion_config import Expansion_Config
from rbc2.expansion.expanders.action_getters.aizynthfinder.aizynthfinder_actions import \
AizynthfinderActionGetter
from rbc2.expansion.expanders.action_getters.askcos.askcos_action_getter import Askcos_Action_Getter
from rbc2.expansion.expanders.action_getters.ring_breaker.ringbreaker_actions import \
RingBreaker_ActionGetter
from rbc2.expansion.default_expander_interface import DefaultExpander
from rbc2.reaction_network_entities.network import Network | 5,785 |
class AIZynthfinderExpander(DefaultExpander):
def __init__(self,
network: Optional[Network] = None,
config: Optional[Expansion_Config] = None,
template_column='retro_template',
cutoff_cumulative=0.995,
cutoff_number=50):
super().__init__(network=network, config=config)
self.action_getter = AizynthfinderActionGetter(template_column=template_column,
cutoff_cumulative=cutoff_cumulative,
cutoff_number=cutoff_number)
self.rxn_type = 'aizynthfinder'
self.rxn_domain = 'chemistry'
self.score_key = 'policy_probability'
class RingBreakerPolicyExpander(DefaultExpander):
def __init__(self,
network: Optional[Network] = None,
config: Optional[Expansion_Config] = None,
cutoff_cumulative=0.995,
cutoff_number=10):
super().__init__(network=network, config=config)
|
class AIZynthfinderExpander(DefaultExpander):
def __init__(self,
network: Optional[Network] = None,
config: Optional[Expansion_Config] = None,
template_column='retro_template',
cutoff_cumulative=0.995,
cutoff_number=50):
super().__init__(network=network, config=config)
self.action_getter = AizynthfinderActionGetter(template_column=template_column,
cutoff_cumulative=cutoff_cumulative,
cutoff_number=cutoff_number)
self.rxn_type = 'aizynthfinder'
self.rxn_domain = 'chemistry'
self.score_key = 'policy_probability'
class RingBreakerPolicyExpander(DefaultExpander):
def __init__(self,
network: Optional[Network] = None,
config: Optional[Expansion_Config] = None,
cutoff_cumulative=0.995,
cutoff_number=10):
super().__init__(network=network, config=config)
| self.action_getter = RingBreaker_ActionGetter(cutoff_number=cutoff_number, | 3 | 2023-12-30 11:33:41+00:00 | 8k |
gregorybchris/typogenetics | tests/test_typogenetics.py | [
{
"identifier": "Base",
"path": "typogenetics/typogenetics.py",
"snippet": "class Base(StrEnum):\n C = auto()\n G = auto()\n T = auto()\n A = auto()\n\n @classmethod\n def from_str(cls, base_str: str) -> \"Base\":\n return {\n \"C\": cls.C,\n \"G\": cls.G,\... | from typogenetics.typogenetics import Base, Enzyme, Folder, Orientation, Rewriter, Strand, Translator | 4,263 |
class TestTypogenetics:
def test_strand_from_str(self) -> None:
assert Strand.from_str("CG GA TA CT AA AC CG A") == Strand(
[
Base.C,
Base.G,
Base.G,
Base.A,
Base.T,
Base.A,
Base.C,
Base.T,
Base.A,
Base.A,
Base.A,
Base.C,
Base.C,
Base.G,
Base.A,
]
)
def test_translator(self) -> None:
strand = Strand.from_str("CG GA TA CT AA AC CG A")
assert Translator.translate(strand) == [
Enzyme.from_str("cop-ina-rpy-off"),
Enzyme.from_str("cut-cop"),
]
def test_folder(self) -> None:
enzyme = Enzyme.from_str("cop-ina-rpy-off")
strand = Strand.from_str("CG GA TA CT AA AC CG A")
|
class TestTypogenetics:
def test_strand_from_str(self) -> None:
assert Strand.from_str("CG GA TA CT AA AC CG A") == Strand(
[
Base.C,
Base.G,
Base.G,
Base.A,
Base.T,
Base.A,
Base.C,
Base.T,
Base.A,
Base.A,
Base.A,
Base.C,
Base.C,
Base.G,
Base.A,
]
)
def test_translator(self) -> None:
strand = Strand.from_str("CG GA TA CT AA AC CG A")
assert Translator.translate(strand) == [
Enzyme.from_str("cop-ina-rpy-off"),
Enzyme.from_str("cut-cop"),
]
def test_folder(self) -> None:
enzyme = Enzyme.from_str("cop-ina-rpy-off")
strand = Strand.from_str("CG GA TA CT AA AC CG A") | assert Folder.fold(enzyme) == Orientation.D | 2 | 2023-12-28 08:59:06+00:00 | 8k |
DerwenAI/textgraphs | textgraphs/pipe.py | [
{
"identifier": "SPACY_MODEL",
"path": "textgraphs/defaults.py",
"snippet": "SPACY_MODEL: str = \"en_core_web_sm\""
},
{
"identifier": "Edge",
"path": "textgraphs/elem.py",
"snippet": "class Edge:\n \"\"\"\nA data class representing an edge between two nodes.\n \"\"\"\n src_node... | import abc
import asyncio
import functools
import itertools
import operator
import traceback
import typing
import networkx as nx # pylint: disable=E0401
import spacy # pylint: disable=E0401
from icecream import ic # pylint: disable=E0401,W0611
from .defaults import SPACY_MODEL
from .elem import Edge, Node, NodeEnum, NounChunk
from .graph import SimpleGraph | 4,434 | """
for src, iri, dst in self.gen_triples(pipe, debug = debug):
await queue.put(( src, iri, dst, ))
class Pipeline: # pylint: disable=R0902,R0903
"""
Manage parsing of a document, which is assumed to be paragraph-sized.
"""
def __init__ ( # pylint: disable=R0913
self,
text_input: str,
tok_pipe: spacy.Language,
ner_pipe: spacy.Language,
aux_pipe: spacy.Language,
kg: KnowledgeGraph, # pylint: disable=C0103
infer_rels: typing.List[ InferRel ],
) -> None:
"""
Constructor.
text_input:
raw text to be parsed
tok_pipe:
the `spaCy.Language` pipeline used for tallying individual tokens
ner_pipe:
the `spaCy.Language` pipeline used for tallying named entities
aux_pipe:
the `spaCy.Language` pipeline used for auxiliary components (e.g., `DBPedia Spotlight`)
kg:
knowledge graph used for entity linking
infer_rels:
a list of components for inferring relations
"""
self.text: str = text_input
# `tok_doc` provides a stream of individual tokens
self.tok_doc: spacy.tokens.Doc = tok_pipe(self.text)
# `ner_doc` provides the merged-entity spans from NER
self.ner_doc: spacy.tokens.Doc = ner_pipe(self.text)
# `aux_doc` e.g., span re-indexing for Spotlight entity linking
self.aux_doc: spacy.tokens.Doc = aux_pipe(self.text)
self.kg: KnowledgeGraph = kg # pylint: disable=C0103
self.infer_rels: typing.List[ InferRel ] = infer_rels
# list of Node objects for each parsed token, in sequence
self.tokens: typing.List[ Node ] = []
# set of Edge objects generated by this Pipeline
self.edges: typing.List[ Edge ] = []
@classmethod
def get_lemma_key (
cls,
span: typing.Union[ spacy.tokens.span.Span, spacy.tokens.token.Token ],
*,
placeholder: bool = False,
) -> str:
"""
Compose a unique, invariant lemma key for the given span.
span:
span of tokens within the lemma
placeholder:
flag for whether to create a placeholder
returns:
a composed lemma key
"""
if isinstance(span, spacy.tokens.token.Token):
terms: typing.List[ str ] = [
span.lemma_.strip().lower(),
span.pos_,
]
if placeholder:
terms.insert(0, str(span.i))
else:
terms = functools.reduce(
operator.iconcat,
[
[ token.lemma_.strip().lower(), token.pos_, ]
for token in span
],
[],
)
return ".".join(terms)
def get_ent_lemma_keys (
self,
) -> typing.Iterator[ typing.Tuple[ str, int ]]:
"""
Iterate through the fully qualified lemma keys for an extracted entity.
yields:
the lemma keys within an extracted entity
"""
for ent in self.tok_doc.ents:
yield self.get_lemma_key(ent), len(ent)
def link_noun_chunks (
self,
nodes: dict,
*,
debug: bool = False,
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Leveraging a factory pattern for NLP pipelines.
This class handles processing for one "chunk" of raw text input to
analyze, which is typically a paragraph. In other words, objects in
this class are expected to get recycled when processing moves on to
the next paragraph, to ease memory requirements.
see copyright/license https://huggingface.co/spaces/DerwenAI/textgraphs/blob/main/README.md
"""
######################################################################
## class definitions
class Component (abc.ABC): # pylint: disable=R0903
"""
Abstract base class for a `spaCy` pipeline component.
"""
@abc.abstractmethod
def augment_pipe (
self,
factory: "PipelineFactory",
) -> None:
"""
Encapsulate a `spaCy` call to `add_pipe()` configuration.
factory:
a `PipelineFactory` used to configure components
"""
raise NotImplementedError
class KnowledgeGraph (Component):
"""
Base class for a _knowledge graph_ interface.
"""
def augment_pipe (
self,
factory: "PipelineFactory",
) -> None:
"""
Encapsulate a `spaCy` call to `add_pipe()` configuration.
factory:
a `PipelineFactory` used to configure components
"""
pass # pylint: disable=W0107
def remap_ner (
self,
label: typing.Optional[ str ],
) -> typing.Optional[ str ]:
"""
Remap the OntoTypes4 values from NER output to more general-purpose IRIs.
label:
input NER label, an `OntoTypes4` value
returns:
an IRI for the named entity
"""
return label
def normalize_prefix (
self,
iri: str,
*,
debug: bool = False, # pylint: disable=W0613
) -> str:
"""
Normalize the given IRI to use standard namespace prefixes.
iri:
input IRI, in fully-qualified domain representation
debug:
debugging flag
returns:
the compact IRI representation, using an RDF namespace prefix
"""
return iri
def perform_entity_linking (
self,
graph: SimpleGraph,
pipe: "Pipeline",
*,
debug: bool = False,
) -> None:
"""
Perform _entity linking_ based on "spotlight" and other services.
graph:
source graph
pipe:
configured pipeline for the current document
debug:
debugging flag
"""
pass # pylint: disable=W0107
def resolve_rel_iri (
self,
rel: str,
*,
lang: str = "en", # pylint: disable=W0613
debug: bool = False, # pylint: disable=W0613
) -> typing.Optional[ str ]:
"""
Resolve a `rel` string from a _relation extraction_ model which has
been trained on this knowledge graph.
rel:
relation label, generation these source from Wikidata for many RE projects
lang:
language identifier
debug:
debugging flag
returns:
a resolved IRI
"""
return rel
class InferRel (abc.ABC): # pylint: disable=R0903
"""
Abstract base class for a _relation extraction_ model wrapper.
"""
@abc.abstractmethod
def gen_triples (
self,
pipe: "Pipeline",
*,
debug: bool = False,
) -> typing.Iterator[typing.Tuple[ Node, str, Node ]]:
"""
Infer relations as triples through a generator _iteratively_.
pipe:
configured pipeline for the current document
debug:
debugging flag
yields:
generated triples
"""
raise NotImplementedError
async def gen_triples_async (
self,
pipe: "Pipeline",
queue: asyncio.Queue,
*,
debug: bool = False,
) -> None:
"""
Infer relations as triples produced to a queue _concurrently_.
pipe:
configured pipeline for the current document
queue:
queue of inference tasks to be performed
debug:
debugging flag
"""
for src, iri, dst in self.gen_triples(pipe, debug = debug):
await queue.put(( src, iri, dst, ))
class Pipeline: # pylint: disable=R0902,R0903
"""
Manage parsing of a document, which is assumed to be paragraph-sized.
"""
def __init__ ( # pylint: disable=R0913
self,
text_input: str,
tok_pipe: spacy.Language,
ner_pipe: spacy.Language,
aux_pipe: spacy.Language,
kg: KnowledgeGraph, # pylint: disable=C0103
infer_rels: typing.List[ InferRel ],
) -> None:
"""
Constructor.
text_input:
raw text to be parsed
tok_pipe:
the `spaCy.Language` pipeline used for tallying individual tokens
ner_pipe:
the `spaCy.Language` pipeline used for tallying named entities
aux_pipe:
the `spaCy.Language` pipeline used for auxiliary components (e.g., `DBPedia Spotlight`)
kg:
knowledge graph used for entity linking
infer_rels:
a list of components for inferring relations
"""
self.text: str = text_input
# `tok_doc` provides a stream of individual tokens
self.tok_doc: spacy.tokens.Doc = tok_pipe(self.text)
# `ner_doc` provides the merged-entity spans from NER
self.ner_doc: spacy.tokens.Doc = ner_pipe(self.text)
# `aux_doc` e.g., span re-indexing for Spotlight entity linking
self.aux_doc: spacy.tokens.Doc = aux_pipe(self.text)
self.kg: KnowledgeGraph = kg # pylint: disable=C0103
self.infer_rels: typing.List[ InferRel ] = infer_rels
# list of Node objects for each parsed token, in sequence
self.tokens: typing.List[ Node ] = []
# set of Edge objects generated by this Pipeline
self.edges: typing.List[ Edge ] = []
@classmethod
def get_lemma_key (
cls,
span: typing.Union[ spacy.tokens.span.Span, spacy.tokens.token.Token ],
*,
placeholder: bool = False,
) -> str:
"""
Compose a unique, invariant lemma key for the given span.
span:
span of tokens within the lemma
placeholder:
flag for whether to create a placeholder
returns:
a composed lemma key
"""
if isinstance(span, spacy.tokens.token.Token):
terms: typing.List[ str ] = [
span.lemma_.strip().lower(),
span.pos_,
]
if placeholder:
terms.insert(0, str(span.i))
else:
terms = functools.reduce(
operator.iconcat,
[
[ token.lemma_.strip().lower(), token.pos_, ]
for token in span
],
[],
)
return ".".join(terms)
def get_ent_lemma_keys (
self,
) -> typing.Iterator[ typing.Tuple[ str, int ]]:
"""
Iterate through the fully qualified lemma keys for an extracted entity.
yields:
the lemma keys within an extracted entity
"""
for ent in self.tok_doc.ents:
yield self.get_lemma_key(ent), len(ent)
def link_noun_chunks (
self,
nodes: dict,
*,
debug: bool = False, | ) -> typing.List[ NounChunk ]: | 4 | 2023-12-25 11:42:53+00:00 | 8k |
proger/nanokitchen | mixer_seq_simple.py | [
{
"identifier": "Mamba",
"path": "mamba_simple.py",
"snippet": "class Mamba(nn.Module):\n def __init__(\n self,\n d_model,\n d_state=16,\n d_conv=4,\n expand=2,\n dt_rank=\"auto\",\n dt_min=0.001,\n dt_max=0.1,\n dt_init=\"random\",\n ... | import math
import json
import os
import torch
import torch.nn as nn
from functools import partial
from collections import namedtuple
from mamba_ssm.models.config_mamba import MambaConfig
from mamba_ssm.utils.generation import GenerationMixin
from mamba_ssm.utils.hf import load_config_hf, load_state_dict_hf
from mamba_simple import Mamba, Block
from mamba_ssm.ops.triton.layernorm import RMSNorm, layer_norm_fn, rms_norm_fn | 3,838 | # Copyright (c) 2023, Albert Gu, Tri Dao.
try:
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
):
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype}
| # Copyright (c) 2023, Albert Gu, Tri Dao.
try:
except ImportError:
RMSNorm, layer_norm_fn, rms_norm_fn = None, None, None
def create_block(
d_model,
ssm_cfg=None,
norm_epsilon=1e-5,
rms_norm=False,
residual_in_fp32=False,
fused_add_norm=False,
layer_idx=None,
device=None,
dtype=None,
):
if ssm_cfg is None:
ssm_cfg = {}
factory_kwargs = {"device": device, "dtype": dtype} | mixer_cls = partial(Mamba, layer_idx=layer_idx, **ssm_cfg, **factory_kwargs) | 0 | 2023-12-27 12:13:00+00:00 | 8k |
linancn/TianGong-AI-LangServe | src/agents/agent.py | [
{
"identifier": "SearchInternet",
"path": "src/tools/search_internet.py",
"snippet": "class SearchInternet(BaseTool):\n name = \"search_internet_tool\"\n description = \"Search the internet for the up-to-date information.\"\n\n class InputSchema(BaseModel):\n query: str\n\n args_schem... | import os
from dotenv import load_dotenv
from langchain.agents import AgentExecutor
from langchain.agents.format_scratchpad.openai_tools import (
format_to_openai_tool_messages,
)
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser
from langchain.chat_models import ChatOpenAI
from langchain.memory import XataChatMessageHistory
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.tools.render import format_tool_to_openai_tool
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
from src.tools.search_internet import SearchInternet
from src.tools.search_lca_db import SearchLCADB
from src.tools.search_vector_db import SearchVectorDB
from src.tools.search_esg import SearchESG | 4,874 |
load_dotenv()
def init_chat_history(session_id: str) -> BaseChatMessageHistory:
xata_api_key = os.getenv("XATA_API_KEY")
xata_db_url = os.getenv("XATA_DB_URL")
xata_table_name = os.getenv("XATA_TABLE_NAME")
return XataChatMessageHistory(
session_id=session_id,
api_key=xata_api_key,
db_url=xata_db_url,
table_name=xata_table_name,
)
def openai_agent():
# lc_tools = [SearchInternet(), SearchVectorDB(), SearchLCADB(), SearchESG()]
|
load_dotenv()
def init_chat_history(session_id: str) -> BaseChatMessageHistory:
xata_api_key = os.getenv("XATA_API_KEY")
xata_db_url = os.getenv("XATA_DB_URL")
xata_table_name = os.getenv("XATA_TABLE_NAME")
return XataChatMessageHistory(
session_id=session_id,
api_key=xata_api_key,
db_url=xata_db_url,
table_name=xata_table_name,
)
def openai_agent():
# lc_tools = [SearchInternet(), SearchVectorDB(), SearchLCADB(), SearchESG()] | lc_tools = [SearchESG(), SearchInternet()] | 0 | 2023-12-25 06:34:52+00:00 | 8k |
0xn0ne/sensitive-helper | sensitive-helper.py | [
{
"identifier": "compress",
"path": "utils/compress.py",
"snippet": "def zip_info(file_path: pathlib.Path) -> Dict[str, Any]:\ndef uncompress_zip(\n file_path: Union[pathlib.Path, str], extract_dir: Union[pathlib.Path, str] = None, is_error: bool = True\n) -> Union[pathlib.Path, Any]:\ndef is_tar(fil... | import base64
import binascii
import csv
import json
import pathlib
import re
import time
import pandas
import tqdm
import argparse
from typing import Any, AnyStr, Dict, List, Union
from utils import compress, configurator, office, process | 4,252 | return ret
def to_csv(data: Union[Dict[str, Any], List[Dict[str, Any]]], filename: str = 'output.csv'):
"""
输入数据应为:cache = {'a': [1, 0, 9], 'b': [3, 7, 6]}
"""
dataframe = pandas.DataFrame(data)
dataframe.to_csv(filename, quoting=csv.QUOTE_MINIMAL)
# 考虑字典数据、列表数据、函数数据
FUZZY_UNIVERSAL_STRING = r'["\'`]?\s*[=:(\{\[]\s*["\'`][\x20-\x7F]{,128}?[\'"`]'
#
PATH_COMMON_STRING = r'users?|windows?|program files(\(x\d{2,3}\))?|s?bin|etc|usr|boot|dev|home|proc|opt|sys|srv|var'
__DEFAULT_CONFIG = {
'target_path': '',
'config_path': 'config.yaml',
'output_format': 'csv',
'process_number': 5,
'exclude_files': [r'\.DS_Store'],
'row_split': '[\x00-\x1F\x7F]+',
'rules': {
'AKSK': [r'LTAI\w+'],
'JSON WEB TOKEN(JWT)': [r'ey[0-9a-zA-Z/+]{4,}={,2}\.[0-9a-zA-Z/+]{6,}={,2}\.[A-Za-z0-9-_]+'],
'FUZZY MATCH': {
'flags': 'I',
'regexp': [
r'(APP|ACCESS|USER|PASS|OSS|ECS|CVM|AWS)[\w]{,8}(NAME|ID|KEY|NUM|ENC|CODE|SEC|WORD)[\w]{,16}%s'
% FUZZY_UNIVERSAL_STRING,
# 考虑驼峰写法,下划线写法,MAP键值下面单词后必须接大写字母、下划线、中划线,否侧可能出现如:
r'(USR|PWD|COOKIE)[_\-A-Z][\w]{,16}%s' % FUZZY_UNIVERSAL_STRING,
r'(SECRET|SIGN|TOKEN)[\w]{,16}%s' % FUZZY_UNIVERSAL_STRING,
],
},
'BASE64': [r'[0-9a-zA-Z/+]{8,}={,2}'],
'URL': {
'regexp': [r'(ftp|https?):\/\/[%.\w\-]+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?'],
're_filters': [
r'(adobe|amap|android|apache|bing|digicert|eclipse|freecodecamp|github|githubusercontent|gnu|godaddy|google|googlesource|youtube|youtu|jd'
r'|npmjs|microsoft|openxmlformats|outlook|mozilla|openssl|oracle|qq|spring|sun|umang|w3|wikipedia|xml)\.('
r'org|com|cn|net|edu|io|be)',
r'(ali|baidu|cdn|example|ssh|ssl)[\w-]*\.(org|com|cn|net|edu|io)',
],
},
'EMAIL': [r'[a-zA-Z0-9][-+.\w]{1,127}@([a-zA-Z0-9][-a-zA-Z0-9]{0,63}.){,3}(org|com|cn|net|edu|mail)'],
'PHONE': [r'(13[0-9]|14[5-9]|15[0-3,5-9]|16[6]|17[0-8]|18[0-9]|19[8,9])\d{8}'],
'FILE PATH': {
'flags': 'I|X',
'regexp': [
r'([a-z]:\\)?([\\/])(users?|windows?|program files(\(x\d{2,3}\))?|s?bin|etc|usr|boot|dev|home|proc|opt'
r'|sys|srv|var)(\2[.\w!#\(~\[\{][.\w!#&\(\)+=~\[\]\{\}\s]{2,63}){1,16}'
],
're_filters': [
# r'[\\/].*sdk.*',
# r'[\\/](alibaba|aliyun|annotation|apache|chromium|collections|eclipse|facebook|functions|github|google'
# r'|internal|jetbrains|oppo|reactnative|reflect|sdklib|sequences|taobao|tencent|unionpay|view|vivo'
# r'|webkit|xiaomi)',
],
},
},
'is_re_all': False,
'is_silent': False,
}
cfg = {}
if __name__ == '__main__':
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='''
███████╗███████╗███╗ ██╗███████╗██╗████████╗██╗██╗ ██╗███████╗
██╔════╝██╔════╝████╗ ██║██╔════╝██║╚══██╔══╝██║██║ ██║██╔════╝
███████╗█████╗ ██╔██╗ ██║███████╗██║ ██║ ██║██║ ██║█████╗
╚════██║██╔══╝ ██║╚██╗██║╚════██║██║ ██║ ██║╚██╗ ██╔╝██╔══╝
███████║███████╗██║ ╚████║███████║██║ ██║ ██║ ╚████╔╝ ███████╗
╚══════╝╚══════╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚══════╝
v0.1.4
by 0xn0ne, https://github.com/0xn0ne/sensitive-helper
''',
)
parser.add_argument(
'-t',
'--target-path',
required=True,
help='search for file paths or folder paths for sensitive cache (eg. ~/download/folder).',
)
parser.add_argument('-p', '--process-number', default=5, type=int, help='number of program processes (default: 5).')
parser.add_argument(
'-c',
'--config-path',
default='configs.yaml',
help='path to the yaml configuration file (default: configs.yaml).',
)
parser.add_argument('-o', '--output-format', help='output file format, available formats json, csv (default: csv).')
parser.add_argument(
'-e', '--exclude-files', nargs='+', help='excluded files, using regular matching (eg. \\.DS_Store .*bin .*doc).'
)
parser.add_argument(
'-a',
'--is-re-all',
action='store_true',
help='hit a single regular expression per file or match all regular expressions to exit the match loop.',
)
parser.add_argument(
'-s',
'--is-silent',
action='store_true',
help='silent mode: when turned on, no hit data will be output on the console. use a progress bar instead.',
)
args = parser.parse_args()
print(parser.description)
nargs = dict(args.__dict__)
for key in args.__dict__:
if nargs[key] is None:
del nargs[key]
| #!/bin/python3
# _*_ coding:utf-8 _*_
#
# sensitive-helper.py
# 本地文件敏感信息搜索工具
def log_run_times(func):
def wrapper(*args, **kwargs):
s_time = time.time()
ret = func(*args, **kwargs)
total_time = time.time() - s_time
if total_time <= 1:
return ret
with open('run_times.log', 'a') as _f:
_f.write('total time(s): {}, args: {}\n'.format(time.time() - s_time, args[0][:127]))
return ret
return wrapper
def string_to_reg_flags(flags: str):
flags_int = 0
for flag in flags.split('|'):
flags_int |= getattr(re, flag)
return flags_int
def is_filter_base64(result: AnyStr):
if len(result) % 4 != 0:
return True, ''
try:
# 编码错误的全都丢掉,不丢掉也看不懂
ret_extend = base64.b64decode(result).decode('utf-8')
if not re.search(r'^[\u0020-\u007F\u2010-\u202f\u3000-\u301f\u4e00-\u9fa5\uff00-\uffef]+$', ret_extend):
return True, ''
# \u0020-\u007F:英文可视字符集
# \u2010-\u202f:中文部分符号集
# \u3000-\u301f:中文部分符号集
# \u4e00-\u9fa5:中文常见文字集
# \u2e80-\u9fff:中文文字及中文异形文字集
# \uff00-\uffef:中文部分符号集
except UnicodeDecodeError:
return True, ''
except binascii.Error:
return True, ''
return False, ret_extend
def is_filter_jwt(result: AnyStr):
times = 0
res_split = result.split(b'.')
while times < 2:
if len(res_split[times]) % 4 != 0:
return True, ''
times += 1
return False, ''
def is_filter_result(result: AnyStr, filters: List[AnyStr], flags: int):
if not filters:
return False, ''
for fil in filters:
if re.search(fil, result, flags):
return True, ''
return False, ''
# @log_run_times
def search_content(
file_object: Union[pathlib.Path, bytes],
rules: Dict[str, List[str]],
split: bytes = b'[\x00-\x1F\x7F]+',
is_re_all: bool = False,
) -> List[Dict[str, str]]:
ret = []
row_contents = [file_object]
if isinstance(file_object, pathlib.Path):
row_contents = re.split(split, file_object.read_bytes())
for row_one in row_contents:
# 按控制字符进行分割行
if len(row_one) < 12:
# 单行内容少于8个字符,丢掉
continue
for rule_name in rules:
rule = rules[rule_name]
flags = 0
filters = None
if isinstance(rule, Dict):
if 'flags' in rule:
flags = string_to_reg_flags(rule['flags'])
if 're_filters' in rule:
filters = rule['re_filters']
rule = rule['regexp']
for regexp in rule:
r_result = re.search(regexp, row_one, flags)
if not r_result:
continue
try:
result_byte = r_result.group()
result_text = result_byte.decode('utf-8')
except UnicodeDecodeError:
continue
is_filter, extend = is_filter_result(result_byte, filters, flags)
if rule_name == 'BASE64':
is_filter, extend = is_filter_base64(result_byte)
if rule_name == 'JSON WEB TOKEN(JWT)':
is_filter, extend = is_filter_jwt(result_byte)
if is_filter:
continue
ret.append(
{
'file': file_object.__str__(),
'group': rule_name,
'regexp': regexp.decode('utf-8'),
'match': result_text,
'extend': extend,
}
)
if not is_re_all:
# 如果关闭了匹配所有正则组数据且已发现有用数据,则退出循环
return ret
return ret
def gen_file_list(src_path: str, exclude_files: List[str]) -> List[pathlib.Path]:
tar_path = pathlib.Path(src_path)
ret = []
if tar_path.is_file():
ret.append(tar_path)
else:
for filepath in tar_path.glob('**/*'):
is_skip = False
if filepath.is_dir():
continue
filename = filepath.name
for r_exclude in exclude_files:
# 文件名正则匹配,在排除名单中则排除文件
if re.match(r_exclude, filename):
is_skip = True
break
if is_skip:
continue
if filename.endswith('.docx') and not filename.startswith('~$'):
office.docx_handler(filepath)
elif filename.endswith('.xlsx') and not filename.startswith('~$'):
office.xlsx_handler(filepath)
else:
compress.uncompress(filepath, is_error=False, is_recursive=True)
ret.append(filepath)
return ret
def run():
pool = process.ProcessPoolHelper(max_workers=cfg.get('process_number'))
print('[*] file loading...')
filelist = gen_file_list(cfg.get('target_path'), cfg.get('exclude_files'))
if not filelist:
print('[!] the file path is empty. please check whether the path is correct.\n')
return
filelist = sorted(filelist, key=lambda x: x.stat().st_size, reverse=True)
ret = []
result_filter_list = []
groups = cfg.get('rules')
for filepath in filelist:
pool.submit_super(search_content, filepath, groups, cfg.get('row_split'), cfg.get('is_re_all'))
print('[*] analyzing...\n')
result_gen = pool.result_yield()
if cfg.get('is_silent'):
result_gen = tqdm.tqdm(
pool.result_yield(),
total=len(filelist),
mininterval=1,
ncols=80,
bar_format='{n_fmt}/{total_fmt} [{bar}] {elapsed}<{remaining},{rate_fmt}{postfix}',
)
for results in result_gen:
if not results:
continue
for result in results:
union_data = [result['file'], result['match']]
# 相同文件,相同匹配字符串去重
if union_data in result_filter_list:
continue
result_filter_list.append([result['file'], result['match']])
ret.append(result)
if not cfg.get('is_silent'):
print('[+] group: {}, match: {}, file: {}'.format(result['group'], result['match'], result['file']))
output_format = cfg.get('output_format')
filename = 'results_{}.csv'.format(time.strftime("%H%M%S", time.localtime()))
if output_format == 'json':
filename = 'results.json'
with open(filename, 'w', encoding='utf-8') as _f:
_f.write(json.dumps(ret))
else:
to_csv(ret, filename)
print('[*] total file number:', len(filelist))
print('[+] output to:', pathlib.Path(filename).absolute())
return ret
def to_csv(data: Union[Dict[str, Any], List[Dict[str, Any]]], filename: str = 'output.csv'):
"""
输入数据应为:cache = {'a': [1, 0, 9], 'b': [3, 7, 6]}
"""
dataframe = pandas.DataFrame(data)
dataframe.to_csv(filename, quoting=csv.QUOTE_MINIMAL)
# 考虑字典数据、列表数据、函数数据
FUZZY_UNIVERSAL_STRING = r'["\'`]?\s*[=:(\{\[]\s*["\'`][\x20-\x7F]{,128}?[\'"`]'
#
PATH_COMMON_STRING = r'users?|windows?|program files(\(x\d{2,3}\))?|s?bin|etc|usr|boot|dev|home|proc|opt|sys|srv|var'
__DEFAULT_CONFIG = {
'target_path': '',
'config_path': 'config.yaml',
'output_format': 'csv',
'process_number': 5,
'exclude_files': [r'\.DS_Store'],
'row_split': '[\x00-\x1F\x7F]+',
'rules': {
'AKSK': [r'LTAI\w+'],
'JSON WEB TOKEN(JWT)': [r'ey[0-9a-zA-Z/+]{4,}={,2}\.[0-9a-zA-Z/+]{6,}={,2}\.[A-Za-z0-9-_]+'],
'FUZZY MATCH': {
'flags': 'I',
'regexp': [
r'(APP|ACCESS|USER|PASS|OSS|ECS|CVM|AWS)[\w]{,8}(NAME|ID|KEY|NUM|ENC|CODE|SEC|WORD)[\w]{,16}%s'
% FUZZY_UNIVERSAL_STRING,
# 考虑驼峰写法,下划线写法,MAP键值下面单词后必须接大写字母、下划线、中划线,否侧可能出现如:
r'(USR|PWD|COOKIE)[_\-A-Z][\w]{,16}%s' % FUZZY_UNIVERSAL_STRING,
r'(SECRET|SIGN|TOKEN)[\w]{,16}%s' % FUZZY_UNIVERSAL_STRING,
],
},
'BASE64': [r'[0-9a-zA-Z/+]{8,}={,2}'],
'URL': {
'regexp': [r'(ftp|https?):\/\/[%.\w\-]+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?'],
're_filters': [
r'(adobe|amap|android|apache|bing|digicert|eclipse|freecodecamp|github|githubusercontent|gnu|godaddy|google|googlesource|youtube|youtu|jd'
r'|npmjs|microsoft|openxmlformats|outlook|mozilla|openssl|oracle|qq|spring|sun|umang|w3|wikipedia|xml)\.('
r'org|com|cn|net|edu|io|be)',
r'(ali|baidu|cdn|example|ssh|ssl)[\w-]*\.(org|com|cn|net|edu|io)',
],
},
'EMAIL': [r'[a-zA-Z0-9][-+.\w]{1,127}@([a-zA-Z0-9][-a-zA-Z0-9]{0,63}.){,3}(org|com|cn|net|edu|mail)'],
'PHONE': [r'(13[0-9]|14[5-9]|15[0-3,5-9]|16[6]|17[0-8]|18[0-9]|19[8,9])\d{8}'],
'FILE PATH': {
'flags': 'I|X',
'regexp': [
r'([a-z]:\\)?([\\/])(users?|windows?|program files(\(x\d{2,3}\))?|s?bin|etc|usr|boot|dev|home|proc|opt'
r'|sys|srv|var)(\2[.\w!#\(~\[\{][.\w!#&\(\)+=~\[\]\{\}\s]{2,63}){1,16}'
],
're_filters': [
# r'[\\/].*sdk.*',
# r'[\\/](alibaba|aliyun|annotation|apache|chromium|collections|eclipse|facebook|functions|github|google'
# r'|internal|jetbrains|oppo|reactnative|reflect|sdklib|sequences|taobao|tencent|unionpay|view|vivo'
# r'|webkit|xiaomi)',
],
},
},
'is_re_all': False,
'is_silent': False,
}
cfg = {}
if __name__ == '__main__':
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='''
███████╗███████╗███╗ ██╗███████╗██╗████████╗██╗██╗ ██╗███████╗
██╔════╝██╔════╝████╗ ██║██╔════╝██║╚══██╔══╝██║██║ ██║██╔════╝
███████╗█████╗ ██╔██╗ ██║███████╗██║ ██║ ██║██║ ██║█████╗
╚════██║██╔══╝ ██║╚██╗██║╚════██║██║ ██║ ██║╚██╗ ██╔╝██╔══╝
███████║███████╗██║ ╚████║███████║██║ ██║ ██║ ╚████╔╝ ███████╗
╚══════╝╚══════╝╚═╝ ╚═══╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═══╝ ╚══════╝
v0.1.4
by 0xn0ne, https://github.com/0xn0ne/sensitive-helper
''',
)
parser.add_argument(
'-t',
'--target-path',
required=True,
help='search for file paths or folder paths for sensitive cache (eg. ~/download/folder).',
)
parser.add_argument('-p', '--process-number', default=5, type=int, help='number of program processes (default: 5).')
parser.add_argument(
'-c',
'--config-path',
default='configs.yaml',
help='path to the yaml configuration file (default: configs.yaml).',
)
parser.add_argument('-o', '--output-format', help='output file format, available formats json, csv (default: csv).')
parser.add_argument(
'-e', '--exclude-files', nargs='+', help='excluded files, using regular matching (eg. \\.DS_Store .*bin .*doc).'
)
parser.add_argument(
'-a',
'--is-re-all',
action='store_true',
help='hit a single regular expression per file or match all regular expressions to exit the match loop.',
)
parser.add_argument(
'-s',
'--is-silent',
action='store_true',
help='silent mode: when turned on, no hit data will be output on the console. use a progress bar instead.',
)
args = parser.parse_args()
print(parser.description)
nargs = dict(args.__dict__)
for key in args.__dict__:
if nargs[key] is None:
del nargs[key]
| cfg = configurator.new(filepath=args.config_path, template=__DEFAULT_CONFIG) | 1 | 2023-12-26 03:30:39+00:00 | 8k |
lvyufeng/uie_mindspore | uie_predictor.py | [
{
"identifier": "ErnieMTokenizerFast",
"path": "tokenizer.py",
"snippet": "class ErnieMTokenizerFast(PreTrainedTokenizerFast):\n r\"\"\"\n Construct a \"fast\" ERNIE-M tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.\n This tokenizer inherits from [`PreTrainedTokeni... | import re
import numpy as np
import math
import argparse
import mindspore
from mindnlp.transformers import UIE, UIEM
from tokenizer import ErnieMTokenizerFast
from utils import logger, get_bool_ids_greater_than, get_span, get_id_and_prob, cut_chinese_sent, dbc2sbc
from mindnlp.transformers import BertTokenizerFast | 5,206 | if cnt_org not in input_mapping.keys():
input_mapping[cnt_org] = [cnt_short]
else:
input_mapping[cnt_org].append(cnt_short)
cnt_short += 1
else:
temp_text_list = [
sen[i:i + max_text_len]
for i in range(0, lens, max_text_len)
]
short_input_texts.extend(temp_text_list)
short_idx = cnt_short
cnt_short += math.ceil(lens / max_text_len)
temp_text_id = [
short_idx + i for i in range(cnt_short - short_idx)
]
if cnt_org not in input_mapping.keys():
input_mapping[cnt_org] = temp_text_id
else:
input_mapping[cnt_org].extend(temp_text_id)
cnt_org += 1
return short_input_texts, input_mapping
def _single_stage_predict(self, inputs):
input_texts = []
prompts = []
for i in range(len(inputs)):
input_texts.append(inputs[i]["text"])
prompts.append(inputs[i]["prompt"])
# max predict length should exclude the length of prompt and summary tokens
max_predict_len = self._max_seq_len - len(max(prompts)) - 3
short_input_texts, self.input_mapping = self._auto_splitter(
input_texts, max_predict_len, split_sentence=self._split_sentence)
short_texts_prompts = []
for k, v in self.input_mapping.items():
short_texts_prompts.extend([prompts[k] for i in range(len(v))])
short_inputs = [{
"text": short_input_texts[i],
"prompt": short_texts_prompts[i]
} for i in range(len(short_input_texts))]
sentence_ids = []
probs = []
input_ids = []
token_type_ids = []
attention_mask = []
offset_maps = []
if self._multilingual:
padding_type = "max_length"
else:
padding_type = "longest"
encoded_inputs = self._tokenizer(
text=short_texts_prompts,
text_pair=short_input_texts,
stride=2,
truncation=True,
max_length=self._max_seq_len,
padding=padding_type,
add_special_tokens=True,
return_token_type_ids=True,
return_attention_mask=True,
return_offsets_mapping=True,
return_tensors="np")
start_prob_concat, end_prob_concat = [], []
for batch_start in range(0, len(short_input_texts), self._batch_size):
input_ids = encoded_inputs["input_ids"][batch_start:batch_start+self._batch_size]
token_type_ids = encoded_inputs["token_type_ids"][batch_start:batch_start+self._batch_size]
attention_mask = encoded_inputs["attention_mask"][batch_start:batch_start+self._batch_size]
offset_maps = encoded_inputs["offset_mapping"][batch_start:batch_start+self._batch_size]
if self._multilingual:
input_ids = np.array(
input_ids, dtype="int64")
attention_mask = np.array(
attention_mask, dtype="int64")
position_ids = (np.cumsum(np.ones_like(input_ids), axis=1)
- np.ones_like(input_ids))*attention_mask
input_dict = {
"input_ids": input_ids,
"attention_mask": attention_mask,
"position_ids": position_ids
}
else:
input_dict = {
"input_ids": np.array(
input_ids, dtype="int64"),
"token_type_ids": np.array(
token_type_ids, dtype="int64"),
"attention_mask": np.array(
attention_mask, dtype="int64")
}
outputs = self.inference_backend.infer(input_dict)
start_prob, end_prob = outputs[0], outputs[1]
start_prob_concat.append(start_prob)
end_prob_concat.append(end_prob)
start_prob_concat = np.concatenate(start_prob_concat)
end_prob_concat = np.concatenate(end_prob_concat)
start_ids_list = get_bool_ids_greater_than(
start_prob_concat, limit=self._position_prob, return_prob=True)
end_ids_list = get_bool_ids_greater_than(
end_prob_concat, limit=self._position_prob, return_prob=True)
input_ids = input_dict['input_ids']
sentence_ids = []
probs = []
for start_ids, end_ids, ids, offset_map in zip(start_ids_list,
end_ids_list,
input_ids.tolist(),
offset_maps):
for i in reversed(range(len(ids))):
if ids[i] != 0:
ids = ids[:i]
break
span_list = get_span(start_ids, end_ids, with_prob=True)
|
class MindSporeInferBackend:
def __init__(self,
model_path_prefix,
multilingual=False,
use_fp16=False):
logger.info(">>> [MindSporeInferBackend] Creating Engine ...")
if multilingual:
self.model = UIEM.from_pretrained(model_path_prefix)
else:
self.model = UIE.from_pretrained(model_path_prefix)
self.model.set_train(False)
if use_fp16:
logger.info(
">>> [MindSporeInferBackend] Use FP16 to inference ...")
self.model = self.model.half()
logger.info(">>> [MindSporeInferBackend] Engine Created ...")
def infer(self, input_dict):
for input_name, input_value in input_dict.items():
input_value = mindspore.Tensor(input_value)
input_dict[input_name] = input_value
outputs = self.model(**input_dict)
start_prob, end_prob = outputs[0], outputs[1]
start_prob = start_prob.asnumpy()
end_prob = end_prob.asnumpy()
return start_prob, end_prob
class UIEPredictor(object):
def __init__(self, model, schema, task_path=None, schema_lang="zh", engine='mindspore', position_prob=0.5, max_seq_len=512, batch_size=64, split_sentence=False, use_fp16=False):
if model in ['uie-m-base', 'uie-m-large']:
self._multilingual = True
else:
self._multilingual = False
self._model = model
self._engine = engine
self._task_path = task_path
self._position_prob = position_prob
self._max_seq_len = max_seq_len
self._batch_size = batch_size
self._split_sentence = split_sentence
self._use_fp16 = use_fp16
self._schema_tree = None
self._is_en = True if model in ['uie-base-en'
] or schema_lang == 'en' else False
self.set_schema(schema)
self._prepare_predictor()
def _prepare_predictor(self):
assert self._engine in ['mindspore'], "engine must be mindspore!"
if self._task_path is None:
self._task_path = self._model
if self._multilingual:
self._tokenizer = ErnieMTokenizerFast.from_pretrained(
self._task_path)
else:
self._tokenizer = BertTokenizerFast.from_pretrained(
self._task_path)
if self._engine == 'mindspore':
self.inference_backend = MindSporeInferBackend(
self._task_path, multilingual=self._multilingual, use_fp16=self._use_fp16)
def set_schema(self, schema):
if isinstance(schema, dict) or isinstance(schema, str):
schema = [schema]
self._schema_tree = self._build_tree(schema)
def __call__(self, inputs):
texts = inputs
if isinstance(texts, str):
texts = [texts]
results = self._multi_stage_predict(texts)
return results
def _multi_stage_predict(self, datas):
"""
Traversal the schema tree and do multi-stage prediction.
Args:
datas (list): a list of strings
Returns:
list: a list of predictions, where the list's length
equals to the length of `datas`
"""
results = [{} for _ in range(len(datas))]
# input check to early return
if len(datas) < 1 or self._schema_tree is None:
return results
# copy to stay `self._schema_tree` unchanged
schema_list = self._schema_tree.children[:]
while len(schema_list) > 0:
node = schema_list.pop(0)
examples = []
input_map = {}
cnt = 0
idx = 0
if not node.prefix:
for data in datas:
examples.append({
"text": data,
"prompt": dbc2sbc(node.name)
})
input_map[cnt] = [idx]
idx += 1
cnt += 1
else:
for pre, data in zip(node.prefix, datas):
if len(pre) == 0:
input_map[cnt] = []
else:
for p in pre:
if self._is_en:
if re.search(r'\[.*?\]$', node.name):
prompt_prefix = node.name[:node.name.find(
"[", 1)].strip()
cls_options = re.search(
r'\[.*?\]$', node.name).group()
# Sentiment classification of xxx [positive, negative]
prompt = prompt_prefix + p + " " + cls_options
else:
prompt = node.name + p
else:
prompt = p + node.name
examples.append({
"text": data,
"prompt": dbc2sbc(prompt)
})
input_map[cnt] = [i + idx for i in range(len(pre))]
idx += len(pre)
cnt += 1
if len(examples) == 0:
result_list = []
else:
result_list = self._single_stage_predict(examples)
if not node.parent_relations:
relations = [[] for i in range(len(datas))]
for k, v in input_map.items():
for idx in v:
if len(result_list[idx]) == 0:
continue
if node.name not in results[k].keys():
results[k][node.name] = result_list[idx]
else:
results[k][node.name].extend(result_list[idx])
if node.name in results[k].keys():
relations[k].extend(results[k][node.name])
else:
relations = node.parent_relations
for k, v in input_map.items():
for i in range(len(v)):
if len(result_list[v[i]]) == 0:
continue
if "relations" not in relations[k][i].keys():
relations[k][i]["relations"] = {
node.name: result_list[v[i]]
}
elif node.name not in relations[k][i]["relations"].keys(
):
relations[k][i]["relations"][
node.name] = result_list[v[i]]
else:
relations[k][i]["relations"][node.name].extend(
result_list[v[i]])
new_relations = [[] for i in range(len(datas))]
for i in range(len(relations)):
for j in range(len(relations[i])):
if "relations" in relations[i][j].keys(
) and node.name in relations[i][j]["relations"].keys():
for k in range(
len(relations[i][j]["relations"][
node.name])):
new_relations[i].append(relations[i][j][
"relations"][node.name][k])
relations = new_relations
prefix = [[] for _ in range(len(datas))]
for k, v in input_map.items():
for idx in v:
for i in range(len(result_list[idx])):
if self._is_en:
prefix[k].append(" of " +
result_list[idx][i]["text"])
else:
prefix[k].append(result_list[idx][i]["text"] + "的")
for child in node.children:
child.prefix = prefix
child.parent_relations = relations
schema_list.append(child)
return results
def _convert_ids_to_results(self, examples, sentence_ids, probs):
"""
Convert ids to raw text in a single stage.
"""
results = []
for example, sentence_id, prob in zip(examples, sentence_ids, probs):
if len(sentence_id) == 0:
results.append([])
continue
result_list = []
text = example["text"]
prompt = example["prompt"]
for i in range(len(sentence_id)):
start, end = sentence_id[i]
if start < 0 and end >= 0:
continue
if end < 0:
start += (len(prompt) + 1)
end += (len(prompt) + 1)
result = {"text": prompt[start:end],
"probability": prob[i]}
result_list.append(result)
else:
result = {
"text": text[start:end],
"start": start,
"end": end,
"probability": prob[i]
}
result_list.append(result)
results.append(result_list)
return results
def _auto_splitter(self, input_texts, max_text_len, split_sentence=False):
'''
Split the raw texts automatically for model inference.
Args:
input_texts (List[str]): input raw texts.
max_text_len (int): cutting length.
split_sentence (bool): If True, sentence-level split will be performed.
return:
short_input_texts (List[str]): the short input texts for model inference.
input_mapping (dict): mapping between raw text and short input texts.
'''
input_mapping = {}
short_input_texts = []
cnt_org = 0
cnt_short = 0
for text in input_texts:
if not split_sentence:
sens = [text]
else:
sens = cut_chinese_sent(text)
for sen in sens:
lens = len(sen)
if lens <= max_text_len:
short_input_texts.append(sen)
if cnt_org not in input_mapping.keys():
input_mapping[cnt_org] = [cnt_short]
else:
input_mapping[cnt_org].append(cnt_short)
cnt_short += 1
else:
temp_text_list = [
sen[i:i + max_text_len]
for i in range(0, lens, max_text_len)
]
short_input_texts.extend(temp_text_list)
short_idx = cnt_short
cnt_short += math.ceil(lens / max_text_len)
temp_text_id = [
short_idx + i for i in range(cnt_short - short_idx)
]
if cnt_org not in input_mapping.keys():
input_mapping[cnt_org] = temp_text_id
else:
input_mapping[cnt_org].extend(temp_text_id)
cnt_org += 1
return short_input_texts, input_mapping
def _single_stage_predict(self, inputs):
input_texts = []
prompts = []
for i in range(len(inputs)):
input_texts.append(inputs[i]["text"])
prompts.append(inputs[i]["prompt"])
# max predict length should exclude the length of prompt and summary tokens
max_predict_len = self._max_seq_len - len(max(prompts)) - 3
short_input_texts, self.input_mapping = self._auto_splitter(
input_texts, max_predict_len, split_sentence=self._split_sentence)
short_texts_prompts = []
for k, v in self.input_mapping.items():
short_texts_prompts.extend([prompts[k] for i in range(len(v))])
short_inputs = [{
"text": short_input_texts[i],
"prompt": short_texts_prompts[i]
} for i in range(len(short_input_texts))]
sentence_ids = []
probs = []
input_ids = []
token_type_ids = []
attention_mask = []
offset_maps = []
if self._multilingual:
padding_type = "max_length"
else:
padding_type = "longest"
encoded_inputs = self._tokenizer(
text=short_texts_prompts,
text_pair=short_input_texts,
stride=2,
truncation=True,
max_length=self._max_seq_len,
padding=padding_type,
add_special_tokens=True,
return_token_type_ids=True,
return_attention_mask=True,
return_offsets_mapping=True,
return_tensors="np")
start_prob_concat, end_prob_concat = [], []
for batch_start in range(0, len(short_input_texts), self._batch_size):
input_ids = encoded_inputs["input_ids"][batch_start:batch_start+self._batch_size]
token_type_ids = encoded_inputs["token_type_ids"][batch_start:batch_start+self._batch_size]
attention_mask = encoded_inputs["attention_mask"][batch_start:batch_start+self._batch_size]
offset_maps = encoded_inputs["offset_mapping"][batch_start:batch_start+self._batch_size]
if self._multilingual:
input_ids = np.array(
input_ids, dtype="int64")
attention_mask = np.array(
attention_mask, dtype="int64")
position_ids = (np.cumsum(np.ones_like(input_ids), axis=1)
- np.ones_like(input_ids))*attention_mask
input_dict = {
"input_ids": input_ids,
"attention_mask": attention_mask,
"position_ids": position_ids
}
else:
input_dict = {
"input_ids": np.array(
input_ids, dtype="int64"),
"token_type_ids": np.array(
token_type_ids, dtype="int64"),
"attention_mask": np.array(
attention_mask, dtype="int64")
}
outputs = self.inference_backend.infer(input_dict)
start_prob, end_prob = outputs[0], outputs[1]
start_prob_concat.append(start_prob)
end_prob_concat.append(end_prob)
start_prob_concat = np.concatenate(start_prob_concat)
end_prob_concat = np.concatenate(end_prob_concat)
start_ids_list = get_bool_ids_greater_than(
start_prob_concat, limit=self._position_prob, return_prob=True)
end_ids_list = get_bool_ids_greater_than(
end_prob_concat, limit=self._position_prob, return_prob=True)
input_ids = input_dict['input_ids']
sentence_ids = []
probs = []
for start_ids, end_ids, ids, offset_map in zip(start_ids_list,
end_ids_list,
input_ids.tolist(),
offset_maps):
for i in reversed(range(len(ids))):
if ids[i] != 0:
ids = ids[:i]
break
span_list = get_span(start_ids, end_ids, with_prob=True) | sentence_id, prob = get_id_and_prob(span_list, offset_map.tolist()) | 1 | 2023-12-25 11:02:24+00:00 | 8k |
SAITPublic/BiRF | test.py | [
{
"identifier": "NGPradianceField",
"path": "lib/models/ngp.py",
"snippet": "class NGPradianceField(torch.nn.Module):\n def __init__(\n self,\n aabb: Union[torch.Tensor, List[float]],\n num_dim: int = 3,\n use_viewdirs: bool = True,\n density_activation: Callable = ... | import argparse
import math
import os
import time
import json
import gin
import imageio
import numpy as np
import torch
import torch.nn.functional as F
import tqdm
from typing import *
from datetime import datetime
from torchmetrics import StructuralSimilarityIndexMeasure
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
from lib.models.ngp import NGPradianceField
from lib.utils import render_image, set_random_seed, load_dataset, load_occgrid, load_model
from nerfacc import ContractionType, OccupancyGrid | 4,832 | if os.path.exists(os.path.join(f"{data_root_fp}", str(scene), "bbox.txt")):
aabb = list(np.loadtxt(os.path.join(f"{data_root_fp}", str(scene), "bbox.txt"))[:6])
contraction_type = ContractionType.AABB
scene_aabb = torch.tensor(aabb, dtype=torch.float32, device=device)
near_plane = None
far_plane = None
render_step_size = (
(scene_aabb[3:] - scene_aabb[:3]).max()
* math.sqrt(3)
/ render_n_samples
).item()
alpha_thre = 0
# setup the radiance field we want to train.
grad_scaler = torch.cuda.amp.GradScaler(2**10)
radiance_field = NGPradianceField(
aabb=aabb,
n_features_per_level=n_features,
).to(device)
radiance_field = load_model(radiance_field, save_path, device=device)
occupancy_grid = OccupancyGrid(
roi_aabb=aabb,
resolution=grid_resolution,
contraction_type=contraction_type,
).to(device)
occupancy_grid = load_occgrid(occupancy_grid, save_path, device=device, res=grid_resolution)
# metrics
SSIM = StructuralSimilarityIndexMeasure(data_range=1.0).to(device)
LPIPS = LearnedPerceptualImagePatchSimilarity(net_type='vgg').to(device)
radiance_field = radiance_field.half()
if render_per_frame > 0:
os.makedirs(f"{save_path}/imgs", exist_ok=True)
# evaluation
init = time.time()
radiance_field.eval()
psnr_list, ssim_list, lpips_list = [], [], []
with torch.no_grad():
for j in tqdm.tqdm(range(len(test_dataset))):
data = test_dataset[j]
render_bkgd = data["color_bkgd"]
rays = data["rays"]
pixels = data["pixels"]
# rendering
rgb, acc, depth, _ = render_image(
radiance_field,
occupancy_grid,
rays,
scene_aabb,
# rendering options
near_plane=near_plane,
far_plane=far_plane,
render_step_size=render_step_size,
render_bkgd=render_bkgd,
cone_angle=cone_angle,
alpha_thre=alpha_thre,
# test options
test_chunk_size=test_chunk_size,
)
if render_per_frame > 0 and j % render_per_frame == 0:
imageio.imwrite(
f"{save_path}/imgs/{j:03d}.png",
(rgb.cpu().numpy() * 255).astype(np.uint8),
)
mse = F.mse_loss(rgb, pixels)
psnr = -10.0 * torch.log(mse) / np.log(10.0)
rgb = rgb.permute(-1, 0, 1)[None, ...]
pixels = pixels.permute(-1, 0, 1)[None, ...]
ssim = SSIM(rgb, pixels)
lpips = LPIPS(rgb, pixels)
psnr_list.append(psnr.item())
ssim_list.append(ssim.item())
lpips_list.append(lpips.item())
psnr_avg = sum(psnr_list) / len(psnr_list)
ssim_avg = sum(ssim_list) / len(ssim_list)
lpips_avg = sum(lpips_list) / len(lpips_list)
print(f"Evaluation PSNR: {round(psnr_avg, 2):.2f}")
print(f"Evaluation SSIM: {round(ssim_avg, 3):.3f}")
print(f"Evaluation LPIPS: {round(lpips_avg, 3):.3f}")
test_time = time.time() - init
render_speed = len(test_dataset) / test_time
encoding_size = os.path.getsize(f"{save_path}/encoding.npz")
network_size = os.path.getsize(f"{save_path}/network.ckpt")
occgrid_size = os.path.getsize(f"{save_path}/occgrid.npz")
total_size = encoding_size + network_size + occgrid_size
print(f"Evaluation encoding size: {round((encoding_size / 2 ** 20), 2):.2f} MB")
print(f"Evaluation network size: {round((network_size / 2 ** 20), 2):.2f} MB")
print(f"Evaluation occgrid size: {round((occgrid_size / 2 ** 20), 2):.2f} MB")
print(f"Evaluation total size: {round((total_size / 2 ** 20), 2):.2f} MB")
results["psnr"] = round(psnr_avg, 2)
results["ssim"] = round(ssim_avg, 3)
results["lpips"] = round(lpips_avg, 3)
results["test_time"] = round(test_time, 2)
results["render_speed"] = round(render_speed, 2)
results['size'] = round(total_size / 2 ** 20, 2)
with open(f"{save_path}/results.json", 'w') as f:
json.dump(results, f)
with open(os.path.join(save_path, "config.gin"), "w") as f:
f.write(gin.operative_config_str())
print("Evaluation done")
return
if __name__ == "__main__":
device = "cuda:0"
args = parse_args()
| """
"Copyright (C) 2021 Samsung Electronics Co. LTD
This software is a property of Samsung Electronics.
No part of this software, either material or conceptual may be copied or distributed, transmitted,
transcribed, stored in a retrieval system, or translated into any human or computer language in any form by any means,
electronic, mechanical, manual or otherwise, or disclosed
to third parties without the express written permission of Samsung Electronics.
(Use of the Software is restricted to non-commercial, personal or academic, research purpose only)"
"""
"""
Modified from NerfAcc (https://github.com/KAIR-BAIR/nerfacc)
Copyright (c) 2022 Ruilong Li, UC Berkeley.
"""
class ExtendAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
items = getattr(namespace, self.dest) or []
items.extend(values)
setattr(namespace, self.dest, items)
def parse_args():
parser = argparse.ArgumentParser()
parser.register('action', 'extend', ExtendAction)
parser.add_argument(
"configs",
action="append",
help="path to config files",
)
parser.add_argument(
"--bind",
nargs='+',
action="extend",
help="param to bind",
)
parser.add_argument(
"--scene",
type=str,
required=True,
choices=[
# nerf synthetic
"chair",
"drums",
"ficus",
"hotdog",
"lego",
"materials",
"mic",
"ship",
# nsvf synthetic
"Bike",
"Lifestyle",
"Palace",
"Robot",
"Spaceship",
"Steamtrain",
"Toad",
"Wineholder",
# nsvf TankAndTemple
"Barn",
"Caterpillar",
"Family",
"Ignatius",
"Truck",
],
help="which scene to use",
)
parser.add_argument(
"--n_features",
type=int,
default=2,
help="number of features"
)
parser.add_argument(
"--seed",
type=int,
default=0,
help="random seed number"
)
parser.add_argument(
"--ckpt_dir",
type=str,
default=None,
help="path for checkpoint directory"
)
return parser.parse_args()
@gin.configurable
def main(
scene: str,
ckpt_dir: str,
n_features: int=2,
seed: int = 2023,
log_dir: str = "./logs",
prefix: Optional[str] = None,
postfix: Optional[str] = None,
max_steps: int = 20000,
render_n_samples: int = 1024,
test_chunk_size: int = 16384,
aabb: List[float] = [-1.5, -1.5, -1.5, 1.5, 1.5, 1.5],
data_root_fp: str = "data/nerf_synthetic/",
train_split: str = "train",
cone_angle: float = 0.0,
sparsity_weight: float = 2e-5,
render_per_frame: int = -1,
):
# log
save_path = f"{log_dir}/{scene}" if ckpt_dir == None else ckpt_dir
if prefix is not None:
save_path = f"{prefix}_{save_path}"
if postfix is not None:
save_path = f"{save_path}_{postfix}"
save_path = f"{save_path}_{n_features}"
print(f'Evaluation for pretrained model in "{save_path}"')
results = {}
# setup the dataset
test_dataset_kwargs = {}
target_sample_batch_size = 1 << 18
grid_resolution = 128
test_dataset, data_root_fp = load_dataset(
scene=scene,
data_root_fp=data_root_fp,
split="test",
num_rays=None,
dataset_kwargs=test_dataset_kwargs,
device=device,
)
if os.path.exists(os.path.join(f"{data_root_fp}", str(scene), "bbox.txt")):
aabb = list(np.loadtxt(os.path.join(f"{data_root_fp}", str(scene), "bbox.txt"))[:6])
contraction_type = ContractionType.AABB
scene_aabb = torch.tensor(aabb, dtype=torch.float32, device=device)
near_plane = None
far_plane = None
render_step_size = (
(scene_aabb[3:] - scene_aabb[:3]).max()
* math.sqrt(3)
/ render_n_samples
).item()
alpha_thre = 0
# setup the radiance field we want to train.
grad_scaler = torch.cuda.amp.GradScaler(2**10)
radiance_field = NGPradianceField(
aabb=aabb,
n_features_per_level=n_features,
).to(device)
radiance_field = load_model(radiance_field, save_path, device=device)
occupancy_grid = OccupancyGrid(
roi_aabb=aabb,
resolution=grid_resolution,
contraction_type=contraction_type,
).to(device)
occupancy_grid = load_occgrid(occupancy_grid, save_path, device=device, res=grid_resolution)
# metrics
SSIM = StructuralSimilarityIndexMeasure(data_range=1.0).to(device)
LPIPS = LearnedPerceptualImagePatchSimilarity(net_type='vgg').to(device)
radiance_field = radiance_field.half()
if render_per_frame > 0:
os.makedirs(f"{save_path}/imgs", exist_ok=True)
# evaluation
init = time.time()
radiance_field.eval()
psnr_list, ssim_list, lpips_list = [], [], []
with torch.no_grad():
for j in tqdm.tqdm(range(len(test_dataset))):
data = test_dataset[j]
render_bkgd = data["color_bkgd"]
rays = data["rays"]
pixels = data["pixels"]
# rendering
rgb, acc, depth, _ = render_image(
radiance_field,
occupancy_grid,
rays,
scene_aabb,
# rendering options
near_plane=near_plane,
far_plane=far_plane,
render_step_size=render_step_size,
render_bkgd=render_bkgd,
cone_angle=cone_angle,
alpha_thre=alpha_thre,
# test options
test_chunk_size=test_chunk_size,
)
if render_per_frame > 0 and j % render_per_frame == 0:
imageio.imwrite(
f"{save_path}/imgs/{j:03d}.png",
(rgb.cpu().numpy() * 255).astype(np.uint8),
)
mse = F.mse_loss(rgb, pixels)
psnr = -10.0 * torch.log(mse) / np.log(10.0)
rgb = rgb.permute(-1, 0, 1)[None, ...]
pixels = pixels.permute(-1, 0, 1)[None, ...]
ssim = SSIM(rgb, pixels)
lpips = LPIPS(rgb, pixels)
psnr_list.append(psnr.item())
ssim_list.append(ssim.item())
lpips_list.append(lpips.item())
psnr_avg = sum(psnr_list) / len(psnr_list)
ssim_avg = sum(ssim_list) / len(ssim_list)
lpips_avg = sum(lpips_list) / len(lpips_list)
print(f"Evaluation PSNR: {round(psnr_avg, 2):.2f}")
print(f"Evaluation SSIM: {round(ssim_avg, 3):.3f}")
print(f"Evaluation LPIPS: {round(lpips_avg, 3):.3f}")
test_time = time.time() - init
render_speed = len(test_dataset) / test_time
encoding_size = os.path.getsize(f"{save_path}/encoding.npz")
network_size = os.path.getsize(f"{save_path}/network.ckpt")
occgrid_size = os.path.getsize(f"{save_path}/occgrid.npz")
total_size = encoding_size + network_size + occgrid_size
print(f"Evaluation encoding size: {round((encoding_size / 2 ** 20), 2):.2f} MB")
print(f"Evaluation network size: {round((network_size / 2 ** 20), 2):.2f} MB")
print(f"Evaluation occgrid size: {round((occgrid_size / 2 ** 20), 2):.2f} MB")
print(f"Evaluation total size: {round((total_size / 2 ** 20), 2):.2f} MB")
results["psnr"] = round(psnr_avg, 2)
results["ssim"] = round(ssim_avg, 3)
results["lpips"] = round(lpips_avg, 3)
results["test_time"] = round(test_time, 2)
results["render_speed"] = round(render_speed, 2)
results['size'] = round(total_size / 2 ** 20, 2)
with open(f"{save_path}/results.json", 'w') as f:
json.dump(results, f)
with open(os.path.join(save_path, "config.gin"), "w") as f:
f.write(gin.operative_config_str())
print("Evaluation done")
return
if __name__ == "__main__":
device = "cuda:0"
args = parse_args() | set_random_seed(args.seed) | 2 | 2023-12-28 02:08:29+00:00 | 8k |
pkariz/grin-explorer | backend/api/bootstrap.py | [
{
"identifier": "check_for_reorg",
"path": "backend/api/helpers.py",
"snippet": "def check_for_reorg(new_block, update_progress_fn, missing_heights, start_height):\n \"\"\"\n Checks if new_block is part of a reorg. Return tuple (reorg, set<heights>)\n where reorg is Reorg instance or None, set<... | from django.db import transaction
from django.db.utils import IntegrityError
from django.utils.dateparse import parse_datetime
from .helpers import check_for_reorg, get_missing_heights_repr, get_prefetched_header_and_block_data
from .models import Block, BlockHeader, Output, Kernel, Input
from .node import NodeV2API, NodeBlockNotFoundException
from .exceptions import UpdateBlockchainProgressError
import decimal
import math
import logging | 4,987 |
logger = logging.getLogger(__name__)
def _get_percent_loaded(nr_missing_blocks, nr_all_blocks, decimal_places):
missing_percent = Decimal('0')
if nr_all_blocks:
# we can calculate, otherwise we would get division by zero
missing_percent = Decimal(str(nr_missing_blocks)) / Decimal(str(nr_all_blocks)) * Decimal('100')
return (Decimal('100') - missing_percent).quantize(
Decimal('1') / Decimal('10')**decimal_places,
rounding=decimal.ROUND_DOWN
)
def update_load_progress(
blockchain, missing, total, step, modulo, decimal_places, verbose=False, source='default',
):
if step % modulo == 0:
logger.info('bc: {}, missing: {}, total: {}, step: {}, modulo: {}, decimal_places: {}, source: {}'.format(
blockchain.slug, missing, total, step, modulo, decimal_places, source))
# update Blockchain's load_progress
blockchain.load_progress = _get_percent_loaded(
missing,
total,
decimal_places
)
blockchain.save()
if verbose:
# option to get output in the shell if you bootstrap from there
print('Blockchain: {} - load_progress: {}%'.format(
blockchain.slug, blockchain.load_progress)
)
def fetch_and_store_block(blockchain, block_height, prefetch=True):
# initialize node api
node_api = NodeV2API(blockchain.node)
if block_height < 0:
# no such block height
raise NodeBlockNotFoundException()
if prefetch:
block_data = get_prefetched_header_and_block_data(blockchain.node, block_height)
else:
block_data = node_api.get_block(height=block_height)
header_data = block_data['header']
timestamp = parse_datetime(header_data['timestamp'])
hash = header_data['hash']
# create header instance
cuckoo_solution = ','.join(map(str, header_data['cuckoo_solution']))
with transaction.atomic():
header, header_created = BlockHeader.objects.get_or_create(
blockchain=blockchain,
cuckoo_solution=cuckoo_solution,
kernel_root=header_data['kernel_root'],
defaults={
'version': header_data['version'],
'output_root': header_data['output_root'],
'range_proof_root': header_data['range_proof_root'],
'kernel_mmr_size': header_data['kernel_mmr_size'],
'output_mmr_size': header_data['output_mmr_size'],
'nonce': str(header_data['nonce']),
'edge_bits': header_data['edge_bits'],
'secondary_scaling': header_data['secondary_scaling'],
'total_difficulty': header_data['total_difficulty'],
'total_kernel_offset': header_data['total_kernel_offset'],
}
)
# create block instance
try:
block, block_created = Block.objects.get_or_create(
blockchain=blockchain,
hash=hash,
height=block_height,
timestamp=timestamp,
header=header,
prev_hash=block_data['header']['previous'],
reorg=None,
nr_inputs=len(block_data['inputs']),
nr_outputs=len(block_data['outputs']),
nr_kernels=len(block_data['kernels']),
)
except IntegrityError as e:
# race condition so it's a duplicate. We can skip creation process
# and just return the block that we already have
return Block.objects.get(blockchain=blockchain, hash=hash)
if not block_created:
# we have already fetched all the data since it's done in an atomic
# transaction, so skip unnecessary work
return block
# bulk create kernels
kernels = []
for kernel_data in block_data['kernels']:
kernels.append(
Kernel(
block=block,
features=kernel_data['features'],
fee=kernel_data['fee'],
fee_shift=kernel_data['fee_shift'],
lock_height=kernel_data['lock_height'],
excess=kernel_data['excess'],
excess_sig=kernel_data['excess_sig'],
)
)
Kernel.objects.bulk_create(kernels)
inputs = []
# create input instances
outputs_data = Output.objects\
.filter(
commitment__in=block_data['inputs'],
block__reorg__isnull=True,
block__blockchain=block.blockchain,
)\
.values('id', 'commitment')
outputs_mapper = { output_data['commitment'] : output_data['id'] for output_data in outputs_data }
for input_data in block_data['inputs']:
inputs.append(
|
Decimal = decimal.Decimal
logger = logging.getLogger(__name__)
def _get_percent_loaded(nr_missing_blocks, nr_all_blocks, decimal_places):
missing_percent = Decimal('0')
if nr_all_blocks:
# we can calculate, otherwise we would get division by zero
missing_percent = Decimal(str(nr_missing_blocks)) / Decimal(str(nr_all_blocks)) * Decimal('100')
return (Decimal('100') - missing_percent).quantize(
Decimal('1') / Decimal('10')**decimal_places,
rounding=decimal.ROUND_DOWN
)
def update_load_progress(
blockchain, missing, total, step, modulo, decimal_places, verbose=False, source='default',
):
if step % modulo == 0:
logger.info('bc: {}, missing: {}, total: {}, step: {}, modulo: {}, decimal_places: {}, source: {}'.format(
blockchain.slug, missing, total, step, modulo, decimal_places, source))
# update Blockchain's load_progress
blockchain.load_progress = _get_percent_loaded(
missing,
total,
decimal_places
)
blockchain.save()
if verbose:
# option to get output in the shell if you bootstrap from there
print('Blockchain: {} - load_progress: {}%'.format(
blockchain.slug, blockchain.load_progress)
)
def fetch_and_store_block(blockchain, block_height, prefetch=True):
# initialize node api
node_api = NodeV2API(blockchain.node)
if block_height < 0:
# no such block height
raise NodeBlockNotFoundException()
if prefetch:
block_data = get_prefetched_header_and_block_data(blockchain.node, block_height)
else:
block_data = node_api.get_block(height=block_height)
header_data = block_data['header']
timestamp = parse_datetime(header_data['timestamp'])
hash = header_data['hash']
# create header instance
cuckoo_solution = ','.join(map(str, header_data['cuckoo_solution']))
with transaction.atomic():
header, header_created = BlockHeader.objects.get_or_create(
blockchain=blockchain,
cuckoo_solution=cuckoo_solution,
kernel_root=header_data['kernel_root'],
defaults={
'version': header_data['version'],
'output_root': header_data['output_root'],
'range_proof_root': header_data['range_proof_root'],
'kernel_mmr_size': header_data['kernel_mmr_size'],
'output_mmr_size': header_data['output_mmr_size'],
'nonce': str(header_data['nonce']),
'edge_bits': header_data['edge_bits'],
'secondary_scaling': header_data['secondary_scaling'],
'total_difficulty': header_data['total_difficulty'],
'total_kernel_offset': header_data['total_kernel_offset'],
}
)
# create block instance
try:
block, block_created = Block.objects.get_or_create(
blockchain=blockchain,
hash=hash,
height=block_height,
timestamp=timestamp,
header=header,
prev_hash=block_data['header']['previous'],
reorg=None,
nr_inputs=len(block_data['inputs']),
nr_outputs=len(block_data['outputs']),
nr_kernels=len(block_data['kernels']),
)
except IntegrityError as e:
# race condition so it's a duplicate. We can skip creation process
# and just return the block that we already have
return Block.objects.get(blockchain=blockchain, hash=hash)
if not block_created:
# we have already fetched all the data since it's done in an atomic
# transaction, so skip unnecessary work
return block
# bulk create kernels
kernels = []
for kernel_data in block_data['kernels']:
kernels.append(
Kernel(
block=block,
features=kernel_data['features'],
fee=kernel_data['fee'],
fee_shift=kernel_data['fee_shift'],
lock_height=kernel_data['lock_height'],
excess=kernel_data['excess'],
excess_sig=kernel_data['excess_sig'],
)
)
Kernel.objects.bulk_create(kernels)
inputs = []
# create input instances
outputs_data = Output.objects\
.filter(
commitment__in=block_data['inputs'],
block__reorg__isnull=True,
block__blockchain=block.blockchain,
)\
.values('id', 'commitment')
outputs_mapper = { output_data['commitment'] : output_data['id'] for output_data in outputs_data }
for input_data in block_data['inputs']:
inputs.append( | Input( | 7 | 2023-12-24 22:15:11+00:00 | 8k |
Rubics-Xuan/Med-DANet | train.py | [
{
"identifier": "UNet_crop",
"path": "models/backup_models/UNet/Med_DANet_V2.py",
"snippet": "class UNet_crop(nn.Module):\n def __init__(self, input_channels, num_classes, mode_train=True, decision_net_predict=False, **kwargs):\n super().__init__()\n\n self.mode_train = mode_train\n ... | import argparse
import os
import random
import logging
import numpy as np
import time
import math
import setproctitle
import torch
import torch.backends.cudnn as cudnn
import torch.optim
import torch.distributed as dist
import warnings
from pickle import FALSE
from sre_parse import FLAGS
from models.backup_models.UNet.Med_DANet_V2 import UNet_crop
from models import criterions
from data.BraTS import BraTS
from torch.utils.data import DataLoader
from utils.tools import all_reduce_tensor
from tensorboardX import SummaryWriter
from torch import nn | 5,555 |
torch.distributed.init_process_group('nccl') # 初始化GPU通信方式NCCL, PyTorch实现分布式运算是通过NCCL进行显卡通信�?
torch.cuda.set_device(args.local_rank) # 为这个进程指定GPU
model = UNet_crop(input_channels=4, num_classes=4, mode_train=True)
model.cuda(args.local_rank)
model = nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank,
find_unused_parameters=True)
if args.start_epoch > 0:
load_file = args.load_file
if os.path.exists(load_file):
checkpoint = torch.load(load_file, map_location=lambda storage, loc: storage)
model.load_state_dict(checkpoint['state_dict'])
print('Successfully loading checkpoint of epoch: {} and training from epoch: {}'
.format(checkpoint['epoch'], args.start_epoch))
else:
print('There is no checkpoint file to load!')
model.train()
param_dicts = [
{
"params":
[p for n, p in model.named_parameters() if "decision_network" not in n and p.requires_grad],
"lr": args.lr,
},
{
"params": [p for n, p in model.named_parameters() if "decision_network" in n and p.requires_grad],
"lr": args.lr * 10,
}
]
optimizer = torch.optim.Adam(param_dicts, lr=args.lr, weight_decay=args.weight_decay, amsgrad=args.amsgrad)
criterion = getattr(criterions, args.criterion)
if args.local_rank == 0:
checkpoint_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'checkpoint',
args.experiment + args.date)
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
train_label_for_DN = f"./traininglabels_DN/{args.experiment + args.date}"
train_label_for_DN_HGG = f"{train_label_for_DN}/HGG"
train_label_for_DN_LGG = f"{train_label_for_DN}/LGG"
if not os.path.exists(train_label_for_DN):
os.makedirs(train_label_for_DN)
if not os.path.exists(train_label_for_DN_HGG):
os.makedirs(train_label_for_DN_HGG)
if not os.path.exists(train_label_for_DN_LGG):
os.makedirs(train_label_for_DN_LGG)
if args.local_rank == 0:
writer = SummaryWriter()
train_list = os.path.join(args.root, args.train_dir, args.train_file)
train_root = os.path.join(args.root, args.train_dir)
train_set = BraTS(train_list, train_root, args.mode)
train_sampler = torch.utils.data.distributed.DistributedSampler(train_set)
logging.info('Samples for train = {}'.format(len(train_set)))
num_gpu = (len(args.gpu) + 1) // 2
num_iter_perepoch = len(train_set) // args.batch_size
num_iter_perepoch = num_iter_perepoch * int(128)
train_loader = DataLoader(dataset=train_set, sampler=train_sampler, batch_size=args.batch_size // num_gpu,
drop_last=True, num_workers=args.num_workers, pin_memory=True)
start_time_training = time.time()
torch.set_grad_enabled(True)
fix = 0
train_epoch = [150, 300]
scale_lr = 10
for epoch in range(args.start_epoch, args.end_epoch):
train_sampler.set_epoch(epoch) # shuffle
setproctitle.setproctitle('{}: {}/{}'.format(args.user, epoch + 1, args.end_epoch))
start_epoch = time.time()
for i, data in enumerate(train_loader):
x, target = data
x = x.cuda(args.local_rank, non_blocking=True)
target = target.cuda(args.local_rank, non_blocking=True)
# shuffle batchsize & slice dimension
max_number = (args.batch_size // num_gpu) * 128
index = torch.randperm(max_number)
B, D = x.size(0), x.size(-1)
x = x.permute(0, 4, 1, 2, 3).contiguous().view(B * D, 4, 128, 128)
target = target.permute(0, 3, 1, 2).contiguous().view(B * D, 128, 128)
x = x[index]
target = target[index]
if epoch < train_epoch[0]:
for s in range(128):
current_iter = epoch * num_iter_perepoch + i * int(128) + (s + 1)
warm_up_learning_rate_adjust_iter(args.lr, current_iter, num_iter_perepoch,
args.end_epoch * num_iter_perepoch, optimizer, power=0.9)
x_s = x[s * (args.batch_size // num_gpu):(s + 1) * (args.batch_size // num_gpu) - 1, ...]
crop1_output, whole_output = model(x_s, crop=True, decide=False, quantify_loss = False,epoch= epoch)
loss_crop1, loss1_crop1, loss2_crop1, loss3_crop1 = criterion(crop1_output, target[s * (
args.batch_size // num_gpu):(s + 1) * (args.batch_size // num_gpu) - 1, ...])
loss_whole, loss1_whole, loss2_whole, loss3_whole = criterion(whole_output, target[
s * (args.batch_size // num_gpu):(s + 1) * (args.batch_size // num_gpu) - 1,...])
loss = (loss_crop1 + loss_whole)/2
loss1 = (loss1_crop1 + loss1_whole)/2
loss2 = (loss2_crop1 + loss2_whole)/2
loss3 = (loss3_crop1 + loss3_whole)/2
|
# from data.BraTS_2020 import BraTS
warnings.filterwarnings('ignore')
local_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
parser = argparse.ArgumentParser()
# Basic Information
parser.add_argument('--user', default='shr', type=str)
parser.add_argument('--experiment',
default='cnn300_50crop',
type=str)
parser.add_argument('--date', default=local_time.split(' ')[0], type=str)
parser.add_argument('--description',
default='cnn300_50crop'
'training on train_0.txt!',
type=str)
# DataSet Information
parser.add_argument('--root', default='./dataset/BraTS2019/', type=str)
# parser.add_argument('--root', default='./dataset/BraTS2020/', type=str)
parser.add_argument('--train_dir', default='Train', type=str)
parser.add_argument('--valid_dir', default='Train', type=str)
parser.add_argument('--output_dir', default='output', type=str)
parser.add_argument('--submission', default='submission', type=str)
parser.add_argument('--visual', default='visualization', type=str)
parser.add_argument('--heatmap_dir', default='heatmap', type=str)
parser.add_argument('--test_date', default=local_time.split(' ')[0], type=str)
parser.add_argument('--mode', default='train', type=str)
parser.add_argument('--train_file', default='train.txt', type=str)
parser.add_argument('--valid_file', default='valid.txt', type=str)
parser.add_argument('--dataset', default='brats', type=str)
parser.add_argument('--model_name',
default='cnn300_50crop',
type=str)
parser.add_argument('--input_C', default=4, type=int)
parser.add_argument('--input_H', default=240, type=int)
parser.add_argument('--input_W', default=240, type=int)
parser.add_argument('--input_D', default=160, type=int)
parser.add_argument('--crop_H', default=128, type=int)
parser.add_argument('--crop_W', default=128, type=int)
parser.add_argument('--crop_D', default=128, type=int)
parser.add_argument('--output_D', default=155, type=int)
# Training Information
parser.add_argument('--lr', default=0.0001, type=float)
parser.add_argument('--weight_decay', default=1e-5, type=float)
parser.add_argument('--amsgrad', default=True, type=bool)
parser.add_argument('--criterion', default='softmax_dice', type=str)
parser.add_argument('--num_class', default=4, type=int)
parser.add_argument('--seed', default=1085, type=int)
parser.add_argument('--no_cuda', default=False, type=bool)
parser.add_argument('--gpu', default='4,5,6,7', type=str)
parser.add_argument('--num_workers', default=8, type=int)
parser.add_argument('--batch_size', default=64, type=int)
parser.add_argument('--start_epoch', default=0, type=int)
parser.add_argument('--end_epoch', default=350, type=int)
parser.add_argument('--save_freq', default=50, type=int)
parser.add_argument('--load_file', default='', type=str)
parser.add_argument('--local_rank', default=0, type=int, help='node rank for distributed training')
args = parser.parse_args()
def dice_score(o, t, eps=1e-8):
num = 2 * (o * t).sum() + eps
den = o.sum() + t.sum() + eps
return num / den
def softmax_output_dice(output, target):
ret = []
# WT
o = output > 0
t = target > 0 # ce
ret += dice_score(o, t),
# TC
o = (output == 1) | (output == 3)
t = (target == 1) | (target == 4)
ret += dice_score(o, t),
# ET
o = (output == 3)
t = (target == 4)
ret += dice_score(o, t),
return ret
def main_worker():
if args.local_rank == 0:
log_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'log', args.experiment + args.date)
log_file = log_dir + '.txt'
log_args(log_file)
logging.info('--------------------------------------This is all argsurations----------------------------------')
for arg in vars(args):
logging.info('{}={}'.format(arg, getattr(args, arg)))
logging.info('----------------------------------------This is a halving line----------------------------------')
logging.info('{}'.format(args.description))
torch.manual_seed(args.seed)
torch.cuda.manual_seed(args.seed)
random.seed(args.seed)
np.random.seed(args.seed)
torch.distributed.init_process_group('nccl') # 初始化GPU通信方式NCCL, PyTorch实现分布式运算是通过NCCL进行显卡通信�?
torch.cuda.set_device(args.local_rank) # 为这个进程指定GPU
model = UNet_crop(input_channels=4, num_classes=4, mode_train=True)
model.cuda(args.local_rank)
model = nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank], output_device=args.local_rank,
find_unused_parameters=True)
if args.start_epoch > 0:
load_file = args.load_file
if os.path.exists(load_file):
checkpoint = torch.load(load_file, map_location=lambda storage, loc: storage)
model.load_state_dict(checkpoint['state_dict'])
print('Successfully loading checkpoint of epoch: {} and training from epoch: {}'
.format(checkpoint['epoch'], args.start_epoch))
else:
print('There is no checkpoint file to load!')
model.train()
param_dicts = [
{
"params":
[p for n, p in model.named_parameters() if "decision_network" not in n and p.requires_grad],
"lr": args.lr,
},
{
"params": [p for n, p in model.named_parameters() if "decision_network" in n and p.requires_grad],
"lr": args.lr * 10,
}
]
optimizer = torch.optim.Adam(param_dicts, lr=args.lr, weight_decay=args.weight_decay, amsgrad=args.amsgrad)
criterion = getattr(criterions, args.criterion)
if args.local_rank == 0:
checkpoint_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'checkpoint',
args.experiment + args.date)
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
train_label_for_DN = f"./traininglabels_DN/{args.experiment + args.date}"
train_label_for_DN_HGG = f"{train_label_for_DN}/HGG"
train_label_for_DN_LGG = f"{train_label_for_DN}/LGG"
if not os.path.exists(train_label_for_DN):
os.makedirs(train_label_for_DN)
if not os.path.exists(train_label_for_DN_HGG):
os.makedirs(train_label_for_DN_HGG)
if not os.path.exists(train_label_for_DN_LGG):
os.makedirs(train_label_for_DN_LGG)
if args.local_rank == 0:
writer = SummaryWriter()
train_list = os.path.join(args.root, args.train_dir, args.train_file)
train_root = os.path.join(args.root, args.train_dir)
train_set = BraTS(train_list, train_root, args.mode)
train_sampler = torch.utils.data.distributed.DistributedSampler(train_set)
logging.info('Samples for train = {}'.format(len(train_set)))
num_gpu = (len(args.gpu) + 1) // 2
num_iter_perepoch = len(train_set) // args.batch_size
num_iter_perepoch = num_iter_perepoch * int(128)
train_loader = DataLoader(dataset=train_set, sampler=train_sampler, batch_size=args.batch_size // num_gpu,
drop_last=True, num_workers=args.num_workers, pin_memory=True)
start_time_training = time.time()
torch.set_grad_enabled(True)
fix = 0
train_epoch = [150, 300]
scale_lr = 10
for epoch in range(args.start_epoch, args.end_epoch):
train_sampler.set_epoch(epoch) # shuffle
setproctitle.setproctitle('{}: {}/{}'.format(args.user, epoch + 1, args.end_epoch))
start_epoch = time.time()
for i, data in enumerate(train_loader):
x, target = data
x = x.cuda(args.local_rank, non_blocking=True)
target = target.cuda(args.local_rank, non_blocking=True)
# shuffle batchsize & slice dimension
max_number = (args.batch_size // num_gpu) * 128
index = torch.randperm(max_number)
B, D = x.size(0), x.size(-1)
x = x.permute(0, 4, 1, 2, 3).contiguous().view(B * D, 4, 128, 128)
target = target.permute(0, 3, 1, 2).contiguous().view(B * D, 128, 128)
x = x[index]
target = target[index]
if epoch < train_epoch[0]:
for s in range(128):
current_iter = epoch * num_iter_perepoch + i * int(128) + (s + 1)
warm_up_learning_rate_adjust_iter(args.lr, current_iter, num_iter_perepoch,
args.end_epoch * num_iter_perepoch, optimizer, power=0.9)
x_s = x[s * (args.batch_size // num_gpu):(s + 1) * (args.batch_size // num_gpu) - 1, ...]
crop1_output, whole_output = model(x_s, crop=True, decide=False, quantify_loss = False,epoch= epoch)
loss_crop1, loss1_crop1, loss2_crop1, loss3_crop1 = criterion(crop1_output, target[s * (
args.batch_size // num_gpu):(s + 1) * (args.batch_size // num_gpu) - 1, ...])
loss_whole, loss1_whole, loss2_whole, loss3_whole = criterion(whole_output, target[
s * (args.batch_size // num_gpu):(s + 1) * (args.batch_size // num_gpu) - 1,...])
loss = (loss_crop1 + loss_whole)/2
loss1 = (loss1_crop1 + loss1_whole)/2
loss2 = (loss2_crop1 + loss2_whole)/2
loss3 = (loss3_crop1 + loss3_whole)/2
| reduce_loss = all_reduce_tensor(loss, world_size=num_gpu).data.cpu().numpy() | 3 | 2023-12-28 07:26:55+00:00 | 8k |
datrocity/pond | pond/versioned_artifact.py | [
{
"identifier": "Artifact",
"path": "pond/artifact/artifact.py",
"snippet": "class Artifact(ABC):\n \"\"\" Knows how to read and write one type of artifact.\n\n Concrete Artifact implementation should save the metadata with the data if possible,\n so that the artifact is self-contained even if,... | import json
import logging
import time
from typing import List, Type, Optional, Union
from pond.artifact import Artifact
from pond.conventions import (
DataType,
WriteMode,
version_manifest_location,
version_location,
versions_lock_file_location,
versioned_artifact_location,
)
from pond.exceptions import (
IncompatibleVersionName, VersionAlreadyExists,
)
from pond.metadata.manifest import Manifest
from pond.storage.datastore import Datastore
from pond.version import Version
from pond.version_name import VersionName | 6,552 |
self.versions_manifest = {
'artifact_class': artifact_class.class_id(),
'version_name_class': version_name_class.class_id(),
}
self.versions_location = versioned_artifact_location(location, artifact_name)
# todo this goes to conventions.py
self.versions_list_location = f'{self.versions_location}/versions.json'
self.versions_manifest_location = f'{self.versions_location}/manifest.yml'
if not self.datastore.exists(self.versions_location):
# Create the versioned artifact folder organization if it does not exist
self.datastore.makedirs(self.versions_location)
self._write_version_names([])
self.versions_manifest['artifact_class'] = artifact_class.class_id()
self.versions_manifest['version_name_class'] = version_name_class.class_id()
self._write_manifest()
# --- VersionedArtifact class interface
@classmethod
def from_datastore(cls, artifact_name: str, location: str, datastore: Datastore):
versions_location = versioned_artifact_location(location, artifact_name)
versions_manifest_location = f'{versions_location}/manifest.yml'
versions_manifest = datastore.read_yaml(versions_manifest_location)
artifact_class_id = versions_manifest['artifact_class']
artifact_class = Artifact.subclass_from_id(artifact_class_id)
version_name_class_id = versions_manifest['version_name_class']
version_name_class = VersionName.subclass_from_id(version_name_class_id)
versioned_artifact = cls(
artifact_name=artifact_name,
location=location,
datastore=datastore,
artifact_class=artifact_class,
version_name_class=version_name_class,
)
return versioned_artifact
# --- VersionedArtifact public interface
def read(self, version_name: Optional[Union[str, VersionName]] = None) -> Version:
""" Read a version of the artifact.
Parameters
----------
version_name: Union[str, VersionName], optional
Version name, given as a string (more common) or as VersionName instance. If None,
the latest version name for the given artifact is used.
Raises
------
VersionDoesNotExist
If the requested version does not exist.
Returns
-------
Version
The version object read from storage.
"""
if version_name is not None:
if isinstance(version_name, str):
version_name = self.version_name_class.from_string(version_name)
else:
version_name = self.latest_version_name()
version = Version.read(
version_name=version_name,
artifact_class=self.artifact_class,
datastore=self.datastore,
location=self.versions_location,
)
return version
def write(self,
data: DataType,
manifest: Manifest,
version_name: Optional[Union[str, VersionName]] = None,
write_mode: WriteMode = WriteMode.ERROR_IF_EXISTS):
""" Write some data to storage.
Parameters
----------
data: DataType
The artifact data to write.
manifest: Manifest
Metadata to store with the data.
version_name: Union[str, VersionName], optional
Version name, given as a string (more common) or as VersionName instance. If None,
the latest version name for the given artifact is used.
write_mode: WriteMode
Write mode, either WriteMode.ERROR_IF_EXISTS or WriteMode.OVERWRITE.
Raises
------
IncompatibleVersionName
If the provided version name does not correspond to the version name class used in
this versioned artifact.
VersionAlreadyExists
If the provided version name exists, and the write mode is "ERROR_IF_EXISTS".
Returns
-------
Version
The version object read from storage.
"""
# todo lock
if version_name is None:
prev_version_name = self.latest_version_name(raise_if_none=False)
version_name = self.version_name_class.next(prev_version_name)
if isinstance(version_name, str):
version_name = VersionName.from_string(version_name)
if not isinstance(version_name, self.version_name_class):
|
logger = logging.getLogger(__name__)
# Time to wait before retrying when creating a new version fails
NEW_VERSION_WAIT_MS = 1000
class VersionedArtifact:
def __init__(self,
artifact_name: str,
location: str,
datastore: Datastore,
artifact_class: Type[Artifact],
version_name_class: Type[VersionName]):
""" An artifact versioned and stored on disk.
`VersionedArtifact` manages the versioning, data, and metadata, of an artifact.
Parameters
----------
artifact_name: str
Name of the artifact.
location: str
Root location in the data store where artifacts are read/written. This is used to
create folder-like groups inside a datastore. This can be, for instance, the name of
a project or experiment.
datastore: Datastore
Data store object, representing the storage where the artifacts are read/written.
artifact_class: Type[Artifact]
version_name_class: Type[VersionName]
Class used to create increasing version names. The default value,
`SimpleVersionName` creates version names as `v1`, `v2`, etc.
"""
self.artifact_name = artifact_name
self.location = location
self.datastore = datastore
self.artifact_class = artifact_class
self.version_name_class = version_name_class
self.versions_manifest = {
'artifact_class': artifact_class.class_id(),
'version_name_class': version_name_class.class_id(),
}
self.versions_location = versioned_artifact_location(location, artifact_name)
# todo this goes to conventions.py
self.versions_list_location = f'{self.versions_location}/versions.json'
self.versions_manifest_location = f'{self.versions_location}/manifest.yml'
if not self.datastore.exists(self.versions_location):
# Create the versioned artifact folder organization if it does not exist
self.datastore.makedirs(self.versions_location)
self._write_version_names([])
self.versions_manifest['artifact_class'] = artifact_class.class_id()
self.versions_manifest['version_name_class'] = version_name_class.class_id()
self._write_manifest()
# --- VersionedArtifact class interface
@classmethod
def from_datastore(cls, artifact_name: str, location: str, datastore: Datastore):
versions_location = versioned_artifact_location(location, artifact_name)
versions_manifest_location = f'{versions_location}/manifest.yml'
versions_manifest = datastore.read_yaml(versions_manifest_location)
artifact_class_id = versions_manifest['artifact_class']
artifact_class = Artifact.subclass_from_id(artifact_class_id)
version_name_class_id = versions_manifest['version_name_class']
version_name_class = VersionName.subclass_from_id(version_name_class_id)
versioned_artifact = cls(
artifact_name=artifact_name,
location=location,
datastore=datastore,
artifact_class=artifact_class,
version_name_class=version_name_class,
)
return versioned_artifact
# --- VersionedArtifact public interface
def read(self, version_name: Optional[Union[str, VersionName]] = None) -> Version:
""" Read a version of the artifact.
Parameters
----------
version_name: Union[str, VersionName], optional
Version name, given as a string (more common) or as VersionName instance. If None,
the latest version name for the given artifact is used.
Raises
------
VersionDoesNotExist
If the requested version does not exist.
Returns
-------
Version
The version object read from storage.
"""
if version_name is not None:
if isinstance(version_name, str):
version_name = self.version_name_class.from_string(version_name)
else:
version_name = self.latest_version_name()
version = Version.read(
version_name=version_name,
artifact_class=self.artifact_class,
datastore=self.datastore,
location=self.versions_location,
)
return version
def write(self,
data: DataType,
manifest: Manifest,
version_name: Optional[Union[str, VersionName]] = None,
write_mode: WriteMode = WriteMode.ERROR_IF_EXISTS):
""" Write some data to storage.
Parameters
----------
data: DataType
The artifact data to write.
manifest: Manifest
Metadata to store with the data.
version_name: Union[str, VersionName], optional
Version name, given as a string (more common) or as VersionName instance. If None,
the latest version name for the given artifact is used.
write_mode: WriteMode
Write mode, either WriteMode.ERROR_IF_EXISTS or WriteMode.OVERWRITE.
Raises
------
IncompatibleVersionName
If the provided version name does not correspond to the version name class used in
this versioned artifact.
VersionAlreadyExists
If the provided version name exists, and the write mode is "ERROR_IF_EXISTS".
Returns
-------
Version
The version object read from storage.
"""
# todo lock
if version_name is None:
prev_version_name = self.latest_version_name(raise_if_none=False)
version_name = self.version_name_class.next(prev_version_name)
if isinstance(version_name, str):
version_name = VersionName.from_string(version_name)
if not isinstance(version_name, self.version_name_class): | raise IncompatibleVersionName( | 2 | 2023-12-24 13:05:58+00:00 | 8k |
demirogun/pyethnobiology | pyethnobiology/indices.py | [
{
"identifier": "RadialPlot",
"path": "pyethnobiology/visualization.py",
"snippet": "class RadialPlot:\n \"\"\"\n Creates a radial bar plot to visualize data in a circular layout.\n \"\"\"\n\n def __init__(self,\n data: pd.DataFrame,\n colorbar_title: str,\n ... | import pandas as pd
from pyethnobiology.visualization import RadialPlot
from pyethnobiology.visualization import HeatmapPlot | 5,094 | self.title = "Informant Consensus Factor (FIC)"
def calculate(self):
"""
Calculates the FIC for each ailment category.
Returns:
pd.DataFrame: DataFrame containing ailment category and FIC columns.
"""
unique_ailment_categories = self.data[self.use_column].unique()
fic_values = []
for ailment_category in unique_ailment_categories:
specific_data = self.data[self.data[self.use_column] == ailment_category]
# Calculate Nur (number of use reports)
nur = specific_data.shape[0]
# Calculate Nt (number of taxa used)
nt = specific_data[self.taxon_column].nunique()
# Calculate FIC value
if nur > nt:
fic = (nur - nt) / (nur - 1)
else:
fic = 0 # Set FIC to 0 if Nur <= Nt
fic_values.append({self.use_column: ailment_category, "FIC": fic})
fic_df = pd.DataFrame(fic_values)
fic_df = fic_df.sort_values(by="FIC", ascending=False).reset_index(drop=True)
return fic_df
def save_data(self):
FIC_df = self.calculate()
FIC_df.to_csv("informant_consensus_factor_FIC.csv", index=False)
print("Saved to informant_consensus_factor_FIC.csv")
def plot_radial(self, filename="FIC.png", dpi=300, num_row=10, ytick_position="onbar", colors=None, show_colorbar=True):
# Plot radial bar chart
radial_plot = RadialPlot(self.calculate(), self.title, "FIC", num_row, ytick_position, colors, show_colorbar, self.informant_column, self.taxon_column, self.use_column)
radial_plot.save_plot(filename, dpi=dpi)
radial_plot.plot()
class FL:
def __init__(self, data, informant_column="informant", taxon_column="taxon", use_column="ailments_treated"):
"""
Initializes the class with necessary data and column names.
Args:
data (pd.DataFrame): DataFrame containing plant usage information.
informant_column (str, optional): Name of the column containing informant IDs. Defaults to "informant".
taxon_column (str, optional): Name of the column containing species names. Defaults to "taxon".
use_column (str, optional): Name of the column containing plant uses. Defaults to "ailments_treated".
"""
self.data = data
self.informant_column = informant_column
self.taxon_column = taxon_column
self.use_column = use_column
self.title = "Fidelity Level (FL) per Species"
def calculate(self):
"""
Calculates the fidelity level (FL) for each species-use combination.
Returns:
pd.DataFrame: DataFrame containing taxon, use, and FL columns.
"""
# Calculate Frequency of Citation (FC) per species
fc_df = FC(self.data, self.informant_column, self.taxon_column, self.use_column).calculate()
# Count informants for each species-use combination
ns_df = (
self.data.groupby([self.taxon_column, self.use_column])[self.informant_column]
.nunique()
.reset_index(name="Ns")
)
# Merge FC and Ns dataframes
merged_df = pd.merge(ns_df, fc_df, on=self.taxon_column)
# Calculate FL = (Ns * 100) / FC
merged_df["FL"] = (merged_df["Ns"] * 100) / merged_df["FC"]
# Exclude rows with FL of 0
merged_df = merged_df[merged_df["FL"] != 0]
return merged_df[[self.taxon_column, self.use_column, "FL"]]
def save_data(self, filename="fidelity_level_FL.csv"):
"""
Saves the calculated FL data to a CSV file.
Args:
filename (str, optional): Name of the CSV file to save. Defaults to "fidelity_level_FL.csv".
"""
fl_df = self.calculate()
fl_df.to_csv(filename, index=False)
print(f"Saved to {filename}")
def plot_heatmap(self,
filename="FL.png",
cmap="coolwarm",
show_colorbar=True,
colorbar_shrink=0.50,
plot_width=10,
plot_height=8,
dpi=300,
fillna_zero=True):
"""
Creates a heatmap of FL values for each species-use combination,
with customizable features for plot appearance and layout.
"""
data = self.calculate()
|
class FC:
def __init__(self, data, informant_column="informant", taxon_column="taxon", use_column="ailments_treated"):
"""
Initializes the class with necessary data and column names.
Args:
data (pd.DataFrame): DataFrame containing plant usage information.
informant_column (str, optional): Name of the column containing informant IDs. Defaults to "informant".
taxon_column (str, optional): Name of the column containing species names. Defaults to "taxon".
use_column (str, optional): Name of the column containing plant uses. Defaults to "ailments_treated".
"""
self.data = data
self.informant_column = informant_column
self.taxon_column = taxon_column
self.use_column = use_column
def calculate(self):
"""
Calculates the frequency of citation (FC) for each species.
Returns:
pd.DataFrame: DataFrame containing taxon and FC columns.
"""
# Calculate FC per species by counting unique informants for each taxon
fc_df = (
self.data.groupby(self.taxon_column, observed=True)[self.informant_column]
.nunique()
.reset_index(name="FC")
)
# Sort FC values in descending order
fc_df = fc_df.sort_values(by="FC", ascending=False).reset_index(drop=True)
return fc_df
def save_data(self):
FC_df = self.calculate()
FC_df.to_csv("frequency_of_citation_FC.csv", index=False)
print("Saved to frequency_of_citation_FC.csv")
def plot_radial(self, filename="FC.png", dpi=300, num_row=10, ytick_position="onbar", colors=None, show_colorbar=True):
# Plot radial bar chart
radial_plot = RadialPlot(self.calculate(), "Frequency of Citation (FC)", "FC", num_row, ytick_position, colors,
show_colorbar, self.informant_column, self.taxon_column, self.use_column)
radial_plot.save_plot(filename, dpi=dpi)
radial_plot.plot()
class NU:
def __init__(self, data, informant_column="informant", taxon_column="taxon", use_column="ailments_treated"):
"""
Initializes the class with necessary data and column names.
Args:
data (pd.DataFrame): DataFrame containing plant usage information.
informant_column (str, optional): Name of the column containing informant IDs.
taxon_column (str, optional): Name of the column containing species names.
use_column (str, optional): Name of the column containing plant uses.
"""
self.data = data
self.informant_column = informant_column
self.taxon_column = taxon_column
self.use_column = use_column
self.title = "Number of Uses (NU) per Species"
def calculate(self):
"""
Calculates the NU for each species.
Returns:
pd.DataFrame: DataFrame containing taxon and NU columns.
"""
nu_df = (
self.data.groupby(self.taxon_column, observed=True)[self.use_column]
.nunique()
.reset_index(name="NU")
)
nu_df = nu_df.sort_values(by="NU", ascending=False).reset_index(drop=True)
return nu_df
def save_data(self):
NU_df = self.calculate()
NU_df.to_csv("number_of_uses_NU.csv", index=False)
print("Saved to number_of_uses_NU.csv")
def plot_radial(self, filename="NU.png", dpi=300, num_row=10, ytick_position="onbar", colors=None, show_colorbar=True):
# Plot radial bar chart
radial_plot = RadialPlot(self.calculate(), self.title, "NU", num_row, ytick_position, colors, show_colorbar, self.informant_column, self.taxon_column, self.use_column)
radial_plot.save_plot(filename, dpi=dpi)
radial_plot.plot()
class UR:
def __init__(self, data, informant_column="informant", taxon_column="taxon", use_column="ailments_treated"):
"""
Initializes the class with necessary data and column names.
Args:
data (pd.DataFrame): DataFrame containing plant usage information.
informant_column (str, optional): Name of the column containing informant IDs.
taxon_column (str, optional): Name of the column containing species names.
use_column (str, optional): Name of the column containing plant uses.
"""
self.data = data
self.informant_column = informant_column
self.taxon_column = taxon_column
self.use_column = use_column
self.title = "Use Report (UR) per Species"
def calculate(self):
"""
Calculates the UR for each species.
Returns:
pd.DataFrame: DataFrame containing taxon and UR columns.
"""
ur_df = (
self.data.groupby(self.taxon_column, observed=True)
.size()
.reset_index(name="UR")
.sort_values(by="UR", ascending=False)
.reset_index(drop=True)
)
return ur_df
def save_data(self):
UR_df = self.calculate()
UR_df.to_csv("use_report_UR.csv", index=False)
print("Saved to use_report_UR.csv")
def plot_radial(self, filename="UR.png", dpi=300, num_row=10, ytick_position="onbar", colors=None, show_colorbar=True):
# Plot radial bar chart
radial_plot = RadialPlot(self.calculate(), self.title, "UR", num_row, ytick_position, colors, show_colorbar,
self.informant_column, self.taxon_column, self.use_column)
radial_plot.save_plot(filename, dpi=dpi)
radial_plot.plot()
class CI:
def __init__(self, data, informant_column="informant", taxon_column="taxon", use_column="ailments_treated"):
"""
Initializes the class with necessary data and column names.
Args:
data (pd.DataFrame): DataFrame containing plant usage information.
informant_column (str, optional): Name of the column containing informant IDs. Defaults to "informant".
taxon_column (str, optional): Name of the column containing species names. Defaults to "taxon".
use_column (str, optional): Name of the column containing plant uses. Defaults to "ailments_treated".
"""
self.data = data
self.informant_column = informant_column
self.taxon_column = taxon_column
self.use_column = use_column
self.title = "Cultural Importance (CI) Index"
def calculate(self):
"""
Calculates the cultural importance index (CI) for each species.
Returns:
pd.DataFrame: DataFrame containing taxon and CI columns.
"""
# Calculate Use Reports (UR) per species
ur_df = UR(self.data, self.informant_column, self.taxon_column, self.use_column).calculate()
# Count unique informants
informants_count = self.data[self.informant_column].nunique()
# Merge UR and informants count based on 'taxon'
ci_df = pd.merge(
ur_df,
self.data[[self.taxon_column, self.informant_column]]
.drop_duplicates()
.groupby(self.taxon_column, observed=False)
.size()
.reset_index(name=f"{self.informant_column}s_count"),
on=self.taxon_column,
)
# Calculate CI index (UR divided by the number of informants)
ci_df["CI"] = ci_df["UR"] / informants_count
# Keep only relevant columns
ci_df = ci_df[[self.taxon_column, "CI"]]
return ci_df
def save_data(self):
CI_df = self.calculate()
CI_df.to_csv("cultural_importance_CI.csv", index=False)
print("Saved to cultural_importance_CI.csv")
def plot_radial(self, filename="CI.png", dpi=300, num_row=10, ytick_position="onbar", colors=None, show_colorbar=True):
# Plot radial bar chart
radial_plot = RadialPlot(self.calculate(), self.title, "CI", num_row, ytick_position,
colors, show_colorbar, self.informant_column, self.taxon_column, self.use_column)
radial_plot.save_plot(filename, dpi=dpi)
radial_plot.plot()
class CV:
def __init__(self, data, informant_column="informant", taxon_column="taxon", use_column="ailments_treated"):
"""
Initializes the class with necessary data and column names.
Args:
data (pd.DataFrame): DataFrame containing plant usage information.
informant_column (str, optional): Name of the column containing informant IDs. Defaults to "informant".
taxon_column (str, optional): Name of the column containing species names. Defaults to "taxon".
use_column (str, optional): Name of the column containing plant uses. Defaults to "ailments_treated".
"""
self.data = data
self.informant_column = informant_column
self.taxon_column = taxon_column
self.use_column = use_column
self.title = "Cultural Value (CV) for Ethnospecies"
def calculate(self):
"""
Calculates the cultural value (CV) for each ethnospecies.
Returns:
pd.DataFrame: DataFrame containing taxon and CV columns.
"""
# Calculate Use Reports (UR) per species
ur_df = UR(self.data, self.informant_column, self.taxon_column, self.use_column).calculate()
# Calculate Number of Uses (NU) per species
nu_df = NU(self.data, self.informant_column, self.taxon_column, self.use_column).calculate()
# Calculate Frequency of Citation (FC) per species
fc_df = FC(self.data, self.informant_column, self.taxon_column, self.use_column).calculate()
# Calculate Uce (Use Citation for Ethnospecies)
potential_uses = self.data[self.use_column].nunique()
nu_df["Uce"] = nu_df["NU"] / potential_uses
# Calculate Ice (Informant Citation Index)
ice = fc_df["FC"] / self.data[self.informant_column].nunique()
fc_df["Ice"] = ice
# Calculate IUce (Informant Use Index)
iuce = ur_df["UR"] / self.data[self.informant_column].nunique()
ur_df["IUce"] = iuce
# Merge dataframes to calculate CV
merged_df = pd.merge(nu_df[[self.taxon_column, "Uce"]], ur_df[[self.taxon_column, "IUce"]], on=self.taxon_column)
merged_df = pd.merge(merged_df, fc_df[[self.taxon_column, "Ice"]], on=self.taxon_column)
# Calculate CV = Uce * Ice * IUce
merged_df["CV"] = merged_df["Uce"] * merged_df["Ice"] * merged_df["IUce"]
# Sort and round CV values
cv_df = merged_df[[self.taxon_column, "CV"]].sort_values(by="CV", ascending=False)
return cv_df
def save_data(self):
CV_df = self.calculate()
CV_df.to_csv("cultural_value_CV.csv", index=False)
print("Saved to cultural_value_CV.csv")
def plot_radial(self, filename="CV.png", dpi=300, num_row=10, ytick_position="onbar", colors=None, show_colorbar=True):
# Plot radial bar chart
radial_plot = RadialPlot(self.calculate(), self.title, "CV", num_row, ytick_position, colors, show_colorbar, self.informant_column, self.taxon_column, self.use_column)
radial_plot.save_plot(filename, dpi=dpi)
radial_plot.plot()
class FIC:
def __init__(self, data, informant_column="informant", taxon_column="taxon", use_column="ailments_treated"):
"""
Initializes the class with necessary data and column names.
Args:
data (pd.DataFrame): DataFrame containing plant usage information.
informant_column (str, optional): Name of the column containing informant IDs.
taxon_column (str, optional): Name of the column containing species names.
use_column (str, optional): Name of the column containing plant uses.
"""
self.data = data
self.informant_column = informant_column
self.taxon_column = taxon_column
self.use_column = use_column
self.title = "Informant Consensus Factor (FIC)"
def calculate(self):
"""
Calculates the FIC for each ailment category.
Returns:
pd.DataFrame: DataFrame containing ailment category and FIC columns.
"""
unique_ailment_categories = self.data[self.use_column].unique()
fic_values = []
for ailment_category in unique_ailment_categories:
specific_data = self.data[self.data[self.use_column] == ailment_category]
# Calculate Nur (number of use reports)
nur = specific_data.shape[0]
# Calculate Nt (number of taxa used)
nt = specific_data[self.taxon_column].nunique()
# Calculate FIC value
if nur > nt:
fic = (nur - nt) / (nur - 1)
else:
fic = 0 # Set FIC to 0 if Nur <= Nt
fic_values.append({self.use_column: ailment_category, "FIC": fic})
fic_df = pd.DataFrame(fic_values)
fic_df = fic_df.sort_values(by="FIC", ascending=False).reset_index(drop=True)
return fic_df
def save_data(self):
FIC_df = self.calculate()
FIC_df.to_csv("informant_consensus_factor_FIC.csv", index=False)
print("Saved to informant_consensus_factor_FIC.csv")
def plot_radial(self, filename="FIC.png", dpi=300, num_row=10, ytick_position="onbar", colors=None, show_colorbar=True):
# Plot radial bar chart
radial_plot = RadialPlot(self.calculate(), self.title, "FIC", num_row, ytick_position, colors, show_colorbar, self.informant_column, self.taxon_column, self.use_column)
radial_plot.save_plot(filename, dpi=dpi)
radial_plot.plot()
class FL:
def __init__(self, data, informant_column="informant", taxon_column="taxon", use_column="ailments_treated"):
"""
Initializes the class with necessary data and column names.
Args:
data (pd.DataFrame): DataFrame containing plant usage information.
informant_column (str, optional): Name of the column containing informant IDs. Defaults to "informant".
taxon_column (str, optional): Name of the column containing species names. Defaults to "taxon".
use_column (str, optional): Name of the column containing plant uses. Defaults to "ailments_treated".
"""
self.data = data
self.informant_column = informant_column
self.taxon_column = taxon_column
self.use_column = use_column
self.title = "Fidelity Level (FL) per Species"
def calculate(self):
"""
Calculates the fidelity level (FL) for each species-use combination.
Returns:
pd.DataFrame: DataFrame containing taxon, use, and FL columns.
"""
# Calculate Frequency of Citation (FC) per species
fc_df = FC(self.data, self.informant_column, self.taxon_column, self.use_column).calculate()
# Count informants for each species-use combination
ns_df = (
self.data.groupby([self.taxon_column, self.use_column])[self.informant_column]
.nunique()
.reset_index(name="Ns")
)
# Merge FC and Ns dataframes
merged_df = pd.merge(ns_df, fc_df, on=self.taxon_column)
# Calculate FL = (Ns * 100) / FC
merged_df["FL"] = (merged_df["Ns"] * 100) / merged_df["FC"]
# Exclude rows with FL of 0
merged_df = merged_df[merged_df["FL"] != 0]
return merged_df[[self.taxon_column, self.use_column, "FL"]]
def save_data(self, filename="fidelity_level_FL.csv"):
"""
Saves the calculated FL data to a CSV file.
Args:
filename (str, optional): Name of the CSV file to save. Defaults to "fidelity_level_FL.csv".
"""
fl_df = self.calculate()
fl_df.to_csv(filename, index=False)
print(f"Saved to {filename}")
def plot_heatmap(self,
filename="FL.png",
cmap="coolwarm",
show_colorbar=True,
colorbar_shrink=0.50,
plot_width=10,
plot_height=8,
dpi=300,
fillna_zero=True):
"""
Creates a heatmap of FL values for each species-use combination,
with customizable features for plot appearance and layout.
"""
data = self.calculate() | heatmap_plot = HeatmapPlot( | 1 | 2023-12-25 01:06:51+00:00 | 8k |
Zitronenjoghurt/Colonaut | tests/test_ship_system.py | [
{
"identifier": "Event",
"path": "src/events/event.py",
"snippet": "class Event():\n TYPES = EventTypes\n \n def __init__(self, type: str, **kwargs) -> None:\n self.type = type\n self.data = kwargs"
},
{
"identifier": "EventBus",
"path": "src/events/event_bus.py",
... | import os
import pytest
import src.space_ship.ship_systems as ShipSystems
from src.events.event import Event
from src.events.event_bus import EventBus
from src.events.response import Response
from src.space_ship.space_ship import SpaceShip
from src.space_ship.ship_system import ShipSystem
from src.utils.file_operations import file_to_dict | 3,936 |
@pytest.fixture
def setup():
EventBus.reset_instance()
@pytest.fixture
def current_dir():
return os.path.dirname(os.path.abspath(__file__))
@pytest.fixture
def space_ship(setup, current_dir):
ship_file = os.path.join(current_dir, '..', 'src', 'data', 'testing', 'ship.json')
ship_dict = file_to_dict(ship_file)
return SpaceShip.from_dict(data=ship_dict)
|
@pytest.fixture
def setup():
EventBus.reset_instance()
@pytest.fixture
def current_dir():
return os.path.dirname(os.path.abspath(__file__))
@pytest.fixture
def space_ship(setup, current_dir):
ship_file = os.path.join(current_dir, '..', 'src', 'data', 'testing', 'ship.json')
ship_dict = file_to_dict(ship_file)
return SpaceShip.from_dict(data=ship_dict)
| def assert_response_data(response: Response, expected_data, response_type = None): | 2 | 2023-12-22 21:24:33+00:00 | 8k |
YYJeffrey/july_server | app/api/v2/topic.py | [
{
"identifier": "db",
"path": "app/model/base.py",
"snippet": "class BaseModel(db.Model):\n def __getitem__(self, key):\n def init_on_load(self):\n def __set_fields(self):\n def _set_fields(self):\n def keys(self):\n def hide(self, *keys):\n def append(self, *keys):\n def status(... | from flask import current_app, g
from app import db
from app.lib.exception import Success, NotFound, Created, Deleted
from app.lib.red_print import RedPrint
from app.lib.schema import paginator_schema
from app.lib.token import auth
from app.manger.fangtang.server_chan import send_ft_msg
from app.model.comment import Comment
from app.model.label import Label
from app.model.star import Star
from app.model.topic import Topic, TopicLabelRel
from app.service.topic import create_topic_verify, format_report_topic, get_topic_list, get_topic_detail
from app.validator.forms import GetTopicListValidator, CreateTopicValidator | 3,800 | # -*- coding: utf-8 -*-
"""
:copyright: (c) 2023 by Jeffrey.
:license: Apache 2.0, see LICENSE for more details.
"""
api = RedPrint('topic')
@api.route('/<topic_id>', methods=['GET'])
def get_topic(topic_id):
"""
获取话题详情
"""
topic = get_topic_detail(topic_id=topic_id)
if topic is None:
| # -*- coding: utf-8 -*-
"""
:copyright: (c) 2023 by Jeffrey.
:license: Apache 2.0, see LICENSE for more details.
"""
api = RedPrint('topic')
@api.route('/<topic_id>', methods=['GET'])
def get_topic(topic_id):
"""
获取话题详情
"""
topic = get_topic_detail(topic_id=topic_id)
if topic is None: | raise NotFound(msg='话题不存在') | 2 | 2023-12-30 04:08:35+00:00 | 8k |
farhad-dalirani/MultiObjectTracking-YOLO-NAS-DeepSORT | deep_sort_pytorch_master/deep_sort/deep_sort.py | [
{
"identifier": "Extractor",
"path": "deep_sort_pytorch_master/deep_sort/deep/feature_extractor.py",
"snippet": "class Extractor(object):\n def __init__(self, model_path, use_cuda=True):\n self.net = Net(reid=True)\n self.device = \"cuda\" if torch.cuda.is_available() and use_cuda else ... | import numpy as np
import torch
from .deep.feature_extractor import Extractor
from .sort.nn_matching import NearestNeighborDistanceMetric
from .sort.preprocessing import non_max_suppression
from .sort.detection import Detection
from .sort.tracker import Tracker | 3,622 |
###
# Changed from orginal repository
###
# from .deep.feature_extractor import Extractor, FastReIDExtractor
__all__ = ['DeepSort']
class DeepSort(object):
def __init__(self, model_path, model_config=None, max_dist=0.2, min_confidence=0.3, nms_max_overlap=1.0, max_iou_distance=0.7, max_age=70, n_init=3, nn_budget=100, use_cuda=True):
self.min_confidence = min_confidence
self.nms_max_overlap = nms_max_overlap
if model_config is None:
self.extractor = Extractor(model_path, use_cuda=use_cuda)
###
# Changed from orginal repository
###
#else:
# self.extractor = FastReIDExtractor(model_config, model_path, use_cuda=use_cuda)
max_cosine_distance = max_dist
metric = NearestNeighborDistanceMetric("cosine", max_cosine_distance, nn_budget)
|
###
# Changed from orginal repository
###
# from .deep.feature_extractor import Extractor, FastReIDExtractor
__all__ = ['DeepSort']
class DeepSort(object):
def __init__(self, model_path, model_config=None, max_dist=0.2, min_confidence=0.3, nms_max_overlap=1.0, max_iou_distance=0.7, max_age=70, n_init=3, nn_budget=100, use_cuda=True):
self.min_confidence = min_confidence
self.nms_max_overlap = nms_max_overlap
if model_config is None:
self.extractor = Extractor(model_path, use_cuda=use_cuda)
###
# Changed from orginal repository
###
#else:
# self.extractor = FastReIDExtractor(model_config, model_path, use_cuda=use_cuda)
max_cosine_distance = max_dist
metric = NearestNeighborDistanceMetric("cosine", max_cosine_distance, nn_budget) | self.tracker = Tracker(metric, max_iou_distance=max_iou_distance, max_age=max_age, n_init=n_init) | 4 | 2023-12-26 15:22:02+00:00 | 8k |
JiePKU/MoLE | fine_tune.py | [
{
"identifier": "ConfigSanitizer",
"path": "library/config_util.py",
"snippet": "class ConfigSanitizer:\n # @curry\n @staticmethod\n def __validate_and_convert_twodim(klass, value: Sequence) -> Tuple:\n Schema(ExactSequence([klass, klass]))(value)\n return tuple(value)\n\n # @curry\n @staticm... | import argparse
import gc
import math
import os
import toml
import torch
import diffusers
import library.train_util as train_util
import library.config_util as config_util
import library.custom_train_functions as custom_train_functions
from multiprocessing import Value
from tqdm import tqdm
from accelerate.utils import set_seed
from diffusers import DDPMScheduler
from library.config_util import (
ConfigSanitizer,
BlueprintGenerator,
)
from library.custom_train_functions import (
apply_snr_weight,
get_weighted_text_embeddings,
prepare_scheduler_for_custom_training,
pyramid_noise_like,
apply_noise_offset,
scale_v_prediction_loss_like_noise_prediction,
) | 7,125 | with torch.no_grad():
train_dataset_group.cache_latents(vae, args.vae_batch_size, args.cache_latents_to_disk, accelerator.is_main_process)
vae.to("cpu")
if torch.cuda.is_available():
torch.cuda.empty_cache()
gc.collect()
accelerator.wait_for_everyone()
# 学習を準備する:モデルを適切な状態にする
training_models = []
if args.gradient_checkpointing:
unet.enable_gradient_checkpointing()
training_models.append(unet)
if args.train_text_encoder:
print("enable text encoder training")
if args.gradient_checkpointing:
text_encoder.gradient_checkpointing_enable()
training_models.append(text_encoder)
else:
text_encoder.to(accelerator.device, dtype=weight_dtype)
text_encoder.requires_grad_(False) # text encoderは学習しない
if args.gradient_checkpointing:
text_encoder.gradient_checkpointing_enable()
text_encoder.train() # required for gradient_checkpointing
else:
text_encoder.eval()
if not cache_latents:
vae.requires_grad_(False)
vae.eval()
vae.to(accelerator.device, dtype=weight_dtype)
for m in training_models:
m.requires_grad_(True)
params = []
for m in training_models:
params.extend(m.parameters())
params_to_optimize = params
# 学習に必要なクラスを準備する
print("prepare optimizer, data loader etc.")
_, _, optimizer = train_util.get_optimizer(args, trainable_params=params_to_optimize)
# dataloaderを準備する
# DataLoaderのプロセス数:0はメインプロセスになる
n_workers = min(args.max_data_loader_n_workers, os.cpu_count() - 1) # cpu_count-1 ただし最大で指定された数まで
train_dataloader = torch.utils.data.DataLoader(
train_dataset_group,
batch_size=1,
shuffle=True,
collate_fn=collater,
num_workers=n_workers,
persistent_workers=args.persistent_data_loader_workers,
)
# 学習ステップ数を計算する
if args.max_train_epochs is not None:
args.max_train_steps = args.max_train_epochs * math.ceil(
len(train_dataloader) / accelerator.num_processes / args.gradient_accumulation_steps
)
print(f"override steps. steps for {args.max_train_epochs} epochs is / 指定エポックまでのステップ数: {args.max_train_steps}")
# データセット側にも学習ステップを送信
train_dataset_group.set_max_train_steps(args.max_train_steps)
# lr schedulerを用意する
lr_scheduler = train_util.get_scheduler_fix(args, optimizer, accelerator.num_processes)
# 実験的機能:勾配も含めたfp16学習を行う モデル全体をfp16にする
if args.full_fp16:
assert (
args.mixed_precision == "fp16"
), "full_fp16 requires mixed precision='fp16' / full_fp16を使う場合はmixed_precision='fp16'を指定してください。"
print("enable full fp16 training.")
unet.to(weight_dtype)
text_encoder.to(weight_dtype)
# acceleratorがなんかよろしくやってくれるらしい
if args.train_text_encoder:
unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
unet, text_encoder, optimizer, train_dataloader, lr_scheduler
)
else:
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(unet, optimizer, train_dataloader, lr_scheduler)
# transform DDP after prepare
text_encoder, unet = train_util.transform_if_model_is_DDP(text_encoder, unet)
# 実験的機能:勾配も含めたfp16学習を行う PyTorchにパッチを当ててfp16でのgrad scaleを有効にする
if args.full_fp16:
train_util.patch_accelerator_for_fp16_training(accelerator)
# resumeする
train_util.resume_from_local_or_hf_if_specified(accelerator, args)
# epoch数を計算する
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
if (args.save_n_epoch_ratio is not None) and (args.save_n_epoch_ratio > 0):
args.save_every_n_epochs = math.floor(num_train_epochs / args.save_n_epoch_ratio) or 1
# 学習する
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
print("running training / 学習開始")
print(f" num examples / サンプル数: {train_dataset_group.num_train_images}")
print(f" num batches per epoch / 1epochのバッチ数: {len(train_dataloader)}")
print(f" num epochs / epoch数: {num_train_epochs}")
print(f" batch size per device / バッチサイズ: {args.train_batch_size}")
print(f" total train batch size (with parallel & distributed & accumulation) / 総バッチサイズ(並列学習、勾配合計含む): {total_batch_size}")
print(f" gradient accumulation steps / 勾配を合計するステップ数 = {args.gradient_accumulation_steps}")
print(f" total optimization steps / 学習ステップ数: {args.max_train_steps}")
global_step = args.global_step
print(global_step)
progress_bar = tqdm(range(args.max_train_steps), initial=global_step, smoothing=0, disable=not accelerator.is_local_main_process, desc="steps")
noise_scheduler = DDPMScheduler(
beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000, clip_sample=False
)
| # training with captions
# XXX dropped option: hypernetwork training
def train(args):
train_util.verify_training_args(args)
train_util.prepare_dataset_args(args, True)
cache_latents = args.cache_latents
if args.seed is not None:
set_seed(args.seed) # 乱数系列を初期化する
tokenizer = train_util.load_tokenizer(args)
# データセットを準備する
if args.dataset_class is None:
blueprint_generator = BlueprintGenerator(ConfigSanitizer(False, True, True))
if args.dataset_config is not None:
print(f"Load dataset config from {args.dataset_config}")
user_config = config_util.load_user_config(args.dataset_config)
ignored = ["train_data_dir", "in_json"]
if any(getattr(args, attr) is not None for attr in ignored):
print(
"ignore following options because config file is found: {0} / 設定ファイルが利用されるため以下のオプションは無視されます: {0}".format(
", ".join(ignored)
)
)
else:
user_config = {
"datasets": [
{
"subsets": [
{
"image_dir": args.train_data_dir,
"metadata_file": args.in_json,
}
]
}
]
}
print(user_config)
blueprint = blueprint_generator.generate(user_config, args, tokenizer=tokenizer)
train_dataset_group = config_util.generate_dataset_group_by_blueprint(blueprint.dataset_group)
else:
train_dataset_group = train_util.load_arbitrary_dataset(args, tokenizer)
current_epoch = Value("i", 0)
current_step = Value("i", 0)
ds_for_collater = train_dataset_group if args.max_data_loader_n_workers == 0 else None
collater = train_util.collater_class(current_epoch, current_step, ds_for_collater)
if args.debug_dataset:
train_util.debug_dataset(train_dataset_group)
return
if len(train_dataset_group) == 0:
print(
"No data found. Please verify the metadata file and train_data_dir option. / 画像がありません。メタデータおよびtrain_data_dirオプションを確認してください。"
)
return
if cache_latents:
assert (
train_dataset_group.is_latent_cacheable()
), "when caching latents, either color_aug or random_crop cannot be used / latentをキャッシュするときはcolor_augとrandom_cropは使えません"
# acceleratorを準備する
print("prepare accelerator")
accelerator, unwrap_model = train_util.prepare_accelerator(args)
# mixed precisionに対応した型を用意しておき適宜castする
weight_dtype, save_dtype = train_util.prepare_dtype(args)
# モデルを読み込む
text_encoder, vae, unet, load_stable_diffusion_format = train_util.load_target_model(args, weight_dtype, accelerator, False)
# verify load/save model formats
if load_stable_diffusion_format:
src_stable_diffusion_ckpt = args.pretrained_model_name_or_path
src_diffusers_model_path = None
else:
src_stable_diffusion_ckpt = None
src_diffusers_model_path = args.pretrained_model_name_or_path
if args.save_model_as is None:
save_stable_diffusion_format = load_stable_diffusion_format
use_safetensors = args.use_safetensors
else:
save_stable_diffusion_format = args.save_model_as.lower() == "ckpt" or args.save_model_as.lower() == "safetensors"
use_safetensors = args.use_safetensors or ("safetensors" in args.save_model_as.lower())
# Diffusers版のxformers使用フラグを設定する関数
def set_diffusers_xformers_flag(model, valid):
# model.set_use_memory_efficient_attention_xformers(valid) # 次のリリースでなくなりそう
# pipeが自動で再帰的にset_use_memory_efficient_attention_xformersを探すんだって(;´Д`)
# U-Netだけ使う時にはどうすればいいのか……仕方ないからコピって使うか
# 0.10.2でなんか巻き戻って個別に指定するようになった(;^ω^)
# Recursively walk through all the children.
# Any children which exposes the set_use_memory_efficient_attention_xformers method
# gets the message
def fn_recursive_set_mem_eff(module: torch.nn.Module):
if hasattr(module, "set_use_memory_efficient_attention_xformers"):
module.set_use_memory_efficient_attention_xformers(valid)
for child in module.children():
fn_recursive_set_mem_eff(child)
fn_recursive_set_mem_eff(model)
# モデルに xformers とか memory efficient attention を組み込む
if args.diffusers_xformers:
print("Use xformers by Diffusers")
set_diffusers_xformers_flag(unet, True)
else:
# Windows版のxformersはfloatで学習できないのでxformersを使わない設定も可能にしておく必要がある
print("Disable Diffusers' xformers")
set_diffusers_xformers_flag(unet, False)
train_util.replace_unet_modules(unet, args.mem_eff_attn, args.xformers)
# 学習を準備する
if cache_latents:
vae.to(accelerator.device, dtype=weight_dtype)
vae.requires_grad_(False)
vae.eval()
with torch.no_grad():
train_dataset_group.cache_latents(vae, args.vae_batch_size, args.cache_latents_to_disk, accelerator.is_main_process)
vae.to("cpu")
if torch.cuda.is_available():
torch.cuda.empty_cache()
gc.collect()
accelerator.wait_for_everyone()
# 学習を準備する:モデルを適切な状態にする
training_models = []
if args.gradient_checkpointing:
unet.enable_gradient_checkpointing()
training_models.append(unet)
if args.train_text_encoder:
print("enable text encoder training")
if args.gradient_checkpointing:
text_encoder.gradient_checkpointing_enable()
training_models.append(text_encoder)
else:
text_encoder.to(accelerator.device, dtype=weight_dtype)
text_encoder.requires_grad_(False) # text encoderは学習しない
if args.gradient_checkpointing:
text_encoder.gradient_checkpointing_enable()
text_encoder.train() # required for gradient_checkpointing
else:
text_encoder.eval()
if not cache_latents:
vae.requires_grad_(False)
vae.eval()
vae.to(accelerator.device, dtype=weight_dtype)
for m in training_models:
m.requires_grad_(True)
params = []
for m in training_models:
params.extend(m.parameters())
params_to_optimize = params
# 学習に必要なクラスを準備する
print("prepare optimizer, data loader etc.")
_, _, optimizer = train_util.get_optimizer(args, trainable_params=params_to_optimize)
# dataloaderを準備する
# DataLoaderのプロセス数:0はメインプロセスになる
n_workers = min(args.max_data_loader_n_workers, os.cpu_count() - 1) # cpu_count-1 ただし最大で指定された数まで
train_dataloader = torch.utils.data.DataLoader(
train_dataset_group,
batch_size=1,
shuffle=True,
collate_fn=collater,
num_workers=n_workers,
persistent_workers=args.persistent_data_loader_workers,
)
# 学習ステップ数を計算する
if args.max_train_epochs is not None:
args.max_train_steps = args.max_train_epochs * math.ceil(
len(train_dataloader) / accelerator.num_processes / args.gradient_accumulation_steps
)
print(f"override steps. steps for {args.max_train_epochs} epochs is / 指定エポックまでのステップ数: {args.max_train_steps}")
# データセット側にも学習ステップを送信
train_dataset_group.set_max_train_steps(args.max_train_steps)
# lr schedulerを用意する
lr_scheduler = train_util.get_scheduler_fix(args, optimizer, accelerator.num_processes)
# 実験的機能:勾配も含めたfp16学習を行う モデル全体をfp16にする
if args.full_fp16:
assert (
args.mixed_precision == "fp16"
), "full_fp16 requires mixed precision='fp16' / full_fp16を使う場合はmixed_precision='fp16'を指定してください。"
print("enable full fp16 training.")
unet.to(weight_dtype)
text_encoder.to(weight_dtype)
# acceleratorがなんかよろしくやってくれるらしい
if args.train_text_encoder:
unet, text_encoder, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
unet, text_encoder, optimizer, train_dataloader, lr_scheduler
)
else:
unet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(unet, optimizer, train_dataloader, lr_scheduler)
# transform DDP after prepare
text_encoder, unet = train_util.transform_if_model_is_DDP(text_encoder, unet)
# 実験的機能:勾配も含めたfp16学習を行う PyTorchにパッチを当ててfp16でのgrad scaleを有効にする
if args.full_fp16:
train_util.patch_accelerator_for_fp16_training(accelerator)
# resumeする
train_util.resume_from_local_or_hf_if_specified(accelerator, args)
# epoch数を計算する
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
if (args.save_n_epoch_ratio is not None) and (args.save_n_epoch_ratio > 0):
args.save_every_n_epochs = math.floor(num_train_epochs / args.save_n_epoch_ratio) or 1
# 学習する
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
print("running training / 学習開始")
print(f" num examples / サンプル数: {train_dataset_group.num_train_images}")
print(f" num batches per epoch / 1epochのバッチ数: {len(train_dataloader)}")
print(f" num epochs / epoch数: {num_train_epochs}")
print(f" batch size per device / バッチサイズ: {args.train_batch_size}")
print(f" total train batch size (with parallel & distributed & accumulation) / 総バッチサイズ(並列学習、勾配合計含む): {total_batch_size}")
print(f" gradient accumulation steps / 勾配を合計するステップ数 = {args.gradient_accumulation_steps}")
print(f" total optimization steps / 学習ステップ数: {args.max_train_steps}")
global_step = args.global_step
print(global_step)
progress_bar = tqdm(range(args.max_train_steps), initial=global_step, smoothing=0, disable=not accelerator.is_local_main_process, desc="steps")
noise_scheduler = DDPMScheduler(
beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000, clip_sample=False
) | prepare_scheduler_for_custom_training(noise_scheduler, accelerator.device) | 4 | 2023-12-30 07:46:35+00:00 | 8k |
khabbazan/Mattermost-Subscriptions | helpers/channels_graphql_ws/graphql_ws_consumer.py | [
{
"identifier": "DictAsObject",
"path": "helpers/channels_graphql_ws/dict_as_object.py",
"snippet": "class DictAsObject:\n \"\"\"Dict wrapper to access keys as attributes.\"\"\"\n\n def __init__(self, scope):\n \"\"\"Remember given `scope`.\"\"\"\n self._scope = scope\n\n def _asd... | import asyncio
import dataclasses
import functools
import inspect
import logging
import threading
import time
import traceback
import weakref
import channels.db
import channels.generic.websocket as ch_websocket
import graphene
import graphql
import graphql.error
import graphql.execution
import graphql.pyutils
import graphql.utilities
from typing import Any
from typing import AsyncIterator
from typing import Awaitable
from typing import Callable
from typing import Dict
from typing import Iterable
from typing import List
from typing import Optional
from typing import Tuple
from typing import Type
from typing import Union
from typing import cast
from .dict_as_object import DictAsObject
from .serializer import Serializer | 3,650 | return_type = info.return_type
while graphql.is_wrapping_type(return_type):
return_type = return_type.of_type # type: ignore[union-attr]
subscription_class = return_type.graphene_type # type: ignore[union-attr]
# It is ok to access private fields of `Subscription`
# implementation. `Subscription` class used to create
# subscriptions as graphene object but actually it is a part of
# consumer implementation.
# pylint: disable=protected-access
# Attach current subscription to the group corresponding to
# the concrete class. This allows to trigger all the
# subscriptions of the current type, by invoking `publish`
# without setting the `group` argument.
groups = [subscription_class._group_name()]
# Invoke the subclass-specified `subscribe` method to get
# the groups subscription must be attached to.
if subscription_class._meta.subscribe is not None:
subclass_groups = subscription_class._meta.subscribe(root, info, *args, **kwds)
# Properly handle `async def subscribe`.
if asyncio.iscoroutinefunction(subscription_class._meta.subscribe):
subclass_groups = await subclass_groups
assert subclass_groups is None or isinstance(subclass_groups, (list, tuple)), (
f"Method 'subscribe' returned a value of an incorrect type" f" {type(subclass_groups)}! A list, a tuple, or 'None' expected."
)
subclass_groups = subclass_groups or []
else:
subclass_groups = []
groups += [subscription_class._group_name(group) for group in subclass_groups]
# The subscription notification queue. Required to preserve the
# order of notifications within a single subscription.
queue_size = subscription_class.notification_queue_limit
if queue_size is None or queue_size <= 0:
# Take default limit from the Consumer class.
queue_size = self.subscription_notification_queue_limit
# The subscription notification queue.
# NOTE: The asyncio.Queue class is not thread-safe. So use the
# `notification_queue_lock` as a guard while reading or writing
# to the queue.
notification_queue: asyncio.Queue = asyncio.Queue(maxsize=queue_size)
# Lock to ensure that `notification_queue` operations are
# thread safe.
notification_queue_lock = threading.RLock()
unsubscribed = subscription_class._meta.unsubscribed
async def unsubscribed_callback():
"""Call `unsubscribed` notification.
The `cls._meta.unsubscribed` might do blocking operations,
so offload it to the thread.
"""
if unsubscribed is None:
return None
result = unsubscribed(None, info, *args, **kwds)
# Properly handle `async def unsubscribed`.
if inspect.isawaitable(result):
result = await result
def enqueue_notification(payload):
"""Put notification to the queue.
Called by the WebSocket consumer (instance of the
GraphqlWsConsumer subclass) when it receives the broadcast
message (from the Channels group) sent by the
Subscription.broadcast.
Args:
sid: Operation id of the subscription.
"""
while True:
with notification_queue_lock:
try:
notification_queue.put_nowait(payload)
break # The item was enqueued. Exit the loop.
except asyncio.QueueFull:
# The queue is full - issue a warning and throw
# away the oldest item from the queue.
# NOTE: Queue with the size 1 means that it is
# safe to drop intermediate notifications.
if notification_queue.maxsize != 1:
LOG.warning(
"Subscription notification dropped! Operation %s(%s).",
operation_name,
operation_id,
)
notification_queue.get_nowait()
notification_queue.task_done()
# Try to put the incoming item to the queue
# within the same lock. This is an speed
# optimization.
try:
notification_queue.put_nowait(payload)
# The item was enqueued. Exit the loop.
break
except asyncio.QueueFull:
# Kind'a impossible to get here, but if we
# do, then we should retry until the queue
# have capacity to process item.
pass
waitlist = []
for group in groups:
self._sids_by_group.setdefault(group, []).append(operation_id)
waitlist.append(asyncio.create_task(self._channel_layer.group_add(group, self.channel_name)))
self._subscriptions[operation_id] = self._SubInf(
groups=groups,
sid=operation_id,
unsubscribed_callback=unsubscribed_callback,
enqueue_notification=enqueue_notification,
)
if waitlist:
await asyncio.wait(waitlist)
| # Copyright (C) DATADVANCE, 2011-2023
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Channels consumer which implements GraphQL WebSocket protocol.
The `GraphqlWsConsumer` is a Channels WebSocket consumer which maintains
WebSocket connection with the client.
Implementation assumes that client uses the protocol implemented by the
library `subscription-transport-ws` (which is used by Apollo).
NOTE: Links based on which this functionality is implemented:
- Protocol description:
https://github.com/apollographql/subscriptions-transport-ws/blob/master/PROTOCOL.md
https://github.com/apollographql/subscriptions-transport-ws/blob/master/src/message-types.ts
- ASGI specification for WebSockets:
https://github.com/django/asgiref/blob/master/specs/www.rst#websocket
- GitHubGist with the root of inspiration:
https://gist.github.com/tricoder42/af3d0337c1b33d82c1b32d12bd0265ec
"""
# Module logger.
LOG = logging.getLogger(__name__)
# WebSocket subprotocol used for the GraphQL.
GRAPHQL_WS_SUBPROTOCOL = "graphql-ws"
class GraphqlWsConsumer(ch_websocket.AsyncJsonWebsocketConsumer):
"""Channels consumer for the WebSocket GraphQL backend.
NOTE: Each instance of this class maintains one WebSocket
connection to a single client.
This class implements the WebSocket-based GraphQL protocol used by
`subscriptions-transport-ws` library (used by Apollo):
https://github.com/apollographql/subscriptions-transport-ws/blob/master/PROTOCOL.md
"""
# ----------------------------------------------------------------- PUBLIC INTERFACE
# Overwrite this in the subclass to specify the GraphQL schema which
# processes GraphQL queries.
schema: graphene.Schema
# The interval to send keepalive messages to the clients (seconds).
send_keepalive_every: Optional[float] = None
# Set to `True` to process requests (i.e. GraphQL documents) from
# a client in order of arrival, which is the same as sending order,
# as guaranteed by the WebSocket protocol. This means that request
# processing for this particular client becomes serial - in other
# words, the server will not start processing another request
# before it finishes the current one. Note that requests from
# different clients (within different WebSocket connections)
# are still processed asynchronously. Useful for tests.
strict_ordering: bool = False
# When set to `True` the server will send an empty data message in
# response to the subscription. This is needed to let client know
# when the subscription activates, so he can be sure he doesn't miss
# any notifications. Disabled by default, cause this is an extension
# to the original protocol and the client must be tuned accordingly.
confirm_subscriptions: bool = False
# The message sent to the client when subscription activation
# confirmation is enabled.
subscription_confirmation_message: Dict[str, Any] = {"data": None, "errors": None}
# Issue a warning to the log when operation takes longer than
# specified number in seconds. None disables the warning.
warn_operation_timeout: Optional[float] = 1
# The size of the subscription notification queue. If there are more
# notifications (for a single subscription) than the given number,
# then an oldest notification is dropped and a warning is logged.
subscription_notification_queue_limit: int = 1024
# GraphQL middleware.
# Instance of `graphql.MiddlewareManager` or the list of functions
# (callables) like the following:
# ```python
# async def my_middleware(next_middleware, root, info, *args, **kwds):
# result = next_middleware(root, info, *args, **kwds)
# if graphql.pyutils.is_awaitable(result):
# result = await result
# return result
# ```
# The first middleware in the middlewares list will be the closest
# to the resolver in the middlewares call stack.
# For more information read docs:
# - https://docs.graphene-python.org/en/latest/execution/middleware/#middleware
# - https://graphql-core-3.readthedocs.io/en/latest/diffs.html#custom-middleware
# Docs about async middlewares are still missing - read the
# GraphQL-core sources to know more.
middleware: Optional[graphql.Middleware] = None
async def on_connect(self, payload):
"""Client connection handler.
Called after CONNECTION_INIT message from client. Overwrite and
raise an Exception to tell the server to reject the connection
when it's necessary.
Args:
payload: Payload from CONNECTION_INIT message.
"""
del payload
async def on_operation(self, op_id, payload):
"""Process business logic before operation processing starts.
Useful e.g. to check that user session is not yet expired.
Throw `graphql.error.GraphQLError` to cancel the operation.
Args:
op_id: Operation id.
payload: Payload of the operation.
"""
del op_id, payload
# ------------------------------------------------------------------- IMPLEMENTATION
# A prefix of Channel groups with subscription notifications.
group_name_prefix: str = "GQLWS"
# Structure that holds subscription information.
@dataclasses.dataclass
class _SubInf:
"""Subscription information structure."""
# Subscription identifier - protocol operation identifier.
sid: int
# Subscription groups the subscription belongs to.
groups: List[str]
# A function which triggets subscription.
enqueue_notification: Callable[[Any], None]
# The callback to invoke when client unsubscribes.
unsubscribed_callback: Callable[..., Awaitable[None]]
def __init__(self, *args, **kwargs):
"""Consumer constructor."""
assert self.schema is not None, "An attribute 'schema' is not set! Subclasses must specify " "the schema which processes GraphQL subscription queries."
# Registry of active (subscribed) subscriptions.
self._subscriptions: Dict[int, GraphqlWsConsumer._SubInf] = {} # {'<sid>': '<SubInf>', ...}
self._sids_by_group = {} # {'<grp>': ['<sid0>', '<sid1>', ...], ...}
# Tasks which send notifications to clients indexed by an
# operation/subscription id.
self._notifier_tasks: Dict[int, asyncio.Task] = {}
# Task that sends keepalive messages periodically.
self._keepalive_task = None
# Background tasks to clean it up when a client disconnects.
# We use weak collection so finished task will be autoremoved.
self._background_tasks: weakref.WeakSet = weakref.WeakSet()
# Crafty weak collection with per-operation locks. It holds a
# mapping from the operaion id (protocol message id) to the
# `asyncio.Lock` used to serialize processing of start & stop
# requests. Since the collection is weak, it automatically
# throws away items when locks are garbage collected.
self._operation_locks: weakref.WeakValueDictionary = weakref.WeakValueDictionary()
# MiddlewareManager maintains internal cache for resolvers
# wrapped with middlewares. Using the same manager for all
# operations improves performance.
self._middleware = None
if self.middleware:
self._middleware = self.middleware
if not isinstance(self._middleware, graphql.MiddlewareManager):
self._middleware = graphql.MiddlewareManager(*self._middleware)
super().__init__(*args, **kwargs)
# ---------------------------------------------------------- CONSUMER EVENT HANDLERS
async def connect(self):
"""Handle new WebSocket connection."""
# Check the subprotocol told by the client.
#
# NOTE: In Python 3.6 `scope["subprotocols"]` was a string, but
# starting with Python 3.7 it is a bytes. This can be a proper
# change or just a bug in the Channels to be fixed. So let's
# accept both variants until it becomes clear.
assert GRAPHQL_WS_SUBPROTOCOL in ((sp.decode() if isinstance(sp, bytes) else sp) for sp in self.scope["subprotocols"]), (
f"WebSocket client does not request for the subprotocol " f"{GRAPHQL_WS_SUBPROTOCOL}!"
)
# Accept connection with the GraphQL-specific subprotocol.
await self.accept(subprotocol=GRAPHQL_WS_SUBPROTOCOL)
async def disconnect(self, code):
"""Handle WebSocket disconnect.
Remove itself from the Channels groups, clear triggers and stop
sending keepalive messages.
"""
# Print debug or warning message depending on the value of the
# connection close code. We consider all reserved codes (<999),
# 1000 "Normal Closure", and 1001 "Going Away" as OK.
# See: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
if not code:
LOG.warning("WebSocket connection closed without a code!")
elif code <= 1001:
LOG.debug("WebSocket connection closed with code: %s.", code)
else:
LOG.warning("WebSocket connection closed with code: %s!", code)
# The list of awaitables to simultaneously wait at the end.
waitlist: List[asyncio.Task] = []
# Unsubscribe from the Channels groups.
waitlist += [asyncio.create_task(self._channel_layer.group_discard(group, self.channel_name)) for group in self._sids_by_group]
# Cancel all currently running background tasks.
for bg_task in self._background_tasks:
bg_task.cancel()
waitlist += list(self._background_tasks)
# Stop sending keepalive messages (if enabled).
if self._keepalive_task is not None:
self._keepalive_task.cancel()
waitlist += [self._keepalive_task]
# Stop tasks which listen to GraphQL lib and send notifications.
for notifier_task in self._notifier_tasks.values():
notifier_task.cancel()
waitlist += [notifier_task]
# Wait for tasks to stop.
if waitlist:
await asyncio.wait(waitlist)
self._background_tasks.clear()
self._keepalive_task = None
self._notifier_tasks.clear()
self._operation_locks.clear()
self._sids_by_group.clear()
self._subscriptions.clear()
async def receive_json(self, content): # pylint: disable=arguments-differ
"""Process WebSocket message received from the client.
NOTE: We force 'STOP' message processing to wait until 'START'
with the same operation id finishes (if it is running). This
protects us from race conditions which may happen when a client
stops operation immediately after starting it. An illustrative
example is a subscribe-unsubscribe pair. If we spawn processing
of both messages concurrently we can deliver subscription
confirmation after unsubscription confirmation.
"""
# Extract message type based on which we select how to proceed.
msg_type = content["type"].upper()
if msg_type == "CONNECTION_INIT":
task = self._on_gql_connection_init(payload=content["payload"])
elif msg_type == "CONNECTION_TERMINATE":
task = self._on_gql_connection_terminate()
elif msg_type == "START":
op_id = content["id"]
# Create and lock a mutex for this particular operation id,
# so STOP processing for the same operation id will wait
# until START processing finishes. Locks are stored in a
# weak collection so we do not have to manually clean it up.
if op_id in self._operation_locks:
raise graphql.error.GraphQLError(f"Operation with msg_id={op_id} is already running!")
op_lock = asyncio.Lock()
self._operation_locks[op_id] = op_lock
await op_lock.acquire()
async def on_start():
try:
# User hook which raises to cancel processing.
await self.on_operation(op_id, payload=content["payload"])
# START message processing.
await self._on_gql_start(op_id, payload=content["payload"])
except Exception as ex: # pylint: disable=broad-except
await self._send_gql_error(op_id, ex)
finally:
op_lock.release()
task = on_start()
elif msg_type == "STOP":
op_id = content["id"]
async def on_stop():
# Wait until START message processing finishes, if any.
async with self._operation_locks.setdefault(op_id, asyncio.Lock()):
await self._on_gql_stop(op_id)
task = on_stop()
else:
task = self._send_gql_error(
content["id"] if "id" in content else None,
Exception(f"Wrong message type '{msg_type}'!"),
)
# If strict ordering is required then simply wait until the
# message processing finishes. Otherwise spawn a task so
# Channels may continue calling `receive_json` while requests
# (i.e. GraphQL documents) are being processed.
if self.strict_ordering:
await task
else:
self._spawn_background_task(task)
async def broadcast(self, message):
"""The broadcast message handler.
Method is called when new `broadcast` message (sent by
`Subscription.broadcast`) received from the Channels group.
"""
# If strict ordering is required then simply wait until all the
# broadcast messages are sent. Otherwise spawn a task so this
# consumer will continue receiving messages.
if self.strict_ordering:
await self._process_broadcast(message)
else:
self._spawn_background_task(self._process_broadcast(message))
async def _process_broadcast(self, message):
"""Process the broadcast message.
This triggers subscription notification to all the subscriptions
belonging to the group received in the `message`.
NOTE: Depending on the value of the `strict_ordering` setting
this method is either awaited directly or offloaded to an async
task by the `broadcast` method (message handler).
"""
group = message["group"]
# Do nothing if group does not exist. It is quite possible for
# a client and a backend to concurrently unsubscribe and send
# notification. And these events do not need to be synchronized.
if group not in self._sids_by_group:
return
payload = message["payload"]
# Put the payload to the notification queues of subscriptions
# belonging to the subscription group. Drop the oldest payloads
# if the `notification_queue` is full.
for sid in self._sids_by_group[group]:
subinf = self._subscriptions[sid]
subinf.enqueue_notification(payload)
async def unsubscribe(self, message):
"""The unsubscribe message handler.
Method is called when new `unsubscribe` message received from
the Channels group. The message is typically sent by the method
`Subscription.unsubscribe`. Here we figure out the group message
received from and stop all the subscriptions in this group.
"""
group = message["group"]
# Do nothing if group does not exist. It is quite possible for
# a client and a backend to unsubscribe from a subscription
# concurrently. And these events do not need to be synchronized.
if group not in self._sids_by_group:
return
# Send messages which look like user unsubscribes from all
# subscriptions in the subscription group. This saves us from
# thinking about raise condition between subscription and
# unsubscription.
if self._sids_by_group[group]:
await asyncio.wait([asyncio.create_task(self.receive_json({"type": "stop", "id": sid})) for sid in self._sids_by_group[group]])
# ---------------------------------------------------------- GRAPHQL PROTOCOL EVENTS
async def _on_gql_connection_init(self, payload):
"""Process the CONNECTION_INIT message.
Start sending keepalive messages if `send_keepalive_every` set.
Respond with either CONNECTION_ACK or CONNECTION_ERROR message.
NOTE: Depending on the value of the `strict_ordering` setting
this method is either awaited directly or offloaded to an async
task. See the `receive_json` handler.
"""
try:
# Notify subclass a new client is connected.
await self.on_connect(payload)
except Exception as ex: # pylint: disable=broad-except
await self._send_gql_connection_error(ex)
# Close the connection. NOTE: We use the 4000 code because
# there are two reasons: A) We can not use codes greater
# than 1000 and less than 3000 because Daphne and Autobahn
# do not allow this (see `sendClose` from
# `autobahn/websocket/protocol.py` and
# `daphne/ws_protocol.py`). B)
# https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
# Mozilla offers codes 4000–4999 available for all apps.
await self.close(code=4000)
else:
# Send CONNECTION_ACK message.
await self._send_gql_connection_ack()
# If keepalive enabled then send one message immediately and
# schedule periodic messages.
if self.send_keepalive_every is not None:
send_keepalive_every = self.send_keepalive_every
async def keepalive_sender():
"""Send keepalive messages periodically."""
while True:
await asyncio.sleep(send_keepalive_every)
await self._send_gql_connection_keep_alive()
self._keepalive_task = asyncio.create_task(keepalive_sender())
# Immediately send keepalive message cause it is
# required by the protocol description.
await self._send_gql_connection_keep_alive()
async def _on_gql_connection_terminate(self):
"""Process the CONNECTION_TERMINATE message.
NOTE: Depending on the value of the `strict_ordering` setting
this method is either awaited directly or offloaded to an async
task. See the `receive_json` handler.
"""
# Close the connection.
await self.close(code=1000)
async def _on_gql_start(self, op_id, payload):
"""Process the START message.
Handle the message with query, mutation or subscription request.
NOTE: Depending on the value of the `strict_ordering` setting
this method is either awaited directly or offloaded to an async
task. See the `receive_json` handler.
"""
try:
if op_id in self._subscriptions:
message = f"Subscription with msg_id={op_id} already exists!"
raise graphql.error.GraphQLError(message)
# Get the message data.
query = payload["query"]
op_name = payload.get("operationName")
variables = payload.get("variables", {})
# Prepare a context object.
context = DictAsObject({})
context.channels_scope = self.scope
context.channel_name = self.channel_name
context.graphql_operation_name = op_name
context.graphql_operation_id = op_id
# Process the request with Graphene and GraphQL-core.
doc_ast, op_ast, errors = await self._on_gql_start__parse_query(op_name, query)
if errors:
await self._send_gql_data(op_id, None, errors)
await self._send_gql_complete(op_id)
return
# Assert values are not None to suppress MyPy complains.
assert doc_ast is not None
assert op_ast is not None
# If the operation is subscription.
if op_ast.operation == graphql.language.ast.OperationType.SUBSCRIPTION:
LOG.debug(
"Subscription request. Operation ID: %s, operation name: %s.)",
op_id,
op_name,
)
# This returns asynchronous generator or ExecutionResult
# instance in case of error.
subscr_result = await self._on_gql_start__subscribe(
doc_ast,
operation_name=op_name,
root_value=None,
variable_values=variables,
context_value=context,
subscribe_field_resolver=functools.partial(
self._on_gql_start__initialize_subscription_stream,
op_id,
op_name,
),
middleware=self._middleware,
)
# When subscr_result is an AsyncGenerator, consume
# stream of notifications and send them to clients.
if not isinstance(subscr_result, graphql.ExecutionResult):
stream = cast(AsyncIterator[graphql.ExecutionResult], subscr_result)
# Send subscription activation message (if enabled)
# NOTE: We do it before reading the the stream
# stream to guarantee that no notifications are sent
# before the subscription confirmation message.
if self.confirm_subscriptions:
await self._send_gql_data(
op_id,
data=self.subscription_confirmation_message["data"],
errors=self.subscription_confirmation_message["errors"],
)
consumer_init_done = asyncio.Event()
async def consume_stream():
consumer_init_done.set()
try:
async for item in stream:
# Skipped subscription event may have no
# data and no errors. Send message only
# when we have something to send.
if item.data or item.errors:
try:
await self._send_gql_data(op_id, item.data, item.errors)
except asyncio.CancelledError:
break
except Exception as ex: # pylint: disable=broad-except
LOG.debug(
"Exception in the subscription GraphQL resolver!" "Operation %s(%s).",
op_name,
op_id,
exc_info=ex,
)
await self._send_gql_data(op_id, None, [ex])
# We need to end this task when client drops
# connection or unsubscribes, so lets store it.
self._notifier_tasks[op_id] = asyncio.create_task(consume_stream())
# We must be sure here that the subscription
# initialization is finished and the stream consumer
# is active before we exit this function. Because in
# the outer scope we have locking mechanism of start
# and stop operations. And we want to say
# "subscription operation is started" only when it
# actually is.
# This allows us to avoid the race condition between
# simultaneous subscribe and unsubscribe calls.
await consumer_init_done.wait()
return
# Else (when gql_subscribe returns ExecutionResult
# containing error) fallback to standard handling below.
operation_result = cast(graphql.ExecutionResult, subscr_result)
# If the operation is query or mutation.
else:
LOG.debug("New query/mutation. Operation %s(%s).", op_name, op_id)
if self.warn_operation_timeout is not None:
start_time = time.perf_counter()
# Standard name for "IntrospectionQuery". We might also
# check that
# `doc_ast.definitions[0].selection_set.selections[0].name.value`
# equals to `__schema`. This is a more robust way. But
# it will eat up more CPU pre each query. For now lets
# check only a query name.
middleware_manager = self._middleware
if op_name == "IntrospectionQuery":
# No need to call middlewares for the
# IntrospectionQuery. There no real resolvers. Only
# the type information.
middleware_manager = None
exec_result = graphql.execution.execute(
self.schema.graphql_schema,
document=doc_ast,
root_value=None,
operation_name=op_name,
variable_values=variables,
context_value=context,
middleware=middleware_manager,
)
if inspect.isawaitable(exec_result):
exec_result = await exec_result
operation_result = cast(graphql.ExecutionResult, exec_result)
if self.warn_operation_timeout is not None:
duration = time.perf_counter() - start_time
if duration >= self.warn_operation_timeout:
LOG.warning(
"Operation %s(%s) took %.6f seconds. Debug" " log contains full operation details.",
op_name,
op_id,
duration,
)
LOG.debug(
"Operation %s(%s) took %.6f seconds. Query:" " %r, variables: %r.",
op_name,
op_id,
duration,
query,
variables,
)
# Respond to a query or mutation immediately.
await self._send_gql_data(op_id, operation_result.data, operation_result.errors)
await self._send_gql_complete(op_id)
except Exception as ex: # pylint: disable=broad-except
if isinstance(ex, graphql.error.GraphQLError):
# Respond with details of GraphQL execution error.
LOG.warning("GraphQL error! Operation %s(%s).", op_name, op_id, exc_info=True)
await self._send_gql_data(op_id, None, [ex])
await self._send_gql_complete(op_id)
else:
# Respond with general error responce.
await self._send_gql_error(op_id, ex)
async def _on_gql_start__parse_query(
self, op_name: str, query: str
) -> Tuple[Optional[graphql.DocumentNode], Optional[graphql.OperationDefinitionNode], Optional[Iterable[graphql.GraphQLError]],]:
"""Parse and validate GraphQL query.
It is highly likely that the same operation will be parsed many
times, so this function is wrapped with LRU cache.
This async function offloads the GraphQL processing to the
worker thread cause according to our experiments even GraphQL
document parsing and validation take a while and depends approx.
linearly on the size of the selection set.
This is a part of START message processing routine so the name
prefixed with `_on_gql_start__` to make this explicit.
Returns:
Tuple with three optional fields:
0: AST of parsed GraphQL document.
1: GraphQL operation definition.
2: Sequence of errors.
"""
res = await channels.db.database_sync_to_async(self._on_gql_start__parse_query_sync_cached, thread_sensitive=False)(op_name, query)
doc_ast: Optional[graphql.DocumentNode] = res[0]
op_ast: Optional[graphql.OperationDefinitionNode] = res[1]
errors: Optional[Iterable[graphql.GraphQLError]] = res[2]
return (doc_ast, op_ast, errors)
@functools.lru_cache(maxsize=128)
def _on_gql_start__parse_query_sync_cached(
self, op_name: str, query: str
) -> Tuple[Optional[graphql.DocumentNode], Optional[graphql.OperationDefinitionNode], Optional[Iterable[graphql.GraphQLError]],]:
"""Parse and validate GraphQL query. Cached sync implementation.
This is a part of START message processing routine so the name
prefixed with `_on_gql_start__` to make this explicit.
"""
# Parsing.
try:
doc_ast = graphql.parse(query)
except graphql.GraphQLError as ex:
return None, None, [ex]
# Validation.
validation_errors: List[graphql.GraphQLError] = graphql.validate(self.schema.graphql_schema, doc_ast)
if validation_errors:
return None, None, validation_errors
op_ast = graphql.utilities.get_operation_ast(doc_ast, op_name)
return doc_ast, op_ast, None
async def _on_gql_start__subscribe(
self,
document: graphql.DocumentNode,
root_value: Any = None,
context_value: Any = None,
variable_values: Optional[Dict[str, Any]] = None,
operation_name: Optional[str] = None,
field_resolver: Optional[graphql.GraphQLFieldResolver] = None,
subscribe_field_resolver: Optional[graphql.GraphQLFieldResolver] = None,
middleware: graphql.Middleware = None,
execution_context_class: Optional[Type[graphql.ExecutionContext]] = None,
) -> Union[AsyncIterator[graphql.ExecutionResult], graphql.ExecutionResult]:
"""Create a GraphQL subscription.
This is a copy of `graphql.execution.subscribe.subscribe` from
the GraphQL-core library v3.2.3 improved to support middlewares
and user defined execution_context_class.
This is a part of START message processing routine so the name
prefixed with `_on_gql_start__` to make this explicit.
"""
result_or_stream = await graphql.create_source_event_stream(
self.schema.graphql_schema,
document,
root_value,
context_value,
variable_values,
operation_name,
subscribe_field_resolver,
)
if isinstance(result_or_stream, graphql.ExecutionResult):
return result_or_stream
async def map_source_to_response(payload: Any) -> graphql.ExecutionResult:
"""Map source to response.
For each payload yielded from a subscription, map it over
the normal GraphQL :func:`~graphql.execute` function, with
`payload` as the `root_value`. This implements the
"MapSourceToResponseEvent" algorithm described in the
GraphQL specification. The :func:`~graphql.execute` function
provides the "ExecuteSubscriptionEvent" algorithm, as it is
nearly identical to the "ExecuteQuery" algorithm, for which
:func:`~graphql.execute` is also used.
"""
result = graphql.execute(
self.schema.graphql_schema,
document,
payload,
context_value,
variable_values,
operation_name,
field_resolver,
middleware=middleware,
execution_context_class=execution_context_class,
) # type: ignore
result = await result if inspect.isawaitable(result) else result
result = cast(graphql.ExecutionResult, result)
# Skip notification if subscription returned `None`.
if not result.errors and result.data:
for key in list(result.data.keys()):
if result.data[key] is None:
result.data.pop(key)
return result
# Map every source value to a ExecutionResult value.
return graphql.MapAsyncIterator(result_or_stream, map_source_to_response)
async def _on_gql_start__initialize_subscription_stream(
self,
operation_id: int,
operation_name: str,
root: Any,
info: graphql.GraphQLResolveInfo,
*args,
**kwds,
):
"""Create asynchronous generator with subscription events.
Called inside `_on_gql_start__subscribe` function by
graphql-core as `subscribe_field_resolver` argument.
This is a part of START message processing routine so the name
prefixed with `_on_gql_start__` to make this explicit.
"""
# Graphene stores original subscription class in `graphene_type`
# field of `return_type` object. Since subscriptions are build
# on top of `graphene` we always have graphene specific
# `return_type` class.
return_type = info.return_type
while graphql.is_wrapping_type(return_type):
return_type = return_type.of_type # type: ignore[union-attr]
subscription_class = return_type.graphene_type # type: ignore[union-attr]
# It is ok to access private fields of `Subscription`
# implementation. `Subscription` class used to create
# subscriptions as graphene object but actually it is a part of
# consumer implementation.
# pylint: disable=protected-access
# Attach current subscription to the group corresponding to
# the concrete class. This allows to trigger all the
# subscriptions of the current type, by invoking `publish`
# without setting the `group` argument.
groups = [subscription_class._group_name()]
# Invoke the subclass-specified `subscribe` method to get
# the groups subscription must be attached to.
if subscription_class._meta.subscribe is not None:
subclass_groups = subscription_class._meta.subscribe(root, info, *args, **kwds)
# Properly handle `async def subscribe`.
if asyncio.iscoroutinefunction(subscription_class._meta.subscribe):
subclass_groups = await subclass_groups
assert subclass_groups is None or isinstance(subclass_groups, (list, tuple)), (
f"Method 'subscribe' returned a value of an incorrect type" f" {type(subclass_groups)}! A list, a tuple, or 'None' expected."
)
subclass_groups = subclass_groups or []
else:
subclass_groups = []
groups += [subscription_class._group_name(group) for group in subclass_groups]
# The subscription notification queue. Required to preserve the
# order of notifications within a single subscription.
queue_size = subscription_class.notification_queue_limit
if queue_size is None or queue_size <= 0:
# Take default limit from the Consumer class.
queue_size = self.subscription_notification_queue_limit
# The subscription notification queue.
# NOTE: The asyncio.Queue class is not thread-safe. So use the
# `notification_queue_lock` as a guard while reading or writing
# to the queue.
notification_queue: asyncio.Queue = asyncio.Queue(maxsize=queue_size)
# Lock to ensure that `notification_queue` operations are
# thread safe.
notification_queue_lock = threading.RLock()
unsubscribed = subscription_class._meta.unsubscribed
async def unsubscribed_callback():
"""Call `unsubscribed` notification.
The `cls._meta.unsubscribed` might do blocking operations,
so offload it to the thread.
"""
if unsubscribed is None:
return None
result = unsubscribed(None, info, *args, **kwds)
# Properly handle `async def unsubscribed`.
if inspect.isawaitable(result):
result = await result
def enqueue_notification(payload):
"""Put notification to the queue.
Called by the WebSocket consumer (instance of the
GraphqlWsConsumer subclass) when it receives the broadcast
message (from the Channels group) sent by the
Subscription.broadcast.
Args:
sid: Operation id of the subscription.
"""
while True:
with notification_queue_lock:
try:
notification_queue.put_nowait(payload)
break # The item was enqueued. Exit the loop.
except asyncio.QueueFull:
# The queue is full - issue a warning and throw
# away the oldest item from the queue.
# NOTE: Queue with the size 1 means that it is
# safe to drop intermediate notifications.
if notification_queue.maxsize != 1:
LOG.warning(
"Subscription notification dropped! Operation %s(%s).",
operation_name,
operation_id,
)
notification_queue.get_nowait()
notification_queue.task_done()
# Try to put the incoming item to the queue
# within the same lock. This is an speed
# optimization.
try:
notification_queue.put_nowait(payload)
# The item was enqueued. Exit the loop.
break
except asyncio.QueueFull:
# Kind'a impossible to get here, but if we
# do, then we should retry until the queue
# have capacity to process item.
pass
waitlist = []
for group in groups:
self._sids_by_group.setdefault(group, []).append(operation_id)
waitlist.append(asyncio.create_task(self._channel_layer.group_add(group, self.channel_name)))
self._subscriptions[operation_id] = self._SubInf(
groups=groups,
sid=operation_id,
unsubscribed_callback=unsubscribed_callback,
enqueue_notification=enqueue_notification,
)
if waitlist:
await asyncio.wait(waitlist)
| _deserialize = channels.db.database_sync_to_async(Serializer.deserialize, thread_sensitive=False) | 1 | 2023-12-25 11:40:56+00:00 | 8k |
Hatins/DEOE | data/genx_utils/sequence_for_streaming.py | [
{
"identifier": "SparselyBatchedObjectLabels",
"path": "data/genx_utils/labels.py",
"snippet": "class SparselyBatchedObjectLabels:\n def __init__(self, sparse_object_labels_batch: List[Optional[ObjectLabels]]):\n # Can contain None elements that indicate missing labels.\n for entry in s... | from pathlib import Path
from typing import List, Optional, Union, Tuple
from omegaconf import DictConfig
from torchdata.datapipes.iter import IterDataPipe
from data.genx_utils.labels import SparselyBatchedObjectLabels
from data.genx_utils.sequence_base import SequenceBase, get_objframe_idx_2_repr_idx
from data.utils.augmentor import RandomSpatialAugmentorGenX
from data.utils.types import DatasetMode, DataType, DatasetType, LoaderDataDictGenX
from utils.timers import TimerDummy as Timer
import h5py
import numpy as np
import torch
import ipdb | 6,993 |
def _scalar_as_1d_array(scalar: Union[int, float]):
return np.atleast_1d(scalar)
def _get_ev_repr_range_indices(indices: np.ndarray, max_len: int) -> List[Tuple[int, int]]:
"""
Computes a list of index ranges based on the input array of indices and a maximum length.
The index ranges are computed such that the difference between consecutive indices
should not exceed the maximum length (max_len).
Parameters:
-----------
indices : np.ndarray
A NumPy array of indices, where the indices are sorted in ascending order.
max_len : int
The maximum allowed length between consecutive indices.
Returns:
--------
out : List[Tuple[int, int]]
A list of tuples, where each tuple contains two integers representing the start and
stop indices of the range.
"""
#np.flatnonzero 返回非零元素的索引
meta_indices_stop = np.flatnonzero(np.diff(indices) > max_len)
meta_indices_start = np.concatenate((np.atleast_1d(0), meta_indices_stop + 1))
meta_indices_stop = np.concatenate((meta_indices_stop, np.atleast_1d(len(indices) - 1)))
out = list()
for meta_idx_start, meta_idx_stop in zip(meta_indices_start, meta_indices_stop):
idx_start = max(indices[meta_idx_start] - max_len + 1, 0)
idx_stop = indices[meta_idx_stop] + 1
out.append((idx_start, idx_stop))
return out
class SequenceForIter(SequenceBase):
def __init__(self,
path: Path,
|
def _scalar_as_1d_array(scalar: Union[int, float]):
return np.atleast_1d(scalar)
def _get_ev_repr_range_indices(indices: np.ndarray, max_len: int) -> List[Tuple[int, int]]:
"""
Computes a list of index ranges based on the input array of indices and a maximum length.
The index ranges are computed such that the difference between consecutive indices
should not exceed the maximum length (max_len).
Parameters:
-----------
indices : np.ndarray
A NumPy array of indices, where the indices are sorted in ascending order.
max_len : int
The maximum allowed length between consecutive indices.
Returns:
--------
out : List[Tuple[int, int]]
A list of tuples, where each tuple contains two integers representing the start and
stop indices of the range.
"""
#np.flatnonzero 返回非零元素的索引
meta_indices_stop = np.flatnonzero(np.diff(indices) > max_len)
meta_indices_start = np.concatenate((np.atleast_1d(0), meta_indices_stop + 1))
meta_indices_stop = np.concatenate((meta_indices_stop, np.atleast_1d(len(indices) - 1)))
out = list()
for meta_idx_start, meta_idx_stop in zip(meta_indices_start, meta_indices_stop):
idx_start = max(indices[meta_idx_start] - max_len + 1, 0)
idx_stop = indices[meta_idx_stop] + 1
out.append((idx_start, idx_stop))
return out
class SequenceForIter(SequenceBase):
def __init__(self,
path: Path, | dataset_mode: DatasetMode, | 4 | 2023-12-29 04:04:34+00:00 | 8k |
yeyingdege/ctr-din-pytorch | din/train.py | [
{
"identifier": "DataIterator",
"path": "din/data_iterator.py",
"snippet": "class DataIterator:\n\n def __init__(self, source,\n uid_voc,\n mid_voc,\n cat_voc,\n batch_size=128,\n maxlen=100,\n skip_empty=... | import time
import random
import sys, os
import numpy as np
import argparse
import torch
from din.data_iterator import DataIterator
from din.model import DeepInterestNetwork
from din.utils import * | 5,028 | # for src, tgt in test_data:
nums += 1
uids, mids, cats, mid_his, cat_his, mid_mask, target, sl, noclk_mids, noclk_cats = prepare_data(src, tgt, return_neg=True)
uids = transform(uids)
mids = transform(mids)
cats = transform(cats)
mid_his = transform(mid_his)
cat_his = transform(cat_his)
mid_mask = transform(mid_mask)
noclk_mids = transform(noclk_mids)
noclk_cats = transform(noclk_cats)
target = transform(target)
prob = model(uids, mids, cats, mid_his, cat_his, mid_mask, noclk_mids, noclk_cats)
loss = - torch.mean(torch.log(prob) * target)
# acc = torch.mean(torch.round(prob) == target)
acc = torch.sum(torch.round(prob) * target) / target.shape[0]
loss_sum += loss
# aux_loss_sum = aux_loss
accuracy_sum += acc
prob_1 = prob[:, 0].tolist()
target_1 = target[:, 0].tolist()
for p ,t in zip(prob_1, target_1):
stored_arr.append([p, t])
test_auc = calc_auc(stored_arr)
accuracy_sum = accuracy_sum / nums
loss_sum = loss_sum / nums
global best_auc
if best_auc < test_auc:
best_auc = test_auc
torch.save({'model_state_dict': model.state_dict()}, model_path)
return test_auc, loss_sum, accuracy_sum
def train_one_epoch(epoch, model, train_data, test_data, optimizer,
maxlen, test_iter, save_iter, best_model_path, model_path):
train_data.reset()
iter = 0
loss_sum = 0.0
accuracy_sum = 0.
for _ in range(8000):
optimizer.zero_grad()
src, tgt = train_data.next()
# (B,), (B), (B), (B, 100), (B, 100), (B, 100), (B, 2), (B), (128, 100, 5), (128, 100, 5)
uids, mids, cats, mid_his, cat_his, mid_mask, target, sl, noclk_mids, noclk_cats = prepare_data(src, tgt, maxlen, return_neg=True)
uids = transform(uids)
mids = transform(mids)
cats = transform(cats)
mid_his = transform(mid_his)
cat_his = transform(cat_his)
mid_mask = transform(mid_mask)
noclk_mids = transform(noclk_mids)
noclk_cats = transform(noclk_cats)
target = transform(target)
y_hat = model(uids, mids, cats, mid_his, cat_his, mid_mask, noclk_mids, noclk_cats)
y_hat = y_hat + 1e-8
loss = - torch.mean(torch.log(y_hat) * target)
# acc = torch.mean(torch.round(y_hat) == target)
acc = torch.sum(torch.round(y_hat) * target) / target.shape[0]
loss_sum += loss
accuracy_sum += acc
loss.backward()
optimizer.step()
iter += 1
if (iter % test_iter) == 0:
print('[epoch: %d/iter: %d] ----> train_loss: %.4f ---- train_accuracy: %.4f' % \
(epoch, iter, loss_sum / test_iter, accuracy_sum / test_iter))
test_auc, test_loss, test_accuracy = eval(test_data, model, best_model_path)
print('test_auc: %.4f ----test_loss: %.4f ---- test_accuracy: %.4f' % (test_auc, test_loss.data, test_accuracy.data))
loss_sum = 0.0
accuracy_sum = 0.0
if (iter % save_iter) == 0:
# print('save model iter: %d' %(iter))
torch.save({
'EPOCH': epoch,
'iter': iter,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': loss,
}, f"{model_path}_ep{epoch}_{iter}")
return model, optimizer
def train(
train_file = "data/local_train_splitByUser",
test_file = "data/local_test_splitByUser",
uid_voc = "data/uid_voc.pkl",
mid_voc = "data/mid_voc.pkl",
cat_voc = "data/cat_voc.pkl",
batch_size = 128,
maxlen = 100,
test_iter = 500,
save_iter = 1000,
model_type = 'DIN',
seed = 2,
epochs = 5
):
out_dir1 = "output"
out_dir2 = "best_model"
os.makedirs(out_dir1, exist_ok=True)
os.makedirs(out_dir2, exist_ok=True)
model_path = f"{out_dir1}/ckpt_noshuff{model_type}{str(seed)}"
best_model_path = f"{out_dir2}/ckpt_noshuff{model_type}{str(seed)}"
train_data = DataIterator(train_file, uid_voc, mid_voc, cat_voc, batch_size, maxlen, shuffle_each_epoch=False)
test_data = DataIterator(test_file, uid_voc, mid_voc, cat_voc, batch_size, maxlen)
n_uid, n_mid, n_cat = train_data.get_n() #uid: 543060, mid: 367983, cat: 1601
if model_type == 'DIN':
| sys.path.append(os.getcwd())
EMBEDDING_DIM = 12
HIDDEN_DIM = [108,200,80,2]
ATTENTION_SIZE = EMBEDDING_DIM * 2
best_auc = 0.0
device = "cuda" if torch.cuda.is_available() else "cpu"
def transform(data):
return torch.from_numpy(data).to(device)
def prepare_data(input, target, maxlen=None, return_neg=False):
# x: a list of sentences
lengths_x = [len(s[4]) for s in input]
seqs_mid = [inp[3] for inp in input]
seqs_cat = [inp[4] for inp in input]
noclk_seqs_mid = [inp[5] for inp in input]
noclk_seqs_cat = [inp[6] for inp in input]
if maxlen is not None:
new_seqs_mid = []
new_seqs_cat = []
new_noclk_seqs_mid = []
new_noclk_seqs_cat = []
new_lengths_x = []
for l_x, inp in zip(lengths_x, input):
if l_x > maxlen:
new_seqs_mid.append(inp[3][l_x - maxlen:])
new_seqs_cat.append(inp[4][l_x - maxlen:])
new_noclk_seqs_mid.append(inp[5][l_x - maxlen:])
new_noclk_seqs_cat.append(inp[6][l_x - maxlen:])
new_lengths_x.append(maxlen)
else:
new_seqs_mid.append(inp[3])
new_seqs_cat.append(inp[4])
new_noclk_seqs_mid.append(inp[5])
new_noclk_seqs_cat.append(inp[6])
new_lengths_x.append(l_x)
lengths_x = new_lengths_x
seqs_mid = new_seqs_mid
seqs_cat = new_seqs_cat
noclk_seqs_mid = new_noclk_seqs_mid
noclk_seqs_cat = new_noclk_seqs_cat
if len(lengths_x) < 1:
return None, None, None, None
n_samples = len(seqs_mid)
maxlen_x = np.max(lengths_x)
neg_samples = len(noclk_seqs_mid[0][0])
mid_his = np.zeros((n_samples, maxlen_x)).astype('int64')
cat_his = np.zeros((n_samples, maxlen_x)).astype('int64')
noclk_mid_his = np.zeros((n_samples, maxlen_x, neg_samples)).astype('int64')
noclk_cat_his = np.zeros((n_samples, maxlen_x, neg_samples)).astype('int64')
mid_mask = np.zeros((n_samples, maxlen_x)).astype('float32')
for idx, [s_x, s_y, no_sx, no_sy] in enumerate(zip(seqs_mid, seqs_cat, noclk_seqs_mid, noclk_seqs_cat)):
mid_mask[idx, :lengths_x[idx]] = 1.
mid_his[idx, :lengths_x[idx]] = s_x
cat_his[idx, :lengths_x[idx]] = s_y
noclk_mid_his[idx, :lengths_x[idx], :] = no_sx
noclk_cat_his[idx, :lengths_x[idx], :] = no_sy
uids = np.array([inp[0] for inp in input])
mids = np.array([inp[1] for inp in input])
cats = np.array([inp[2] for inp in input])
if return_neg:
return uids, mids, cats, mid_his, cat_his, mid_mask, np.array(target), np.array(lengths_x), noclk_mid_his, noclk_cat_his
else:
return uids, mids, cats, mid_his, cat_his, mid_mask, np.array(target), np.array(lengths_x)
def eval(test_data, model, model_path):
test_data.reset()
loss_sum = 0.
accuracy_sum = 0.
nums = 0
stored_arr = []
for _ in range(100):
src, tgt = test_data.next()
# for src, tgt in test_data:
nums += 1
uids, mids, cats, mid_his, cat_his, mid_mask, target, sl, noclk_mids, noclk_cats = prepare_data(src, tgt, return_neg=True)
uids = transform(uids)
mids = transform(mids)
cats = transform(cats)
mid_his = transform(mid_his)
cat_his = transform(cat_his)
mid_mask = transform(mid_mask)
noclk_mids = transform(noclk_mids)
noclk_cats = transform(noclk_cats)
target = transform(target)
prob = model(uids, mids, cats, mid_his, cat_his, mid_mask, noclk_mids, noclk_cats)
loss = - torch.mean(torch.log(prob) * target)
# acc = torch.mean(torch.round(prob) == target)
acc = torch.sum(torch.round(prob) * target) / target.shape[0]
loss_sum += loss
# aux_loss_sum = aux_loss
accuracy_sum += acc
prob_1 = prob[:, 0].tolist()
target_1 = target[:, 0].tolist()
for p ,t in zip(prob_1, target_1):
stored_arr.append([p, t])
test_auc = calc_auc(stored_arr)
accuracy_sum = accuracy_sum / nums
loss_sum = loss_sum / nums
global best_auc
if best_auc < test_auc:
best_auc = test_auc
torch.save({'model_state_dict': model.state_dict()}, model_path)
return test_auc, loss_sum, accuracy_sum
def train_one_epoch(epoch, model, train_data, test_data, optimizer,
maxlen, test_iter, save_iter, best_model_path, model_path):
train_data.reset()
iter = 0
loss_sum = 0.0
accuracy_sum = 0.
for _ in range(8000):
optimizer.zero_grad()
src, tgt = train_data.next()
# (B,), (B), (B), (B, 100), (B, 100), (B, 100), (B, 2), (B), (128, 100, 5), (128, 100, 5)
uids, mids, cats, mid_his, cat_his, mid_mask, target, sl, noclk_mids, noclk_cats = prepare_data(src, tgt, maxlen, return_neg=True)
uids = transform(uids)
mids = transform(mids)
cats = transform(cats)
mid_his = transform(mid_his)
cat_his = transform(cat_his)
mid_mask = transform(mid_mask)
noclk_mids = transform(noclk_mids)
noclk_cats = transform(noclk_cats)
target = transform(target)
y_hat = model(uids, mids, cats, mid_his, cat_his, mid_mask, noclk_mids, noclk_cats)
y_hat = y_hat + 1e-8
loss = - torch.mean(torch.log(y_hat) * target)
# acc = torch.mean(torch.round(y_hat) == target)
acc = torch.sum(torch.round(y_hat) * target) / target.shape[0]
loss_sum += loss
accuracy_sum += acc
loss.backward()
optimizer.step()
iter += 1
if (iter % test_iter) == 0:
print('[epoch: %d/iter: %d] ----> train_loss: %.4f ---- train_accuracy: %.4f' % \
(epoch, iter, loss_sum / test_iter, accuracy_sum / test_iter))
test_auc, test_loss, test_accuracy = eval(test_data, model, best_model_path)
print('test_auc: %.4f ----test_loss: %.4f ---- test_accuracy: %.4f' % (test_auc, test_loss.data, test_accuracy.data))
loss_sum = 0.0
accuracy_sum = 0.0
if (iter % save_iter) == 0:
# print('save model iter: %d' %(iter))
torch.save({
'EPOCH': epoch,
'iter': iter,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': loss,
}, f"{model_path}_ep{epoch}_{iter}")
return model, optimizer
def train(
train_file = "data/local_train_splitByUser",
test_file = "data/local_test_splitByUser",
uid_voc = "data/uid_voc.pkl",
mid_voc = "data/mid_voc.pkl",
cat_voc = "data/cat_voc.pkl",
batch_size = 128,
maxlen = 100,
test_iter = 500,
save_iter = 1000,
model_type = 'DIN',
seed = 2,
epochs = 5
):
out_dir1 = "output"
out_dir2 = "best_model"
os.makedirs(out_dir1, exist_ok=True)
os.makedirs(out_dir2, exist_ok=True)
model_path = f"{out_dir1}/ckpt_noshuff{model_type}{str(seed)}"
best_model_path = f"{out_dir2}/ckpt_noshuff{model_type}{str(seed)}"
train_data = DataIterator(train_file, uid_voc, mid_voc, cat_voc, batch_size, maxlen, shuffle_each_epoch=False)
test_data = DataIterator(test_file, uid_voc, mid_voc, cat_voc, batch_size, maxlen)
n_uid, n_mid, n_cat = train_data.get_n() #uid: 543060, mid: 367983, cat: 1601
if model_type == 'DIN': | model = DeepInterestNetwork(n_uid, n_mid, n_cat, EMBEDDING_DIM, HIDDEN_DIM) | 1 | 2023-12-27 05:53:50+00:00 | 8k |
Enthusiasm23/primkit | src/primkit/designer/Primer.py | [
{
"identifier": "MFE_PRIMER",
"path": "src/primkit/config.py",
"snippet": "MFE_PRIMER = os.environ.get('MFE_PRIMER', \"https://mfeprimer3.igenetech.com\")"
},
{
"identifier": "PRIMER_URL",
"path": "src/primkit/config.py",
"snippet": "PRIMER_URL = os.environ.get('PRIMER_URL', f\"{MFE_PRIM... | import re
import time
import logging
import requests
from bs4 import BeautifulSoup
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from selenium.common import NoSuchElementException
from ..config import MFE_PRIMER, PRIMER_URL, RETRY_INTERVAL, \
MAX_RETRIES, CHECK_INTERVAL, PRIMER_PARAMS, PARAMS_CONSTRAINTS, \
PRIMER_SET_COUNT, WAITING_TIMEOUT
from ..utils.SiteSeleniumer import WebDriverUtility | 5,078 | logger.info(f"Validating parameter {parameter} with value {value}.")
if parameter in ['DB', 'SnpFilter']:
if value not in constraints:
logger.error(f"Value for {parameter} is not within the allowed constraints.")
return value in constraints
elif parameter in ['PrimerMinSize', 'PrimerOptSize', 'PrimerMaxSize',
'PrimerMinTm', 'PrimerOptTm', 'PrimerMaxTm',
'ProdMinSize', 'ProdMaxSize',
'DimerScore', 'HairpinScore', 'Tm',
'SpecMinSize', 'SpecMaxSize']:
if not (constraints[0] <= int(value) <= constraints[1]):
logger.error(f"Value for {parameter} is not within the allowed range of {constraints}.")
return constraints[0] <= int(value) <= constraints[1]
else:
return True
def validate_bed_input(bed_input, max_count=PRIMER_SET_COUNT):
"""
Validates the format of the BedInput parameter and ensures the number of entries does not exceed the maximum count.
The BedInput should be a string containing lines with specific chromosomes (chr1 to chr22, chrX, chrY),
start, and end positions, separated by tabs or spaces and ending with a newline character.
Regular expression matches lines with "chr[specific chromosome][spaces/tabs][number][spaces/tabs][number][newline]"
:param bed_input: The input string in BED format to validate.
:param max_count: The maximum number of entries allowed.
:return: A tuple containing a boolean indicating if the BedInput format is correct and the processed BedInput.
"""
logger.info("Validating the BedInput format.")
bed_lines = bed_input.splitlines()
if len(bed_lines) > max_count:
logger.warning(
f"BedInput contains more than {max_count} entries. Only the first {max_count} will be processed.")
bed_lines = bed_lines[:max_count] # Keep only the first 20 entries
bed_input_pattern = re.compile(r'chr(?:[1-9]|1\d|2[0-2]|X|Y)\s+(\d+)\s+(\d+)(\r?\n|$)')
for line in bed_lines:
match = bed_input_pattern.match(line)
if not match:
logger.error(
f"Line does not match the expected format: {line}. (Expected format: 'chr[specific chromosome][spaces/tabs][number][spaces/tabs][number][newline]').")
return False, bed_input # Return original bed_input for further reference
start, end = map(int, match.groups()[:2])
if start >= end:
logger.error(
f"Starting position is greater than or equal to the ending position in the line: {line}. (The ending position must be greater than the starting position by at least 1 base pair (bp).)")
return False, bed_input
processed_bed_input = "\n".join(bed_lines) # Reconstruct the BedInput with potentially fewer lines
return True, processed_bed_input
def build_data_dict(token, bed_input, custom_params=None, default_params=None):
"""
Builds a data dictionary using default and custom parameters.
:param token: The authentication token required for the POST request.
:param bed_input: The BED format input containing chromosome, start, and end positions.
:param custom_params: A dictionary of parameters provided by the user to override defaults.
:param default_params: A dictionary of default parameters for the POST request.
:return: A dictionary containing the combined default and custom parameters.
"""
logger.info("Building data dictionary with parameters.")
data = default_params.copy() if default_params else {}
data.update(custom_params if custom_params else {})
data['_xsrf'] = token
data['BedInput'] = bed_input
return data
def prepare_post_data(token, bed_input, custom_params=None, default_params=PRIMER_PARAMS,
constraints=PARAMS_CONSTRAINTS):
"""
Prepares the data for a POST request by validating parameters and constructing a data dictionary.
:param token: The authentication token required for the POST request.
:param bed_input: The BED format input containing chromosome, start, and end positions.
:param custom_params: Optional; A dictionary of parameters provided by the user to override defaults.
:param default_params: Optional; A dictionary of default parameters for the POST request.
:param constraints: Optional; A dictionary of constraints for parameter validation.
:return: A dictionary ready to be sent in a POST request if all validations pass.
:raises ValueError: If token is empty, BedInput format is incorrect, custom_params is not a dictionary,
or if any parameter is out of its constraint range.
"""
logger.info("Preparing post data.")
if not token:
logger.error("Token parameter cannot be empty.")
raise ValueError("Token parameter cannot be empty.")
valid, processed_bed_input = validate_bed_input(bed_input)
if not valid:
logger.error("BedInput format is incorrect.")
raise ValueError("BedInput format is incorrect.")
if custom_params is not None and not isinstance(custom_params, dict):
logger.error("Custom_params must be a dictionary.")
raise ValueError("Custom_params must be a dictionary.")
valid_keys = constraints.keys()
for key in custom_params or {}:
if key not in valid_keys:
valid_keys_str = ', '.join(valid_keys)
logger.error(f"Invalid parameter: {key}. Valid keys are: {valid_keys_str}")
raise ValueError(f"Invalid parameter: {key}. Valid keys are: {valid_keys_str}")
data = build_data_dict(token, processed_bed_input, custom_params, default_params)
for key, value in data.items():
if not validate_parameter(key, value, constraints.get(key, [])):
logger.error(f"Parameter {key} with value {value} is out of constraint range.")
raise ValueError(f"Parameter {key} with value {value} is out of constraint range.")
logger.info("Data prepared successfully.")
return data
def submit_and_track(data, headers, cookies, url=PRIMER_URL, root_url=MFE_PRIMER, max_retries=MAX_RETRIES,
|
logger = logging.getLogger(__name__)
def validate_parameter(parameter, value, constraints):
"""
Validates if a single parameter value is within its constraint range.
:param parameter: The name of the parameter to validate.
:param value: The value of the parameter to validate.
:param constraints: A list or tuple containing the allowed range or set of values for the parameter.
:return: Boolean indicating whether the parameter value is valid.
"""
logger.info(f"Validating parameter {parameter} with value {value}.")
if parameter in ['DB', 'SnpFilter']:
if value not in constraints:
logger.error(f"Value for {parameter} is not within the allowed constraints.")
return value in constraints
elif parameter in ['PrimerMinSize', 'PrimerOptSize', 'PrimerMaxSize',
'PrimerMinTm', 'PrimerOptTm', 'PrimerMaxTm',
'ProdMinSize', 'ProdMaxSize',
'DimerScore', 'HairpinScore', 'Tm',
'SpecMinSize', 'SpecMaxSize']:
if not (constraints[0] <= int(value) <= constraints[1]):
logger.error(f"Value for {parameter} is not within the allowed range of {constraints}.")
return constraints[0] <= int(value) <= constraints[1]
else:
return True
def validate_bed_input(bed_input, max_count=PRIMER_SET_COUNT):
"""
Validates the format of the BedInput parameter and ensures the number of entries does not exceed the maximum count.
The BedInput should be a string containing lines with specific chromosomes (chr1 to chr22, chrX, chrY),
start, and end positions, separated by tabs or spaces and ending with a newline character.
Regular expression matches lines with "chr[specific chromosome][spaces/tabs][number][spaces/tabs][number][newline]"
:param bed_input: The input string in BED format to validate.
:param max_count: The maximum number of entries allowed.
:return: A tuple containing a boolean indicating if the BedInput format is correct and the processed BedInput.
"""
logger.info("Validating the BedInput format.")
bed_lines = bed_input.splitlines()
if len(bed_lines) > max_count:
logger.warning(
f"BedInput contains more than {max_count} entries. Only the first {max_count} will be processed.")
bed_lines = bed_lines[:max_count] # Keep only the first 20 entries
bed_input_pattern = re.compile(r'chr(?:[1-9]|1\d|2[0-2]|X|Y)\s+(\d+)\s+(\d+)(\r?\n|$)')
for line in bed_lines:
match = bed_input_pattern.match(line)
if not match:
logger.error(
f"Line does not match the expected format: {line}. (Expected format: 'chr[specific chromosome][spaces/tabs][number][spaces/tabs][number][newline]').")
return False, bed_input # Return original bed_input for further reference
start, end = map(int, match.groups()[:2])
if start >= end:
logger.error(
f"Starting position is greater than or equal to the ending position in the line: {line}. (The ending position must be greater than the starting position by at least 1 base pair (bp).)")
return False, bed_input
processed_bed_input = "\n".join(bed_lines) # Reconstruct the BedInput with potentially fewer lines
return True, processed_bed_input
def build_data_dict(token, bed_input, custom_params=None, default_params=None):
"""
Builds a data dictionary using default and custom parameters.
:param token: The authentication token required for the POST request.
:param bed_input: The BED format input containing chromosome, start, and end positions.
:param custom_params: A dictionary of parameters provided by the user to override defaults.
:param default_params: A dictionary of default parameters for the POST request.
:return: A dictionary containing the combined default and custom parameters.
"""
logger.info("Building data dictionary with parameters.")
data = default_params.copy() if default_params else {}
data.update(custom_params if custom_params else {})
data['_xsrf'] = token
data['BedInput'] = bed_input
return data
def prepare_post_data(token, bed_input, custom_params=None, default_params=PRIMER_PARAMS,
constraints=PARAMS_CONSTRAINTS):
"""
Prepares the data for a POST request by validating parameters and constructing a data dictionary.
:param token: The authentication token required for the POST request.
:param bed_input: The BED format input containing chromosome, start, and end positions.
:param custom_params: Optional; A dictionary of parameters provided by the user to override defaults.
:param default_params: Optional; A dictionary of default parameters for the POST request.
:param constraints: Optional; A dictionary of constraints for parameter validation.
:return: A dictionary ready to be sent in a POST request if all validations pass.
:raises ValueError: If token is empty, BedInput format is incorrect, custom_params is not a dictionary,
or if any parameter is out of its constraint range.
"""
logger.info("Preparing post data.")
if not token:
logger.error("Token parameter cannot be empty.")
raise ValueError("Token parameter cannot be empty.")
valid, processed_bed_input = validate_bed_input(bed_input)
if not valid:
logger.error("BedInput format is incorrect.")
raise ValueError("BedInput format is incorrect.")
if custom_params is not None and not isinstance(custom_params, dict):
logger.error("Custom_params must be a dictionary.")
raise ValueError("Custom_params must be a dictionary.")
valid_keys = constraints.keys()
for key in custom_params or {}:
if key not in valid_keys:
valid_keys_str = ', '.join(valid_keys)
logger.error(f"Invalid parameter: {key}. Valid keys are: {valid_keys_str}")
raise ValueError(f"Invalid parameter: {key}. Valid keys are: {valid_keys_str}")
data = build_data_dict(token, processed_bed_input, custom_params, default_params)
for key, value in data.items():
if not validate_parameter(key, value, constraints.get(key, [])):
logger.error(f"Parameter {key} with value {value} is out of constraint range.")
raise ValueError(f"Parameter {key} with value {value} is out of constraint range.")
logger.info("Data prepared successfully.")
return data
def submit_and_track(data, headers, cookies, url=PRIMER_URL, root_url=MFE_PRIMER, max_retries=MAX_RETRIES, | retry_interval=RETRY_INTERVAL): | 2 | 2023-12-25 14:12:46+00:00 | 8k |
Wangyuhao06/2022-adhoc | src/env.py | [
{
"identifier": "random_waypoint",
"path": "pymobility/models/mobility.py",
"snippet": "def random_waypoint(*args, **kwargs):\n return iter(RandomWaypoint(*args, **kwargs))"
},
{
"identifier": "Node",
"path": "src/node.py",
"snippet": "class Node(object):\n def __init__(self,id_nod... | import random
import numpy as np
from math import log2, log10
from queue import Queue
from pymobility.models.mobility import random_waypoint
from src.node import Node
from src.packet import Packet
from src.parameter import *
from src.transtask import Trans_task | 4,746 | all_ob.append(pw+dgr+pcs+dn)
#self.node_list[node_id].ob_send=neibor_vector
return np.array(all_ob)
# def generate_trans_task(self,trans_id,send_node,rec_node,packet):
# trans_task_temp=Trans_task(trans_id,send_node,rec_node,packet)
# return trans_task_temp
def env_check_right(self):
for node_id in self.live_node_ID_list:
if self.node_list[node_id].trans_task_send.empty():
assert self.node_list[node_id].sending_flag == 0
elif not self.node_list[node_id].trans_task_send.empty():
assert self.node_list[node_id].sending_flag == 1
st_temp=self.node_list[node_id].trans_task_send.get()
self.node_list[node_id].trans_task_send.put(st_temp)#无损使用队列内容
s_node_send_id,s_node_rec_id,s_packet_id=st_temp.show_info()
assert node_id==s_node_send_id
# assert self.node_list[node_id].next_hop_id==s_node_rec_id
assert self.node_list[node_id].packets_ToSend_id[0]==s_packet_id
elif self.node_list[node_id].trans_task_rec.empty():
assert self.rec_flag == 0
elif not self.node_list[node_id].trans_task_rec.empty():
assert self.node_list[node_id].rec_flag == 1
rt_temp=self.node_list[node_id].trans_task_rec.get()
self.node_list[node_id].trans_task_rec.put(rt_temp)#无损使用队列内容
r_node_send_id,r_node_rec_id,r_packet_id=rt_temp.show_info()
assert node_id==r_node_rec_id
# assert self.node_list[node_id].next_hop_id==s_node_rec_id
assert self.node_list[node_id].packets_ToSend_id[0] != r_packet_id
return 0
def topology_update(self,cur_time,rand_change):
self.topology = np.zeros((NODE_MAX,NODE_MAX))
################--------随机更改拓扑结构--------################
if rand_change:
positions=next(self.geo_area)
self.position = positions
for a in range(NODE_MAX):
for b in range(NODE_MAX):
if np.linalg.norm(positions[a]-positions[b]) <= COM_RANGE:
self.topology[a,b]=1
self.topology[b,a]=1
else:
self.topology[a,b]=0
self.topology[b,a]=0
# if np.random.rand()<DELTA and cur_time%30==0:
# for i in np.random.randint(0,self.node_max,np.random.randint(3)+1):
# self.topology[i,:]=np.random.randint(0,2,self.node_max)
# self.topology[i,i] = 1
# for j in range(self.node_max):
# #构建双向图
# if self.topology[i,j] == 1:
# self.topology[j,i] = 1
# print(positions)
# print("****************")
# print(self.topology)
# print("------------------------------------")
################--------更新邻域--------################
self.live_node_ID_list=[]
self.topology_actSpace=[]
for i in range(self.topology.shape[0]):
if any(self.topology[i,:]):
TPtemp = np.nonzero(self.topology[i,:])
# self.node_list[i].neibor_idlist=TPtemp
self.topology_actSpace.append(TPtemp)
self.live_node_ID_list.append(i)
else:
TPtemp = -1
self.topology_actSpace.append(TPtemp)
return self.topology
def get_state_reward(self):
return self.topology,self.all_ob,self.reward
def time_step(self,cur_time,action):
self.packet_arrive_success=[]
self.agent_arrive=[]
for i in range(NODE_MAX):
self.packet_arrive_success.append(0)
self.agent_arrive.append(0)
self.arrive_success=0
# self.env_check_right()
topology_now=self.topology_update(cur_time,1)
self.generate_packet(cur_time)
self.all_ob=self.all_agent_observe()
self.trans_task_update(cur_time)
for node_index in self.live_node_ID_list :
if len(self.node_list[node_index].packets_ToSend_id)>0 and self.node_list[node_index].sending_flag!=1:
packet_toSend_id=self.node_list[node_index].packets_ToSend_id[0]
#包未到达且非在传----->生成trans_task
if self.packets_list[packet_toSend_id].arrive_flag==0 and self.packets_list[packet_toSend_id].in_TR==0:
#传输和接收节点决策
send_node=self.node_list[node_index]
Action=action[node_index]#######################################################
next_hop_id,current_freqB,current_amp_send=Action[0],Action[1:N_ACTION_C],Action[N_ACTION_C]
send_node.next_hop_id=next_hop_id
rec_node=self.node_list[next_hop_id]
current_amp_rec=RECAMP
self.node_list[node_index].current_freqB=current_freqB
self.node_list[node_index].next_hop_id=next_hop_id
self.node_list[node_index].current_amp_send=current_amp_send
#频谱环境更新
freqB_ID_now=0
for fB_ocp in current_freqB:
if node_index!=next_hop_id and fB_ocp:
self.freqB_list[freqB_ID_now].append(node_index)
self.freqB_use_history[freqB_ID_now].append(node_index)
freqB_ID_now+=1
#T-T生成与T-T环境更新
|
class Environment():
#初始化环境
def __init__(self):
#初始数据-最大节点数
self.node_max=NODE_MAX
self.node_space_size=NODE_MAX
self.node_moving_area=MOV_AREA
#初始化二维平面
self.geo_area = random_waypoint(self.node_max, dimensions=(MOV_AREA, MOV_AREA), velocity=(10, 15), wt_max=1.0)
self.position=0
#初始化随机相邻矩阵
self.topology = np.zeros((self.node_space_size,self.node_space_size))
self.topology[0:self.node_max,0:self.node_max] = np.random.randint(0,2,(self.node_max,self.node_max))
for i in range(self.node_max):
self.topology[i,i] = 1
for j in range(self.node_max):
#构建双向图
if self.topology[i,j] == 1:
self.topology[j,i] = 1
#初始化节点动作空间
self.topology_actSpace=[]
#初始化频谱块元组-----(0,[])表示(占用与否,[占用transtaskID列表])
self.freqB_list=([],[],[],[],[],[],[],[],[],[]) #((0,[]),(0,[]),(0,[]),(0,[]),(0,[]),(0,[]),(0,[]),(0,[]),(0,[]),(0,[]))
self.freqB_use_history=([],[],[],[],[],[],[],[],[],[])
#初始化传输事件列表
self.trans_task_ID_inTR=[]
self.trans_task_list=[]
self.trans_task_cnt=0 # id计数器
#初始化包列表
self.amount_poisson_list = np.random.poisson(lam=LAMDA,size=MAX_TIME)#包数量初始化
self.size_normal_list = ((np.random.normal(0,1,MAX_TIME*2)*16+16)//8)*8#包大小初始化
self.pack_use_cnt=0#包序号计数器
self.packets_list=[]#包列表
self.packets_live_id=[]
#初始化节点列表
self.node_list=[]
self.live_node_ID_list=[]
for i in range(self.node_max):
locals()['node_'+str(i)] = Node(i)
self.node_list.append(locals()['node_'+str(i)])
self.live_node_ID_list.append(i)
#噪声系数
self.noise_list = np.random.rayleigh(1,MAX_TIME*2)#*NOISE_CONST/2
#统计参数
self.envTr_time=0
self.allNode_pw=0
self.allNode_delay=0
self.time_avg=0
self.arrive_time=1
self.end=0
self.terminate=0
self.packet_arrive_success=[]
self.agent_arrive=[]
for i in range(NODE_MAX):
self.packet_arrive_success.append(0)#节点作为 |源节点| 发的包成功到达数
self.agent_arrive.append(0)#节点作为 |最后一个中间节点| 发的包成功到达数
# self.sum_packet_done_rate=0
#四元组
self.all_ob=np.array([[0]*OBS_LEN]*NODE_MAX)
self.reward=np.array([1]*self.node_max)
self.para_reward=np.array([1]*self.node_max)
def generate_packet(self,cur_time):
packetsList_temp=[]
packets_cnt=self.amount_poisson_list[cur_time]
for i in range(packets_cnt):
nodes_temp = random.sample(self.live_node_ID_list,2)
locals()['packet_'+str(self.pack_use_cnt)]=Packet(self.pack_use_cnt,abs(self.size_normal_list[self.pack_use_cnt])+8,nodes_temp[0],nodes_temp[1],cur_time)
self.packets_list.append(locals()['packet_'+str(self.pack_use_cnt)])
self.packets_live_id.append(self.pack_use_cnt)
packetsList_temp.append(locals()['packet_'+str(self.pack_use_cnt)])
self.node_list[nodes_temp[0]].packets_ToSend_id.append(self.pack_use_cnt)
self.node_list[nodes_temp[0]].packets_id_list.append(self.pack_use_cnt)
self.pack_use_cnt+=1
return packetsList_temp
#传输任务更新
def trans_task_update(self,cur_time):
if len(self.trans_task_ID_inTR)>0 and len(self.trans_task_list)>0:
#所有在传传输任务
for trans_temp_id in self.trans_task_ID_inTR:
task_finish=self.trans_task_list[trans_temp_id].Trans_task_update()
node_send_id,node_rec_id,packet_id=self.trans_task_list[trans_temp_id].show_info()
#包传输更新
self.packets_list[packet_id].time_use+=1
#节点更新
# self.node_list[node_send_id].next_hop_id=node_rec_id
if node_send_id!=node_rec_id:
self.node_list[node_send_id].power_list.append(self.trans_task_list[trans_temp_id].power_consume[0])
self.node_list[node_send_id].current_power_send=self.trans_task_list[trans_temp_id].power_consume[0]
self.node_list[node_send_id].energy_consumption+=self.trans_task_list[trans_temp_id].power_consume[0]
self.node_list[node_rec_id].power_list.append(self.trans_task_list[trans_temp_id].power_consume[1])
self.node_list[node_rec_id].current_power_receive=self.trans_task_list[trans_temp_id].power_consume[1]
self.node_list[node_rec_id].energy_consumption+=self.trans_task_list[trans_temp_id].power_consume[1]
#统计参数更新
self.envTr_time+=1
#trans任务完成更新
if task_finish and self.topology[node_send_id,node_rec_id]==1 :
#更新包与节点
# T-T清除
self.trans_task_ID_inTR.remove(trans_temp_id)
# 包属性清除
self.packets_list[packet_id].in_TR=0
self.packets_list[packet_id].cur_trans_task_id=0
self.packets_list[packet_id].cur_node_id=node_rec_id
# 发送节点属性清除
self.node_list[node_send_id].packets_ToSend_id.remove(packet_id)
self.node_list[node_send_id].trans_task_send.get()
self.node_list[node_send_id].sending_flag=0
self.node_list[node_send_id].current_amp_send=0
self.node_list[node_send_id].current_power_send=0
# 接收节点属性清除
self.node_list[node_rec_id].trans_taskID_rec.remove(trans_temp_id)
if len(self.node_list[node_rec_id].trans_taskID_rec)==0:
self.node_list[node_rec_id].rec_flag=0
# self.node_list[node_rec_id].current_amp_receive=0
self.node_list[node_rec_id].current_power_receive=0
# 频谱环境更新(频谱块release)
freqB_ID_now=0
for freqB_ocp_now in self.trans_task_list[trans_temp_id].FreqB_occup:
if freqB_ocp_now and node_send_id!=node_rec_id:
self.freqB_list[freqB_ID_now].remove(node_send_id)
freqB_ID_now+=1
#判断是否到达目的地
if self.packets_list[packet_id].cur_node_id==self.packets_list[packet_id].dst_node_id and self.topology[node_send_id,node_rec_id]==1:
# 可通信到达
self.packets_list[packet_id].arrive_flag=1
self.packets_live_id.remove(packet_id)
### 记录接受节点和发出节点的奖励 ###
self.packet_arrive_success[self.packets_list[packet_id].ori_node_id]+=1
self.agent_arrive[node_send_id]+=1
# self.arrive_time += self.trans_task_list[trans_temp_id].time_use # datacheck3
self.arrive_success += 1
elif self.topology[node_send_id,node_rec_id]==1 :
#可通信没到达
self.node_list[node_rec_id].packets_ToSend_id.append(packet_id)
# self.arrive_time += (cur_time - self.packets_list[packet_id].time_start) # datacheck3
else:
#不可通信
self.trans_task_list[trans_temp_id].time_cnt=0
self.trans_task_list[trans_temp_id].finish_flag=0
# for packet_id in self.packets_live_id:
# #判断是否到达目的地
# if self.packets_list[packet_id].cur_node_id==self.packets_list[packet_id].dst_node_id or self.packets_list[packet_id].arrive_flag==1:
# #到达
# continue
# # self.arrive_time += self.trans_task_list[trans_temp_id].time_use
# else:#没到达
# self.arrive_time += 1
self.arrive_time += len(self.packets_live_id)
def all_agent_observe(self):
all_ob=[]
# fBlst=[0,0,0,0,0,0,0,0,0,0]
degree=0
pack_storage=0
pw_avg_all=0
dst_node=-1
# for node_id in range(self.node_max):
# if len (self.node_list[node_id].packets_ToSend_id):
# packet_toSend_id=self.node_list[node_id].packets_ToSend_id[0]
# dst_node=self.packets_list[packet_toSend_id].dst_node_id
# else:
# dst_node=-1
# for node_id in self.live_node_ID_list:
# for node_id in range(self.node_max):
# fb_tp_id=0
# for fb_tp in self.node_list[node_id].current_freqB:
# fBlst[fb_tp_id]=fb_tp
# fb_tp_id+=1
# for node_id in self.live_node_ID_list:
#neibor_idlist=self.node_list[node_id].neibor_idlist[:]#深复制
#receive ob?
#neibor_idlist.append(node_id)
#neibor_vector=[]
#for i in neibor_idlist:
# for node_id in range(self.node_max):
# pwl=self.node_list[node_id].power_list
# if len(pwl)>=BACKTIME:
# pwlst=pwl[len(pwl)-BACKTIME:len(pwl)]
# else:
# pwlst=pwl
# if len(pwlst)>0:
# pw_avg=sum(pwlst)/len(pwlst)
# else:
# pw_avg=0
# pw_avg_all+=pw_avg
for node_id in range(self.node_max):
pwl=self.node_list[node_id].power_list
if len(pwl)>=BACKTIME:
pwlst=pwl[len(pwl)-BACKTIME:len(pwl)]
else:
pwlst=pwl
if len(pwlst)>0:
pw_avg=sum(pwlst)/len(pwlst)
else:
pw_avg=0
if len (self.node_list[node_id].packets_ToSend_id)>0:
packet_toSend_id=self.node_list[node_id].packets_ToSend_id[0]
dst_node=self.packets_list[packet_toSend_id].dst_node_id
else:
dst_node=-1
pw=[]
pw.append(pw_avg)
dgr=[]
degree=len(self.topology_actSpace[node_id][0])-1
dgr.append(degree)
pcs=[]
pack_storage=len(self.node_list[node_id].packets_ToSend_id)
pcs.append(pack_storage)
dn=[]
dn.append(dst_node)
all_ob.append(pw+dgr+pcs+dn)
#self.node_list[node_id].ob_send=neibor_vector
return np.array(all_ob)
# def generate_trans_task(self,trans_id,send_node,rec_node,packet):
# trans_task_temp=Trans_task(trans_id,send_node,rec_node,packet)
# return trans_task_temp
def env_check_right(self):
for node_id in self.live_node_ID_list:
if self.node_list[node_id].trans_task_send.empty():
assert self.node_list[node_id].sending_flag == 0
elif not self.node_list[node_id].trans_task_send.empty():
assert self.node_list[node_id].sending_flag == 1
st_temp=self.node_list[node_id].trans_task_send.get()
self.node_list[node_id].trans_task_send.put(st_temp)#无损使用队列内容
s_node_send_id,s_node_rec_id,s_packet_id=st_temp.show_info()
assert node_id==s_node_send_id
# assert self.node_list[node_id].next_hop_id==s_node_rec_id
assert self.node_list[node_id].packets_ToSend_id[0]==s_packet_id
elif self.node_list[node_id].trans_task_rec.empty():
assert self.rec_flag == 0
elif not self.node_list[node_id].trans_task_rec.empty():
assert self.node_list[node_id].rec_flag == 1
rt_temp=self.node_list[node_id].trans_task_rec.get()
self.node_list[node_id].trans_task_rec.put(rt_temp)#无损使用队列内容
r_node_send_id,r_node_rec_id,r_packet_id=rt_temp.show_info()
assert node_id==r_node_rec_id
# assert self.node_list[node_id].next_hop_id==s_node_rec_id
assert self.node_list[node_id].packets_ToSend_id[0] != r_packet_id
return 0
def topology_update(self,cur_time,rand_change):
self.topology = np.zeros((NODE_MAX,NODE_MAX))
################--------随机更改拓扑结构--------################
if rand_change:
positions=next(self.geo_area)
self.position = positions
for a in range(NODE_MAX):
for b in range(NODE_MAX):
if np.linalg.norm(positions[a]-positions[b]) <= COM_RANGE:
self.topology[a,b]=1
self.topology[b,a]=1
else:
self.topology[a,b]=0
self.topology[b,a]=0
# if np.random.rand()<DELTA and cur_time%30==0:
# for i in np.random.randint(0,self.node_max,np.random.randint(3)+1):
# self.topology[i,:]=np.random.randint(0,2,self.node_max)
# self.topology[i,i] = 1
# for j in range(self.node_max):
# #构建双向图
# if self.topology[i,j] == 1:
# self.topology[j,i] = 1
# print(positions)
# print("****************")
# print(self.topology)
# print("------------------------------------")
################--------更新邻域--------################
self.live_node_ID_list=[]
self.topology_actSpace=[]
for i in range(self.topology.shape[0]):
if any(self.topology[i,:]):
TPtemp = np.nonzero(self.topology[i,:])
# self.node_list[i].neibor_idlist=TPtemp
self.topology_actSpace.append(TPtemp)
self.live_node_ID_list.append(i)
else:
TPtemp = -1
self.topology_actSpace.append(TPtemp)
return self.topology
def get_state_reward(self):
return self.topology,self.all_ob,self.reward
def time_step(self,cur_time,action):
self.packet_arrive_success=[]
self.agent_arrive=[]
for i in range(NODE_MAX):
self.packet_arrive_success.append(0)
self.agent_arrive.append(0)
self.arrive_success=0
# self.env_check_right()
topology_now=self.topology_update(cur_time,1)
self.generate_packet(cur_time)
self.all_ob=self.all_agent_observe()
self.trans_task_update(cur_time)
for node_index in self.live_node_ID_list :
if len(self.node_list[node_index].packets_ToSend_id)>0 and self.node_list[node_index].sending_flag!=1:
packet_toSend_id=self.node_list[node_index].packets_ToSend_id[0]
#包未到达且非在传----->生成trans_task
if self.packets_list[packet_toSend_id].arrive_flag==0 and self.packets_list[packet_toSend_id].in_TR==0:
#传输和接收节点决策
send_node=self.node_list[node_index]
Action=action[node_index]#######################################################
next_hop_id,current_freqB,current_amp_send=Action[0],Action[1:N_ACTION_C],Action[N_ACTION_C]
send_node.next_hop_id=next_hop_id
rec_node=self.node_list[next_hop_id]
current_amp_rec=RECAMP
self.node_list[node_index].current_freqB=current_freqB
self.node_list[node_index].next_hop_id=next_hop_id
self.node_list[node_index].current_amp_send=current_amp_send
#频谱环境更新
freqB_ID_now=0
for fB_ocp in current_freqB:
if node_index!=next_hop_id and fB_ocp:
self.freqB_list[freqB_ID_now].append(node_index)
self.freqB_use_history[freqB_ID_now].append(node_index)
freqB_ID_now+=1
#T-T生成与T-T环境更新 | trans_task_now=Trans_task(self.trans_task_cnt,send_node,rec_node,self.packets_list[packet_toSend_id]) | 3 | 2023-12-30 09:35:30+00:00 | 8k |
davidsvy/fractal_video | src/transform/compose.py | [
{
"identifier": "Transform_Camera",
"path": "src/transform/camera.py",
"snippet": "class Transform_Camera(nn.Module):\n\n def __init__(self, prob_shift, prob_zoom, prob_shake, n_steps):\n super(Transform_Camera, self).__init__()\n assert 0 <= prob_shift <= 1\n assert 0 <= prob_zo... | import pytorchvideo.transforms as Tv
import torch
import torch.nn as nn
import torchvision.transforms as T
from src.transform.camera import Transform_Camera
from src.transform.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from src.transform.spatial import Crop_Center, Random_Perspective | 3,969 |
def transform_inner_train(crop_size=112, min_scale=0.5, interp='bicubic'):
crop_tr = Tv.RandomResizedCrop(
target_height=crop_size,
target_width=crop_size,
scale=(min_scale, 1),
aspect_ratio=(3.0 / 4.0, 4.0 / 3.0),
interpolation=interp,
)
transform = T.Compose([
Tv.ConvertUint8ToFloat(),
crop_tr,
])
return transform
def transform_inner_val(crop_size=112, resize=True, interp='bicubic', crop_inc=True):
return T.Compose([
Tv.ConvertUint8ToFloat(),
Crop_Center(
crop_size=crop_size,
interpolation=interp,
resize=resize,
crop_inc=crop_inc,
),
Tv.Normalize(
mean=IMAGENET_DEFAULT_MEAN,
|
def transform_inner_train(crop_size=112, min_scale=0.5, interp='bicubic'):
crop_tr = Tv.RandomResizedCrop(
target_height=crop_size,
target_width=crop_size,
scale=(min_scale, 1),
aspect_ratio=(3.0 / 4.0, 4.0 / 3.0),
interpolation=interp,
)
transform = T.Compose([
Tv.ConvertUint8ToFloat(),
crop_tr,
])
return transform
def transform_inner_val(crop_size=112, resize=True, interp='bicubic', crop_inc=True):
return T.Compose([
Tv.ConvertUint8ToFloat(),
Crop_Center(
crop_size=crop_size,
interpolation=interp,
resize=resize,
crop_inc=crop_inc,
),
Tv.Normalize(
mean=IMAGENET_DEFAULT_MEAN, | std=IMAGENET_DEFAULT_STD, | 2 | 2023-12-27 19:43:45+00:00 | 8k |
Simuoss/THE-TTF2HEX_Extractor | extractor.py | [
{
"identifier": "char_in_font",
"path": "in_font.py",
"snippet": "def char_in_font(char: str, cfont: TTFont) -> bool:\n \"\"\"判断字符是否在字体里\n\n Args:\n char (str): 单字符文本\n fontfile (str): 字体文件\n\n Returns:\n bool: 是否在字体里\n ... | from PySide6.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, \
QFileDialog, QCheckBox, QLineEdit, QSpinBox, QComboBox, QProgressBar, QTextEdit
from PySide6.QtGui import QImage, QPixmap
from PySide6.QtCore import Qt
from PIL import Image, ImageFont, ImageDraw
from fontTools.ttLib import TTFont
from in_font import char_in_font
from woker import Worker | 4,464 | if not preview_text.isprintable():
self.update_main_progress(0, "这个字符显示不出呢")
return
# 如果整个preview_text存在字符不在字体里,则不显示
if not all(char_in_font(c, TTFont(font_path)) for c in preview_text):
self.update_main_progress(0, "字体里没有这个字呢")
return
# 创建一个空白画布来绘制字符
canvas = Image.new("1", (canvas_size_width, canvas_size_height), reverse_color)
# 使用PIL加载字体文件
font = ImageFont.truetype(font_path, size=font_size)
draw = ImageDraw.Draw(canvas)
# 清空图像内容(不一定是8*8)
draw.rectangle([0, 0, canvas_size_width, canvas_size_height], fill=reverse_color)#参数为左上角和右下角的坐标
# 在图像上绘制字符
draw.text((offset_x,offset_y), preview_text, font=font, fill= not reverse_color)
# 上下翻转
if flip:
canvas = canvas.transpose(Image.FLIP_TOP_BOTTOM)
# 左右翻转
if mirror:
canvas = canvas.transpose(Image.FLIP_LEFT_RIGHT)
# 顺时针旋转
if rotate == "90°":
canvas = canvas.transpose(Image.ROTATE_270)# 逆时针旋转270°,即顺时针旋转90°
elif rotate == "180°":
canvas = canvas.transpose(Image.ROTATE_180)
elif rotate == "270°":
canvas = canvas.transpose(Image.ROTATE_90)
# 获取字符的点阵表示
pixels = list(canvas.getdata())
bitmap = [pixels[i:i+canvas_size_width] for i in range(0, len(pixels), canvas_size_width)]
# 将点阵转换为硬缩放不大于400*400的图像
zoom = 300 // canvas_size_width
canvas = Image.new("1", (canvas_size_width*zoom, canvas_size_height*zoom))
draw = ImageDraw.Draw(canvas)
for y in range(canvas_size_height):
for x in range(canvas_size_width):
if bitmap[y][x]:
draw.rectangle([x*zoom, y*zoom, (x+1)*zoom, (y+1)*zoom], fill=0)
else:
draw.rectangle([x*zoom, y*zoom, (x+1)*zoom, (y+1)*zoom], fill=1)
# 在将 PIL.Image 转换为 QImage 对象时,需要将其模式转换为 RGB888 或 ARGB32
canvas = canvas.convert("RGB")
# 将 PIL.Image 转换为 QImage 对象
qimage = QImage(canvas.tobytes(), canvas.width, canvas.height, QImage.Format_RGB888)
# 然后再将 QImage 对象传递给 QPixmap.fromImage 方法
self.preview_image_label.setPixmap(QPixmap.fromImage(qimage))
def extract_font(self):
font_path = self.file_path_textbox.text()
font_size = self.font_size_spinbox.value()
canvas_size_width = self.canvas_size_width_spinbox.value()
canvas_size_height = self.canvas_size_height_spinbox.value()
offset_x = self.offset_x_spinbox.value()
offset_y = self.offset_y_spinbox.value()
flip = self.flip_checkbox.isChecked()
mirror = self.mirror_checkbox.isChecked()
rotate = self.rotate_combobox.currentText()
reverse_color = self.invert_checkbox.isChecked()
input_text = self.extract_from_text_input.toPlainText()
if not font_path:
self.update_main_progress(0, "还没选字体呢")
return
# 如果没选中任何提取范围,则默认提取 ASCII 可见字符集
if not self.ascii_checkbox.isChecked() and not self.chinese_checkbox.isChecked() \
and not self.common_chinese_checkbox.isChecked() and not self.chinese_punctuation_checkbox.isChecked() \
and not self.custom_range_checkbox.isChecked() and not self.extract_from_text_checkbox.isChecked():
self.ascii_checkbox.setChecked(True)
# 如果选择了自选区域,则检查输入是否合法
if self.custom_range_checkbox.isChecked() and not self.select_all_checkbox.isChecked():
range_from = self.range_from_input.text()
range_to = self.range_to_input.text()
if not range_from or not range_to:
self.update_main_progress(0,"自选区域想选什么呢?")
return
if not range_from.startswith("0x") or not range_to.startswith("0x"):
self.update_main_progress(0,"自选区域要0x开头哦")
return
range_from = int(range_from, 16)
range_to = int(range_to, 16)
if range_from > range_to:
self.update_main_progress(0,"自选区域要从小到大哦")
return
# 确定提取范围
extract_range = ""
if self.extract_from_text_checkbox.isChecked():# 从文本提取
extract_range = input_text
elif self.select_all_checkbox.isChecked():# 全选
extract_range = [chr(i) for i in range(0x0000, 0xFFFF + 1)]
else:
if self.ascii_checkbox.isChecked():# ASCII 可见字符集
extract_range += "".join([chr(i) for i in range(0x0020, 0x007E + 1)])
if self.chinese_checkbox.isChecked():# 所有汉字
extract_range += "".join([chr(i) for i in range(0x4E00, 0x9FFF + 1)])
if self.common_chinese_checkbox.isChecked():# 常用汉字
extract_range += "".join([chr(i) for i in range(0x4E00, 0x9FA5 + 1)])
if self.chinese_punctuation_checkbox.isChecked():# 汉字标点符号
extract_range += "".join([chr(i) for i in range(0x3000, 0x303F + 1)])
if self.custom_range_checkbox.isChecked():# 自选区域
extract_range += "".join([chr(i) for i in range(range_from, range_to + 1)])
#print(f"提取范围:{extract_range}")
# 创建 Worker 对象
|
class FontExtractorApp(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("TTF2HEX 字体字库转换器 --- By 司沐_Simuoss @ https://github.com/Simuoss")
# 主窗口包含一个水平布局
main_layout = QHBoxLayout()
left_layout = QVBoxLayout()
right_layout = QVBoxLayout()
self.setupLeftWidgets(left_layout)
self.setupRightWidgets(right_layout)
main_layout.addLayout(left_layout)
main_layout.addLayout(right_layout)
central_widget = QWidget()
central_widget.setLayout(main_layout)
self.setCentralWidget(central_widget)
def setupLeftWidgets(self, layout):
self.setupFileSelection(layout)
self.setupCanvasFontInputs(layout)
self.setupCharacterOffsetInputs(layout)
self.setupFlipMirrorCheckboxes(layout)
self.setupRotateInvertOptions(layout)
self.setupExtractFontOptions(layout)
def setupRightWidgets(self, layout):
self.setupMintArea(layout)
self.setupPreviewArea(layout)
self.setupExtractArea(layout)
# 下面是拆分出来的小功能块
def setupFileSelection(self, layout):
# 创建选择文件相关部件和布局
# 创建一个水平布局以容纳文件选择按钮和文件路径文本框
file_layout = QHBoxLayout()
# 添加标题和选择文件标签
title_label = QLabel("选择字体文件:")
file_layout.addWidget(title_label)
# 创建一个不可编辑的文本框用于显示文件路径
self.file_path_textbox = QLineEdit()
self.file_path_textbox.setReadOnly(True)
file_layout.addWidget(self.file_path_textbox)
# 创建一个按钮用于选择文件
select_file_button = QPushButton("选择文件")
select_file_button.clicked.connect(self.select_font_file)
file_layout.addWidget(select_file_button)
# 将文件选择部件添加到主布局中
layout.addLayout(file_layout)
def setupCanvasFontInputs(self, layout):
# 创建画布大小、字体大小输入相关部件和布局
# 添加画布大小、字体大小输入
canvas_font_layout = QHBoxLayout()
canvas_label = QLabel("画布大小(宽:高):")
canvas_font_layout.addWidget(canvas_label)
self.canvas_size_width_spinbox = QSpinBox()
self.canvas_size_width_spinbox.setMinimum(1)
self.canvas_size_width_spinbox.setValue(12) # 默认值为8
canvas_font_layout.addWidget(self.canvas_size_width_spinbox)
self.canvas_size_height_spinbox = QSpinBox()
self.canvas_size_height_spinbox.setMinimum(1)
self.canvas_size_height_spinbox.setValue(12)
canvas_font_layout.addWidget(self.canvas_size_height_spinbox)
font_label = QLabel("字体大小:")
canvas_font_layout.addWidget(font_label)
self.font_size_spinbox = QSpinBox()
self.font_size_spinbox.setMinimum(1)
self.font_size_spinbox.setValue(12) # 默认值为8
canvas_font_layout.addWidget(self.font_size_spinbox)
layout.addLayout(canvas_font_layout)
def setupCharacterOffsetInputs(self, layout):
# 创建字符偏移量输入相关部件和布局
# 添加字符偏移量输入框及方向提示标签
offset_layout = QHBoxLayout()
offset_label = QLabel("字符偏移量(可为负):")
offset_layout.addWidget(offset_label)
self.offset_x_spinbox = QSpinBox()
self.offset_x_spinbox.setMinimum(-10)
self.offset_x_spinbox.setMaximum(10)
offset_layout.addWidget(self.offset_x_spinbox)
self.offset_x_direction_label = QLabel("向右→ ")
offset_layout.addWidget(self.offset_x_direction_label)
self.offset_y_spinbox = QSpinBox()
self.offset_y_spinbox.setMinimum(-10)
self.offset_y_spinbox.setMaximum(10)
offset_layout.addWidget(self.offset_y_spinbox)
self.offset_y_direction_label = QLabel("↓向下")
offset_layout.addWidget(self.offset_y_direction_label)
layout.addLayout(offset_layout)
def setupFlipMirrorCheckboxes(self, layout):
# 创建上下翻转和左右翻转复选框相关部件和布局
# 添加上下翻转和左右翻转复选框
flip_mirror_layout = QHBoxLayout()
flip_label = QLabel("上下翻转:")
flip_mirror_layout.addWidget(flip_label)
self.flip_checkbox = QCheckBox()
flip_mirror_layout.addWidget(self.flip_checkbox)
mirror_label = QLabel("左右翻转:")
flip_mirror_layout.addWidget(mirror_label)
self.mirror_checkbox = QCheckBox()
flip_mirror_layout.addWidget(self.mirror_checkbox)
layout.addLayout(flip_mirror_layout)
def setupRotateInvertOptions(self, layout):
# 创建旋转角度和反色选项相关部件和布局
# 并排添加旋转角度和反色选项
rotate_and_invert_layout = QHBoxLayout()
# 添加旋转角度选项
rotate_layout = QHBoxLayout()
rotate_label = QLabel("顺时针旋转角度:")
rotate_layout.addWidget(rotate_label)
self.rotate_combobox = QComboBox()
self.rotate_combobox.addItem("0°")
self.rotate_combobox.addItem("90°")
self.rotate_combobox.addItem("180°")
self.rotate_combobox.addItem("270°")
rotate_layout.addWidget(self.rotate_combobox)
rotate_and_invert_layout.addLayout(rotate_layout)
# 添加反色选项
invert_label = QLabel(" 反色:")
rotate_and_invert_layout.addWidget(invert_label)
self.invert_checkbox = QCheckBox()
rotate_and_invert_layout.addWidget(self.invert_checkbox)
layout.addLayout(rotate_and_invert_layout)
def setupExtractFontOptions(self, layout):
# 创建提取字体选项相关部件和布局
# 添加提取字体选项
# 创建布局
extract_range_layout = QVBoxLayout()
self.extract_font_label = QLabel("选择提取字体范围:")
extract_range_layout.addWidget(self.extract_font_label)
# 创建全选复选框
self.select_all_checkbox = QCheckBox("所有字体(很大,慎用)")
self.select_all_checkbox.stateChanged.connect(self.toggle_select_all)
extract_range_layout.addWidget(self.select_all_checkbox)
# 创建其他提取范围复选框
self.ascii_checkbox = QCheckBox("ASCII可见字符集(0x0020, 0x007E)")
self.chinese_checkbox = QCheckBox("所有汉字(0x4E00, 0x9FFF)")
self.common_chinese_checkbox = QCheckBox("常用汉字(0x4E00, 0x9FA5)")
self.chinese_punctuation_checkbox = QCheckBox("汉字标点符号(0x3000, 0x303F)")
extract_range_layout.addWidget(self.ascii_checkbox)
extract_range_layout.addWidget(self.chinese_checkbox)
extract_range_layout.addWidget(self.common_chinese_checkbox)
extract_range_layout.addWidget(self.chinese_punctuation_checkbox)
# 创建自选区域复选框
self.custom_range_checkbox = QCheckBox("自选区域")
self.custom_range_checkbox.stateChanged.connect(self.toggle_custom_range)
extract_range_layout.addWidget(self.custom_range_checkbox)
# 创建水平布局用于放置自选区域输入框
custom_range_layout = QHBoxLayout()
# 创建自选区域输入框
self.range_from_input = QLineEdit()
self.range_from_input.setPlaceholderText("开始(0x0000)")
self.range_to_input = QLineEdit()
self.range_to_input.setPlaceholderText("结束(0xFFFF)")
self.range_from_input.setEnabled(False)
self.range_to_input.setEnabled(False)
custom_range_layout.addWidget(self.range_from_input)
custom_range_layout.addWidget(self.range_to_input)
extract_range_layout.addLayout(custom_range_layout)
# 创建从文本复选框,后面跟一个文本框
self.extract_from_text_checkbox = QCheckBox("从文本提取(一般用这个)")
self.extract_from_text_checkbox.stateChanged.connect(self.toggle_extract_from_text)
extract_range_layout.addWidget(self.extract_from_text_checkbox)
self.extract_from_text_input = QTextEdit()
self.extract_from_text_input.setPlaceholderText("输入要提取的字符")
self.extract_from_text_input.setEnabled(False)
extract_range_layout.addWidget(self.extract_from_text_input)
layout.addLayout(extract_range_layout)
# 标志变量来控制复选框状态
self.custom_range_enabled = False
def setupMintArea(self, layout):
# 预览区域标题
preview_label = QLabel("预览区域:")
layout.addWidget(preview_label)
# 提示标签
preview_tip_label1 = QLabel("有些字体标的是12px,但实际上调到15px才是正常的12px状态,需要多微调参数试试")
layout.addWidget(preview_tip_label1)
preview_tip_label2 = QLabel("有些屏幕显示点阵是旋转过的,比如1306的oled屏就需要上下翻转+旋转90°才是正的")
layout.addWidget(preview_tip_label2)
def setupPreviewArea(self, layout):
# 创建预览图像展示框
self.preview_image_label = QLabel()
self.preview_image_label.setAlignment(Qt.AlignCenter)
self.preview_image_label.setFixedSize(400, 400)
self.preview_image_label.setStyleSheet("border: 1px solid black;")
layout.addWidget(self.preview_image_label)
# 创建预览操作区域
preview_options_layout = QHBoxLayout()
# 创建预览字符输入框
self.preview_input = QLineEdit()
self.preview_input.setPlaceholderText("输入字符或 Unicode 编码")
# 默认是A
self.preview_input.setText("A")
preview_options_layout.addWidget(self.preview_input)
# 创建预览按钮
preview_button = QPushButton("预览")
preview_button.clicked.connect(self.preview_font)
preview_options_layout.addWidget(preview_button)
layout.addLayout(preview_options_layout)
def setupExtractArea(self, layout):
# 创建提取字体按钮
extract_button = QPushButton("提取字体")
extract_button.clicked.connect(self.extract_font)
layout.addWidget(extract_button)
# 创建主任务的进度条
self.main_progress_bar = QProgressBar()
self.main_progress_bar.setRange(0, 100)
self.main_progress_bar.setValue(0)
self.main_progress_bar.setFormat("等待开始")
layout.addWidget(self.main_progress_bar)
def update_main_progress(self, progress, text):
self.main_progress_bar.setValue(progress)
self.main_progress_bar.setFormat(text)
def select_font_file(self):
options = QFileDialog.Options()
file_dialog = QFileDialog()
file_path, _ = file_dialog.getOpenFileName(self, "选择字体文件", "", "TrueType 字体文件 (*.ttf)", options=options)
if file_path:
self.file_path_textbox.setText(file_path)
#print(f"已选择字体文件:{file_path}")
def toggle_extract_from_text(self, state):
# 如果选中了从文本提取,则禁用其他提取范围复选框
if state:
self.select_all_checkbox.setChecked(False)
self.select_all_checkbox.setEnabled(False)
self.ascii_checkbox.setChecked(False)
self.ascii_checkbox.setEnabled(False)
self.chinese_checkbox.setChecked(False)
self.chinese_checkbox.setEnabled(False)
self.common_chinese_checkbox.setChecked(False)
self.common_chinese_checkbox.setEnabled(False)
self.chinese_punctuation_checkbox.setChecked(False)
self.chinese_punctuation_checkbox.setEnabled(False)
self.custom_range_checkbox.setChecked(False)
self.custom_range_checkbox.setEnabled(False)
self.extract_from_text_input.setEnabled(True)
else:
self.select_all_checkbox.setEnabled(True)
self.ascii_checkbox.setEnabled(True)
self.chinese_checkbox.setEnabled(True)
self.common_chinese_checkbox.setEnabled(True)
self.chinese_punctuation_checkbox.setEnabled(True)
self.custom_range_checkbox.setEnabled(True)
self.extract_from_text_input.setEnabled(False)
def toggle_select_all(self, state):
self.ascii_checkbox.setChecked(state)
self.ascii_checkbox.setEnabled(not state)
self.chinese_checkbox.setChecked(state)
self.chinese_checkbox.setEnabled(not state)
self.common_chinese_checkbox.setChecked(state)
self.common_chinese_checkbox.setEnabled(not state)
self.chinese_punctuation_checkbox.setChecked(state)
self.chinese_punctuation_checkbox.setEnabled(not state)
self.custom_range_checkbox.setChecked(state)
self.custom_range_checkbox.setEnabled(not state)
self.extract_from_text_checkbox.setChecked(False)
self.extract_from_text_checkbox.setEnabled(not state)
self.toggle_custom_range(state)
# 切换自选区域输入框的状态
def toggle_custom_range(self, state):
if not self.custom_range_enabled:
self.range_from_input.setEnabled(True)
self.range_to_input.setEnabled(True)
self.custom_range_enabled = True
else:
self.range_from_input.setEnabled(False)
self.range_to_input.setEnabled(False)
self.custom_range_enabled = False
def preview_font(self):
font_path = self.file_path_textbox.text()
font_size = self.font_size_spinbox.value()
canvas_size_width = self.canvas_size_width_spinbox.value()
canvas_size_height = self.canvas_size_height_spinbox.value()
offset_x = self.offset_x_spinbox.value()
offset_y = self.offset_y_spinbox.value()
flip = self.flip_checkbox.isChecked()
mirror = self.mirror_checkbox.isChecked()
rotate = self.rotate_combobox.currentText()
preview_text = self.preview_input.text()
reverse_color = self.invert_checkbox.isChecked()
if not font_path:
self.update_main_progress(0, "还没选字体呢")
return
if not preview_text:
self.update_main_progress(0, "还没输入预览字符呢")
return
if not preview_text.isprintable():
self.update_main_progress(0, "这个字符显示不出呢")
return
# 如果整个preview_text存在字符不在字体里,则不显示
if not all(char_in_font(c, TTFont(font_path)) for c in preview_text):
self.update_main_progress(0, "字体里没有这个字呢")
return
# 创建一个空白画布来绘制字符
canvas = Image.new("1", (canvas_size_width, canvas_size_height), reverse_color)
# 使用PIL加载字体文件
font = ImageFont.truetype(font_path, size=font_size)
draw = ImageDraw.Draw(canvas)
# 清空图像内容(不一定是8*8)
draw.rectangle([0, 0, canvas_size_width, canvas_size_height], fill=reverse_color)#参数为左上角和右下角的坐标
# 在图像上绘制字符
draw.text((offset_x,offset_y), preview_text, font=font, fill= not reverse_color)
# 上下翻转
if flip:
canvas = canvas.transpose(Image.FLIP_TOP_BOTTOM)
# 左右翻转
if mirror:
canvas = canvas.transpose(Image.FLIP_LEFT_RIGHT)
# 顺时针旋转
if rotate == "90°":
canvas = canvas.transpose(Image.ROTATE_270)# 逆时针旋转270°,即顺时针旋转90°
elif rotate == "180°":
canvas = canvas.transpose(Image.ROTATE_180)
elif rotate == "270°":
canvas = canvas.transpose(Image.ROTATE_90)
# 获取字符的点阵表示
pixels = list(canvas.getdata())
bitmap = [pixels[i:i+canvas_size_width] for i in range(0, len(pixels), canvas_size_width)]
# 将点阵转换为硬缩放不大于400*400的图像
zoom = 300 // canvas_size_width
canvas = Image.new("1", (canvas_size_width*zoom, canvas_size_height*zoom))
draw = ImageDraw.Draw(canvas)
for y in range(canvas_size_height):
for x in range(canvas_size_width):
if bitmap[y][x]:
draw.rectangle([x*zoom, y*zoom, (x+1)*zoom, (y+1)*zoom], fill=0)
else:
draw.rectangle([x*zoom, y*zoom, (x+1)*zoom, (y+1)*zoom], fill=1)
# 在将 PIL.Image 转换为 QImage 对象时,需要将其模式转换为 RGB888 或 ARGB32
canvas = canvas.convert("RGB")
# 将 PIL.Image 转换为 QImage 对象
qimage = QImage(canvas.tobytes(), canvas.width, canvas.height, QImage.Format_RGB888)
# 然后再将 QImage 对象传递给 QPixmap.fromImage 方法
self.preview_image_label.setPixmap(QPixmap.fromImage(qimage))
def extract_font(self):
font_path = self.file_path_textbox.text()
font_size = self.font_size_spinbox.value()
canvas_size_width = self.canvas_size_width_spinbox.value()
canvas_size_height = self.canvas_size_height_spinbox.value()
offset_x = self.offset_x_spinbox.value()
offset_y = self.offset_y_spinbox.value()
flip = self.flip_checkbox.isChecked()
mirror = self.mirror_checkbox.isChecked()
rotate = self.rotate_combobox.currentText()
reverse_color = self.invert_checkbox.isChecked()
input_text = self.extract_from_text_input.toPlainText()
if not font_path:
self.update_main_progress(0, "还没选字体呢")
return
# 如果没选中任何提取范围,则默认提取 ASCII 可见字符集
if not self.ascii_checkbox.isChecked() and not self.chinese_checkbox.isChecked() \
and not self.common_chinese_checkbox.isChecked() and not self.chinese_punctuation_checkbox.isChecked() \
and not self.custom_range_checkbox.isChecked() and not self.extract_from_text_checkbox.isChecked():
self.ascii_checkbox.setChecked(True)
# 如果选择了自选区域,则检查输入是否合法
if self.custom_range_checkbox.isChecked() and not self.select_all_checkbox.isChecked():
range_from = self.range_from_input.text()
range_to = self.range_to_input.text()
if not range_from or not range_to:
self.update_main_progress(0,"自选区域想选什么呢?")
return
if not range_from.startswith("0x") or not range_to.startswith("0x"):
self.update_main_progress(0,"自选区域要0x开头哦")
return
range_from = int(range_from, 16)
range_to = int(range_to, 16)
if range_from > range_to:
self.update_main_progress(0,"自选区域要从小到大哦")
return
# 确定提取范围
extract_range = ""
if self.extract_from_text_checkbox.isChecked():# 从文本提取
extract_range = input_text
elif self.select_all_checkbox.isChecked():# 全选
extract_range = [chr(i) for i in range(0x0000, 0xFFFF + 1)]
else:
if self.ascii_checkbox.isChecked():# ASCII 可见字符集
extract_range += "".join([chr(i) for i in range(0x0020, 0x007E + 1)])
if self.chinese_checkbox.isChecked():# 所有汉字
extract_range += "".join([chr(i) for i in range(0x4E00, 0x9FFF + 1)])
if self.common_chinese_checkbox.isChecked():# 常用汉字
extract_range += "".join([chr(i) for i in range(0x4E00, 0x9FA5 + 1)])
if self.chinese_punctuation_checkbox.isChecked():# 汉字标点符号
extract_range += "".join([chr(i) for i in range(0x3000, 0x303F + 1)])
if self.custom_range_checkbox.isChecked():# 自选区域
extract_range += "".join([chr(i) for i in range(range_from, range_to + 1)])
#print(f"提取范围:{extract_range}")
# 创建 Worker 对象 | self.worker = Worker(font_path, font_size, canvas_size_width, canvas_size_height, offset_x, offset_y, flip, mirror, rotate, reverse_color, extract_range) | 1 | 2023-12-30 06:38:36+00:00 | 8k |
ysyBrenda/Transformer-For-Geochemical-Anomaly-Detection | train.py | [
{
"identifier": "Transformer",
"path": "transformer/Models.py",
"snippet": "class Transformer(nn.Module):\n ''' A sequence to sequence model with attention mechanism. '''\n\n def __init__(\n self, src_pad_idx, trg_pad_idx,\n d_word_vec=38, d_model=38, d_inner=2048,\n ... | import argparse
import time
import dill as pickle
import numpy as np
import random
import os
import torch
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as Data
from tqdm import tqdm
from transformer.Models import Transformer
from transformer.Optim import ScheduledOptim
from tensorboardX import SummaryWriter | 3,887 | torch.save(checkpoint, os.path.join(opt.output_dir, opt.fileHead, model_name))
print(' - [Info] The checkpoint file has been updated.')
with open(log_train_file, 'a') as log_tf, open(log_valid_file, 'a') as log_vf:
log_tf.write('{epoch},{loss: 8.5f},{lr:8.2e}\n'.format(
epoch=epoch_i, loss=train_loss, lr=lr))
log_vf.write('{epoch},{loss: 8.5f},{lr:8.2e}\n'.format(
epoch=epoch_i, loss=valid_loss, lr=lr))
if opt.use_tb:
tb_writer.add_scalars('loss', {'train': train_loss, 'val': valid_loss}, epoch_i)
tb_writer.add_scalar('learning_rate', lr, epoch_i)
# auto break
if valid_loss < best:
best = valid_loss
bad_counter = 0
else:
bad_counter += 1
if bad_counter == patience:
break
log_opt_file = 'opt_file_log.log' # add
with open(log_opt_file, 'a') as log_f:
log_f.write(str(opt.fileHead) + '__loss__{:8.5f}\n'.format(valid_loss))
def main():
'''
Usage:
python train.py
-data_pkl ./data/pre_data.pkl -output_dir output -epoch 150 -b 16 -use_tb -save_mode all
'''
parser = argparse.ArgumentParser()
parser.add_argument('-data_pkl', default=None) # all-in-1 data pickle or bpe field
parser.add_argument('-train_path', default=None) # bpe encoded data
parser.add_argument('-val_path', default=None) # bpe encoded data
parser.add_argument('-epoch', type=int, default=10)
parser.add_argument('-b', '--batch_size', type=int, default=2048)
parser.add_argument('-d_model', type=int, default=38) # 38;8 #todo
parser.add_argument('-d_inner_hid', type=int, default=2048) # 64 #todo
parser.add_argument('-d_k', type=int, default=38)
parser.add_argument('-d_v', type=int, default=38)
parser.add_argument('-n_head', type=int, default=2)
parser.add_argument('-n_layers', type=int, default=4) # 6
parser.add_argument('-warmup', '--n_warmup_steps', type=int, default=4000)
parser.add_argument('-lr_mul', type=float, default=2.0) # 2.0
parser.add_argument('-seed', type=int, default=None)
parser.add_argument('-dropout', type=float, default=0.1)
parser.add_argument('-output_dir', type=str, default=None)
parser.add_argument('-use_tb', action='store_true')
parser.add_argument('-save_mode', type=str, choices=['all', 'best'], default='best')
parser.add_argument('-no_cuda', action='store_true')
parser.add_argument('-unmask', type=float, default=0.3)
parser.add_argument('-l2', type=float, default=0.0) # weight_dacay
parser.add_argument('-lambda_con', type=float, default=0.01) # contrast loss lambda
parser.add_argument('-T', type=int, default=1) # the times of mask
parser.add_argument('-isContrastLoss', action='store_true')
parser.add_argument('-isRandMask', action='store_true')
opt = parser.parse_args()
# # ++++++++++++++++
opt.d_k = opt.d_model
opt.d_v = opt.d_model
opt.cuda = not opt.no_cuda
opt.d_word_vec = opt.d_model # 512 ==>38
# ------Output fileHead----
opt.fileHead = 'T' + str(opt.T) + '_unmask' + str(opt.unmask) + '_h' + str(opt.n_head) + 'L' + str(
opt.n_layers) + '_hid' + str(opt.d_inner_hid) + '_d' + str(opt.d_model) + '_b' + str(
opt.batch_size) + '_warm' + str(opt.n_warmup_steps) + '_lrm' + str(opt.lr_mul) + '_seed' + \
str(opt.seed) + '_dr' + str(opt.dropout) +'_isCL'+str(opt.isContrastLoss)+ '_lamb'+str(opt.lambda_con) +'_ismask'+str(opt.isRandMask)
if os.path.exists(os.path.join(opt.output_dir, opt.fileHead)):
print('the output file is rewriting....', opt.fileHead)
else:
os.mkdir(os.path.join(opt.output_dir, opt.fileHead))
print('The output filename is generated: ', opt.fileHead)
# https://pytorch.org/docs/stable/notes/randomness.html
# For reproducibility
if opt.seed is not None:
torch.manual_seed(opt.seed)
torch.backends.cudnn.benchmark = False
# torch.set_deterministic(True)
np.random.seed(opt.seed)
random.seed(opt.seed)
if not opt.output_dir:
print('No experiment result will be saved.')
raise
if not os.path.exists(opt.output_dir):
os.makedirs(opt.output_dir)
if opt.batch_size < 2048 and opt.n_warmup_steps <= 4000:
print('[Warning] The warmup steps may be not enough.\n' \
'(sz_b, warmup) = (2048, 4000) is the official setting.\n' \
'Using smaller batch w/o longer warmup may cause ' \
'the warmup stage ends with only little data trained.')
device = torch.device('cuda' if opt.cuda else 'cpu')
# ========= Loading Dataset =========#
training_data, validation_data = prepare_dataloaders(opt, device)
print("training data size:{}, validation data size:{}".format(training_data.__len__(),validation_data.__len__()))
print(opt)
log_opt_file = os.path.join(opt.output_dir, opt.fileHead, 'opt.log')
with open(log_opt_file, 'w') as log_f:
log_f.write(str(opt))
| '''
This script handles the training process.
author: ysyBrenda
run in env:torch1.3.0
'''
# to use tensorboard,input following in terminal:
# $ tensorboard --logdir=output --port 6006
# if【was already in use】:lsof -i:6006, kill -9 PID
def train_epoch(model, training_data, optimizer, opt, device):
''' Epoch operation in training'''
model.train()
total_loss = 0
iter = 0
desc = ' - (Training) '
for batch in tqdm(training_data, mininterval=2, desc=desc, leave=False): # todo
# prepare data
if opt.isContrastLoss:
temp= batch[0].to(device)
a = torch.chunk(temp, 3, dim=1)
src_seq=torch.cat([a[0],a[1],a[2]],0)
else:
src_seq = batch[0].to(device)
gold = batch[1][:, 2:].unsqueeze(1)
trg_seq, gold = map(lambda x: x.to(device), [batch[1].unsqueeze(1), gold.contiguous().view(-1)]) # transpose、unsqueeze vector
if opt.isContrastLoss:
trg_seq=torch.cat([trg_seq,trg_seq,trg_seq],0)
# forward
optimizer.zero_grad()
pred, *_ = model(src_seq, trg_seq)
# backward and update parameters
if opt.isContrastLoss:
a = torch.chunk(pred, 3, dim=0)
contras_loss = F.l1_loss(a[1].contiguous().view(-1), a[2].contiguous().view(-1), reduction='mean')
loss = F.l1_loss(a[0].contiguous().view(-1), gold, reduction='mean') + opt.lambda_con * contras_loss
else:
loss = F.l1_loss(pred.contiguous().view(-1), gold, reduction='mean') # F.l1_loss,F_mse_loss
loss.backward()
optimizer.step_and_update_lr()
total_loss += loss.item()
iter += 1
print('total_train loss: {:8.5f},iter:{},average_train loss:{:8.5f} '.format(total_loss,iter,total_loss/iter)) #optimizer.n_steps=iter
return total_loss/iter
def eval_epoch(model, validation_data, device, opt):
''' Epoch operation in evaluation '''
model.eval()
total_loss = 0
iter=0
desc = ' - (Validation) '
with torch.no_grad():
for batch in tqdm(validation_data, mininterval=2, desc=desc, leave=False):
if opt.isContrastLoss:
temp = batch[0].to(device)
a = torch.chunk(temp, 3, dim=1)
src_seq = torch.cat([a[0], a[1], a[2]], 0)
else:
src_seq = batch[0].to(device)
gold = batch[1][:, 2:].unsqueeze(1)
trg_seq, gold = map(lambda x: x.to(device), [batch[1].unsqueeze(1), gold.contiguous().view(-1)])
if opt.isContrastLoss:
trg_seq = torch.cat([trg_seq, trg_seq, trg_seq], 0)
# forward
pred, *_ = model(src_seq, trg_seq)
# ============= loss==========================
if opt.isContrastLoss:
a = torch.chunk(pred, 3, dim=0)
contras_loss = F.l1_loss(a[1].contiguous().view(-1), a[2].contiguous().view(-1), reduction='mean')
loss = F.l1_loss(a[0].contiguous().view(-1), gold, reduction='mean') + opt.lambda_con * contras_loss
else:
loss = F.l1_loss(pred.contiguous().view(-1), gold, reduction='mean') # reduction="mean"
total_loss += loss.item()
iter +=1
print('total_val loss:{:8.5f} ,iter:{},average_val loss:{:8.5f}'.format(total_loss,iter,total_loss/iter))
return total_loss/iter
def train(model, training_data, validation_data, optimizer, device, opt):
""" Start training """
# Use tensorboard to plot curves, e.g. loss, learning rate
if opt.use_tb:
print("[Info] Use Tensorboard")
# from torch.utils.tensorboard import SummaryWriter
tb_writer = SummaryWriter(log_dir=os.path.join(opt.output_dir, 'tensorboard' + opt.fileHead))
log_train_file = os.path.join(opt.output_dir, opt.fileHead, 'train.log')
log_valid_file = os.path.join(opt.output_dir, opt.fileHead, 'valid.log')
print('[Info] Training performance will be written to file: {} and {}'.format(log_train_file, log_valid_file))
with open(log_train_file, 'w') as log_tf, open(log_valid_file, 'w') as log_vf:
log_tf.write('epoch,loss,lr\n')
log_vf.write('epoch,loss,lr\n')
def print_performances(header, loss, start_time, lr):
print(' - {header:12} loss: {loss: 8.5f}, lr: {lr: 8.2e}, ' \
'elapse: {elapse:3.3f} min'.format(
header=f"({header})", loss=loss,
elapse=(time.time() - start_time) / 60, lr=lr)) # lr: {lr:8.5f} 8.2e
valid_losses = []
bad_counter = 0
best = 50000
patience = 5 # 5
for epoch_i in range(opt.epoch):
print('[ Epoch', epoch_i, ']')
start = time.time()
train_loss = train_epoch(
model, training_data, optimizer, opt, device) # todo
# Current learning rate
lr = optimizer._optimizer.param_groups[0]['lr']
print_performances('Training', train_loss, start, lr)
# start = time.time()
valid_loss = eval_epoch(model, validation_data, device, opt) # todo
print_performances('Validation', valid_loss, start, lr)
valid_losses += [valid_loss]
checkpoint = {'epoch': epoch_i, 'settings': opt, 'model': model.state_dict()}
if opt.save_mode == 'all':
# if epoch_i % 10 == 9:
model_name = 'model_{epoch:d}_vloss_{vloss:.4f}.chkpt'.format(epoch=epoch_i, vloss=valid_loss)
torch.save(checkpoint, os.path.join(opt.output_dir, opt.fileHead, model_name))
elif opt.save_mode == 'best':
model_name = 'model_best.chkpt'
torch.save(checkpoint, os.path.join(opt.output_dir, opt.fileHead, model_name))
print(' - [Info] The checkpoint file has been updated.')
with open(log_train_file, 'a') as log_tf, open(log_valid_file, 'a') as log_vf:
log_tf.write('{epoch},{loss: 8.5f},{lr:8.2e}\n'.format(
epoch=epoch_i, loss=train_loss, lr=lr))
log_vf.write('{epoch},{loss: 8.5f},{lr:8.2e}\n'.format(
epoch=epoch_i, loss=valid_loss, lr=lr))
if opt.use_tb:
tb_writer.add_scalars('loss', {'train': train_loss, 'val': valid_loss}, epoch_i)
tb_writer.add_scalar('learning_rate', lr, epoch_i)
# auto break
if valid_loss < best:
best = valid_loss
bad_counter = 0
else:
bad_counter += 1
if bad_counter == patience:
break
log_opt_file = 'opt_file_log.log' # add
with open(log_opt_file, 'a') as log_f:
log_f.write(str(opt.fileHead) + '__loss__{:8.5f}\n'.format(valid_loss))
def main():
'''
Usage:
python train.py
-data_pkl ./data/pre_data.pkl -output_dir output -epoch 150 -b 16 -use_tb -save_mode all
'''
parser = argparse.ArgumentParser()
parser.add_argument('-data_pkl', default=None) # all-in-1 data pickle or bpe field
parser.add_argument('-train_path', default=None) # bpe encoded data
parser.add_argument('-val_path', default=None) # bpe encoded data
parser.add_argument('-epoch', type=int, default=10)
parser.add_argument('-b', '--batch_size', type=int, default=2048)
parser.add_argument('-d_model', type=int, default=38) # 38;8 #todo
parser.add_argument('-d_inner_hid', type=int, default=2048) # 64 #todo
parser.add_argument('-d_k', type=int, default=38)
parser.add_argument('-d_v', type=int, default=38)
parser.add_argument('-n_head', type=int, default=2)
parser.add_argument('-n_layers', type=int, default=4) # 6
parser.add_argument('-warmup', '--n_warmup_steps', type=int, default=4000)
parser.add_argument('-lr_mul', type=float, default=2.0) # 2.0
parser.add_argument('-seed', type=int, default=None)
parser.add_argument('-dropout', type=float, default=0.1)
parser.add_argument('-output_dir', type=str, default=None)
parser.add_argument('-use_tb', action='store_true')
parser.add_argument('-save_mode', type=str, choices=['all', 'best'], default='best')
parser.add_argument('-no_cuda', action='store_true')
parser.add_argument('-unmask', type=float, default=0.3)
parser.add_argument('-l2', type=float, default=0.0) # weight_dacay
parser.add_argument('-lambda_con', type=float, default=0.01) # contrast loss lambda
parser.add_argument('-T', type=int, default=1) # the times of mask
parser.add_argument('-isContrastLoss', action='store_true')
parser.add_argument('-isRandMask', action='store_true')
opt = parser.parse_args()
# # ++++++++++++++++
opt.d_k = opt.d_model
opt.d_v = opt.d_model
opt.cuda = not opt.no_cuda
opt.d_word_vec = opt.d_model # 512 ==>38
# ------Output fileHead----
opt.fileHead = 'T' + str(opt.T) + '_unmask' + str(opt.unmask) + '_h' + str(opt.n_head) + 'L' + str(
opt.n_layers) + '_hid' + str(opt.d_inner_hid) + '_d' + str(opt.d_model) + '_b' + str(
opt.batch_size) + '_warm' + str(opt.n_warmup_steps) + '_lrm' + str(opt.lr_mul) + '_seed' + \
str(opt.seed) + '_dr' + str(opt.dropout) +'_isCL'+str(opt.isContrastLoss)+ '_lamb'+str(opt.lambda_con) +'_ismask'+str(opt.isRandMask)
if os.path.exists(os.path.join(opt.output_dir, opt.fileHead)):
print('the output file is rewriting....', opt.fileHead)
else:
os.mkdir(os.path.join(opt.output_dir, opt.fileHead))
print('The output filename is generated: ', opt.fileHead)
# https://pytorch.org/docs/stable/notes/randomness.html
# For reproducibility
if opt.seed is not None:
torch.manual_seed(opt.seed)
torch.backends.cudnn.benchmark = False
# torch.set_deterministic(True)
np.random.seed(opt.seed)
random.seed(opt.seed)
if not opt.output_dir:
print('No experiment result will be saved.')
raise
if not os.path.exists(opt.output_dir):
os.makedirs(opt.output_dir)
if opt.batch_size < 2048 and opt.n_warmup_steps <= 4000:
print('[Warning] The warmup steps may be not enough.\n' \
'(sz_b, warmup) = (2048, 4000) is the official setting.\n' \
'Using smaller batch w/o longer warmup may cause ' \
'the warmup stage ends with only little data trained.')
device = torch.device('cuda' if opt.cuda else 'cpu')
# ========= Loading Dataset =========#
training_data, validation_data = prepare_dataloaders(opt, device)
print("training data size:{}, validation data size:{}".format(training_data.__len__(),validation_data.__len__()))
print(opt)
log_opt_file = os.path.join(opt.output_dir, opt.fileHead, 'opt.log')
with open(log_opt_file, 'w') as log_f:
log_f.write(str(opt))
| transformer = Transformer( | 0 | 2023-12-22 13:22:58+00:00 | 8k |
camenduru/MotionCtrl-hf | lvdm/models/ddpm3d.py | [
{
"identifier": "disabled_train",
"path": "lvdm/basics.py",
"snippet": "def disabled_train(self, mode=True):\n \"\"\"Overwrite model.train with this function to make sure train/eval mode\n does not change anymore.\"\"\"\n return self"
},
{
"identifier": "default",
"path": "lvdm/comm... | import logging
import os
import random
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
from contextlib import contextmanager
from functools import partial
from einops import rearrange, repeat
from tqdm import tqdm
from pytorch_lightning.utilities import rank_zero_only
from torch.optim.lr_scheduler import CosineAnnealingLR, LambdaLR
from torchvision.utils import make_grid
from lvdm.basics import disabled_train
from lvdm.common import default, exists, extract_into_tensor, noise_like
from lvdm.distributions import DiagonalGaussianDistribution, normal_kl
from lvdm.ema import LitEma
from lvdm.models.samplers.ddim import DDIMSampler
from lvdm.models.utils_diffusion import make_beta_schedule
from utils.utils import instantiate_from_config | 6,339 | """
wild mixture of
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
https://github.com/CompVis/taming-transformers
-- merci
"""
mainlogger = logging.getLogger('mainlogger')
__conditioning_keys__ = {'concat': 'c_concat',
'crossattn': 'c_crossattn',
'adm': 'y'}
class DDPM(pl.LightningModule):
# classic DDPM with Gaussian diffusion, in image space
def __init__(self,
unet_config,
timesteps=1000,
beta_schedule="linear",
loss_type="l2",
ckpt_path=None,
ignore_keys=[],
load_only_unet=False,
monitor=None,
use_ema=True,
first_stage_key="image",
image_size=256,
channels=3,
log_every_t=100,
clip_denoised=True,
linear_start=1e-4,
linear_end=2e-2,
cosine_s=8e-3,
given_betas=None,
original_elbo_weight=0.,
v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
l_simple_weight=1.,
conditioning_key=None,
parameterization="eps", # all assuming fixed variance schedules
scheduler_config=None,
use_positional_encodings=False,
learn_logvar=False,
logvar_init=0.,
):
super().__init__()
assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
self.parameterization = parameterization
mainlogger.info(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
self.cond_stage_model = None
self.clip_denoised = clip_denoised
self.log_every_t = log_every_t
self.first_stage_key = first_stage_key
self.channels = channels
self.temporal_length = unet_config.params.temporal_length
self.image_size = image_size # try conv?
if isinstance(self.image_size, int):
self.image_size = [self.image_size, self.image_size]
self.use_positional_encodings = use_positional_encodings
self.model = DiffusionWrapper(unet_config, conditioning_key)
#count_params(self.model, verbose=True)
self.use_ema = use_ema
if self.use_ema:
| """
wild mixture of
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
https://github.com/CompVis/taming-transformers
-- merci
"""
mainlogger = logging.getLogger('mainlogger')
__conditioning_keys__ = {'concat': 'c_concat',
'crossattn': 'c_crossattn',
'adm': 'y'}
class DDPM(pl.LightningModule):
# classic DDPM with Gaussian diffusion, in image space
def __init__(self,
unet_config,
timesteps=1000,
beta_schedule="linear",
loss_type="l2",
ckpt_path=None,
ignore_keys=[],
load_only_unet=False,
monitor=None,
use_ema=True,
first_stage_key="image",
image_size=256,
channels=3,
log_every_t=100,
clip_denoised=True,
linear_start=1e-4,
linear_end=2e-2,
cosine_s=8e-3,
given_betas=None,
original_elbo_weight=0.,
v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
l_simple_weight=1.,
conditioning_key=None,
parameterization="eps", # all assuming fixed variance schedules
scheduler_config=None,
use_positional_encodings=False,
learn_logvar=False,
logvar_init=0.,
):
super().__init__()
assert parameterization in ["eps", "x0"], 'currently only supporting "eps" and "x0"'
self.parameterization = parameterization
mainlogger.info(f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode")
self.cond_stage_model = None
self.clip_denoised = clip_denoised
self.log_every_t = log_every_t
self.first_stage_key = first_stage_key
self.channels = channels
self.temporal_length = unet_config.params.temporal_length
self.image_size = image_size # try conv?
if isinstance(self.image_size, int):
self.image_size = [self.image_size, self.image_size]
self.use_positional_encodings = use_positional_encodings
self.model = DiffusionWrapper(unet_config, conditioning_key)
#count_params(self.model, verbose=True)
self.use_ema = use_ema
if self.use_ema: | self.model_ema = LitEma(self.model) | 7 | 2023-12-27 19:32:03+00:00 | 8k |
bitstuffing/pychat | tests/pychat.py | [
{
"identifier": "OpenChat",
"path": "core/openchat.py",
"snippet": "class OpenChat(Browser):\n\n main_origin = \"https://openchat.team\"\n main_referer = \"https://openchat.team/es\"\n\n history = {}\n\n def __init__(self):\n super().__init__()\n self.url = \"https://openchat.t... | from core.openchat import OpenChat
from core.bing import Bing
from core.translator import Translator | 6,740 | #from core.watson import Watson
#def test_library_function():
realPetitionPromptNew = "¿qué modelo de lenguaje estás utilizando? ¿chatgpt3 o chatgpt4?"
#watson = Watson()
#watson.speech_to_text()
openchat = OpenChat()
openchat.send_message(realPetitionPromptNew, stream=True)
bing = Bing()
#bing.speech_to_text()
bing.init_conversation(realPetitionPromptNew)
| #from core.watson import Watson
#def test_library_function():
realPetitionPromptNew = "¿qué modelo de lenguaje estás utilizando? ¿chatgpt3 o chatgpt4?"
#watson = Watson()
#watson.speech_to_text()
openchat = OpenChat()
openchat.send_message(realPetitionPromptNew, stream=True)
bing = Bing()
#bing.speech_to_text()
bing.init_conversation(realPetitionPromptNew)
| translator = Translator() | 2 | 2023-12-28 19:45:49+00:00 | 8k |
vita-epfl/social-transmotion | train_jrdb.py | [
{
"identifier": "collate_batch",
"path": "dataset_jrdb.py",
"snippet": "def collate_batch(batch):\n joints_list = []\n masks_list = []\n num_people_list = []\n for joints, masks in batch:\n \n joints_list.append(joints)\n masks_list.append(masks)\n num_people_list.append... | import argparse
import numpy as np
import os
import random
import time
import torch
from datetime import datetime
from progress.bar import Bar
from torch.utils.data import DataLoader, ConcatDataset
from torch.utils.tensorboard import SummaryWriter
from dataset_jrdb import collate_batch, batch_process_coords, get_datasets, create_dataset
from model_jrdb import create_model
from utils.utils import create_logger, load_default_config, load_config, AverageMeter
from utils.metrics import MSE_LOSS | 3,774 | for epoch in range(config["TRAIN"]["epochs"]):
start_time = time.time()
dataiter = iter(dataloader_train)
timer = {"DATA": 0, "FORWARD": 0, "BACKWARD": 0}
loss_avg = AverageMeter()
disc_loss_avg = AverageMeter()
disc_acc_avg = AverageMeter()
if config["TRAIN"]["optimizer"] == "adam":
adjust_learning_rate(optimizer, epoch, config)
train_steps = len(dataloader_train)
bar = Bar(f"TRAIN {epoch}/{config['TRAIN']['epochs'] - 1}", fill="#", max=train_steps)
for i in range(train_steps):
model.train()
optimizer.zero_grad()
################################
# Load a batch of data
################################
start = time.time()
try:
joints, masks, padding_mask = next(dataiter)
except StopIteration:
dataiter = iter(dataloader_train)
joints, masks, padding_mask = next(dataiter)
in_joints, in_masks, out_joints, out_masks, padding_mask = batch_process_coords(joints, masks, padding_mask, config, training=True)
padding_mask = padding_mask.to(config["DEVICE"])
timer["DATA"] = time.time() - start
################################
# Forward Pass
################################
start = time.time()
loss, pred_joints = compute_loss(model, config, in_joints, out_joints, in_masks, out_masks, padding_mask, epoch=epoch, mode='train', optimizer=None)
timer["FORWARD"] = time.time() - start
################################
# Backward Pass + Optimization
################################
start = time.time()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), config["TRAIN"]["max_grad_norm"])
optimizer.step()
timer["BACKWARD"] = time.time() - start
################################
# Logging
################################
loss_avg.update(loss.item(), len(joints))
summary = [
f"{str(epoch).zfill(3)} ({i + 1}/{train_steps})",
f"LOSS: {loss_avg.avg:.4f}",
f"T-TOT: {bar.elapsed_td}",
f"T-ETA: {bar.eta_td:}"
]
for key, val in timer.items():
summary.append(f"{key}: {val:.2f}")
bar.suffix = " | ".join(summary)
bar.next()
if cfg['dry_run']:
break
bar.finish()
################################
# Tensorboard logs
################################
global_step += train_steps
writer_train.add_scalar("loss", loss_avg.avg, epoch)
val_loss = evaluate_loss(model, dataloader_val, config)
writer_valid.add_scalar("loss", val_loss, epoch)
val_ade = val_loss/100
if val_ade < min_val_loss:
min_val_loss = val_ade
print('------------------------------BEST MODEL UPDATED------------------------------')
print('Best ADE: ', val_ade)
save_checkpoint(model, optimizer, epoch, config, 'best_val'+'_checkpoint.pth.tar', logger)
if cfg['dry_run']:
break
print('time for training: ', time.time()-start_time)
print('epoch ', epoch, ' finished!')
if not cfg['dry_run']:
save_checkpoint(model, optimizer, epoch, config, 'checkpoint.pth.tar', logger)
logger.info("All done.")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--exp_name", type=str, default="", help="Experiment name. Otherwise will use timestamp")
parser.add_argument("--cfg", type=str, default="", help="Config name. Otherwise will use default config")
parser.add_argument('--dry-run', action='store_true', help="Run just one iteration")
args = parser.parse_args()
if args.cfg != "":
|
def evaluate_loss(model, dataloader, config):
bar = Bar(f"EVAL", fill="#", max=len(dataloader))
loss_avg = AverageMeter()
dataiter = iter(dataloader)
model.eval()
with torch.no_grad():
for i in range(len(dataloader)):
try:
joints, masks, padding_mask = next(dataiter)
except StopIteration:
break
in_joints, in_masks, out_joints, out_masks, padding_mask = batch_process_coords(joints, masks, padding_mask, config)
padding_mask = padding_mask.to(config["DEVICE"])
loss, _ = compute_loss(model, config, in_joints, out_joints, in_masks, out_masks, padding_mask)
loss_avg.update(loss.item(), len(in_joints))
summary = [
f"({i + 1}/{len(dataloader)})",
f"LOSS: {loss_avg.avg:.4f}",
f"T-TOT: {bar.elapsed_td}",
f"T-ETA: {bar.eta_td:}"
]
bar.suffix = " | ".join(summary)
bar.next()
bar.finish()
return loss_avg.avg
def compute_loss(model, config, in_joints, out_joints, in_masks, out_masks, padding_mask, epoch=None, mode='val', loss_last=True, optimizer=None):
_, in_F, _, _ = in_joints.shape
metamask = (mode == 'train')
pred_joints = model(in_joints, padding_mask, metamask=metamask)
loss = MSE_LOSS(pred_joints[:,in_F:], out_joints, out_masks)
return loss, pred_joints
def adjust_learning_rate(optimizer, epoch, config):
"""
From: https://github.com/microsoft/MeshTransformer/
Sets the learning rate to the initial LR decayed by x every y epochs
x = 0.1, y = args.num_train_epochs*2/3 = 100
"""
# dct_multi_overfit_3dpw_allsize_multieval_noseg_rot_permute_id
lr = config['TRAIN']['lr'] * (config['TRAIN']['lr_decay'] ** epoch) # (0.1 ** (epoch // (config['TRAIN']['epochs']*4./5.) ))
if 'lr_drop' in config['TRAIN'] and config['TRAIN']['lr_drop']:
lr = lr * (0.1 ** (epoch // (config['TRAIN']['epochs']*4./5.) ))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
print('lr: ',lr)
def save_checkpoint(model, optimizer, epoch, config, filename, logger):
logger.info(f'Saving checkpoint to {filename}.')
ckpt = {
'model': model.state_dict(),
'optimizer': optimizer.state_dict(),
'epoch': epoch,
'config': config
}
torch.save(ckpt, os.path.join(config['OUTPUT']['ckpt_dir'], filename))
def dataloader_for(dataset, config, **kwargs):
return DataLoader(dataset,
batch_size=config['TRAIN']['batch_size'],
num_workers=config['TRAIN']['num_workers'],
collate_fn=collate_batch,
**kwargs)
def dataloader_for_val(dataset, config, **kwargs):
return DataLoader(dataset,
batch_size=1,
num_workers=0,
collate_fn=collate_batch,
**kwargs)
def train(config, logger, experiment_name="", dataset_name=""):
################################
# Load data
################################
in_F, out_F = config['TRAIN']['input_track_size'], config['TRAIN']['output_track_size']
dataset_train = ConcatDataset(get_datasets(config['DATA']['train_datasets'], config, logger))
dataloader_train = dataloader_for(dataset_train, config, shuffle=True, pin_memory=True)
logger.info(f"Training on a total of {len(dataset_train)} annotations.")
dataset_val = create_dataset(config['DATA']['train_datasets'][0], logger, split="val", track_size=(in_F+out_F), track_cutoff=in_F)
dataloader_val = dataloader_for(dataset_val, config, shuffle=True, pin_memory=True)
writer_name = experiment_name + "_" + str(datetime.now().strftime('%Y-%m-%d_%H-%M-%S'))
writer_train = SummaryWriter(os.path.join(config["OUTPUT"]["runs_dir"], f"{writer_name}_TRAIN"))
writer_valid = SummaryWriter(os.path.join(config["OUTPUT"]["runs_dir"], f"{writer_name}_VALID"))
################################
# Create model, loss, optimizer
################################
model = create_model(config, logger)
if config["MODEL"]["checkpoint"] != "":
logger.info(f"Loading checkpoint from {config['MODEL']['checkpoint']}")
checkpoint = torch.load(os.path.join(config['OUTPUT']['ckpt_dir'], config["MODEL"]["checkpoint"]))
model.load_state_dict(checkpoint["model"])
optimizer = torch.optim.Adam(model.parameters(), lr=config['TRAIN']['lr'])
num_parameters = sum(p.numel() for p in model.parameters() if p.requires_grad)
logger.info(f"Model has {num_parameters} parameters.")
################################
# Begin Training
################################
global_step = 0
min_val_loss = 1e4
for epoch in range(config["TRAIN"]["epochs"]):
start_time = time.time()
dataiter = iter(dataloader_train)
timer = {"DATA": 0, "FORWARD": 0, "BACKWARD": 0}
loss_avg = AverageMeter()
disc_loss_avg = AverageMeter()
disc_acc_avg = AverageMeter()
if config["TRAIN"]["optimizer"] == "adam":
adjust_learning_rate(optimizer, epoch, config)
train_steps = len(dataloader_train)
bar = Bar(f"TRAIN {epoch}/{config['TRAIN']['epochs'] - 1}", fill="#", max=train_steps)
for i in range(train_steps):
model.train()
optimizer.zero_grad()
################################
# Load a batch of data
################################
start = time.time()
try:
joints, masks, padding_mask = next(dataiter)
except StopIteration:
dataiter = iter(dataloader_train)
joints, masks, padding_mask = next(dataiter)
in_joints, in_masks, out_joints, out_masks, padding_mask = batch_process_coords(joints, masks, padding_mask, config, training=True)
padding_mask = padding_mask.to(config["DEVICE"])
timer["DATA"] = time.time() - start
################################
# Forward Pass
################################
start = time.time()
loss, pred_joints = compute_loss(model, config, in_joints, out_joints, in_masks, out_masks, padding_mask, epoch=epoch, mode='train', optimizer=None)
timer["FORWARD"] = time.time() - start
################################
# Backward Pass + Optimization
################################
start = time.time()
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), config["TRAIN"]["max_grad_norm"])
optimizer.step()
timer["BACKWARD"] = time.time() - start
################################
# Logging
################################
loss_avg.update(loss.item(), len(joints))
summary = [
f"{str(epoch).zfill(3)} ({i + 1}/{train_steps})",
f"LOSS: {loss_avg.avg:.4f}",
f"T-TOT: {bar.elapsed_td}",
f"T-ETA: {bar.eta_td:}"
]
for key, val in timer.items():
summary.append(f"{key}: {val:.2f}")
bar.suffix = " | ".join(summary)
bar.next()
if cfg['dry_run']:
break
bar.finish()
################################
# Tensorboard logs
################################
global_step += train_steps
writer_train.add_scalar("loss", loss_avg.avg, epoch)
val_loss = evaluate_loss(model, dataloader_val, config)
writer_valid.add_scalar("loss", val_loss, epoch)
val_ade = val_loss/100
if val_ade < min_val_loss:
min_val_loss = val_ade
print('------------------------------BEST MODEL UPDATED------------------------------')
print('Best ADE: ', val_ade)
save_checkpoint(model, optimizer, epoch, config, 'best_val'+'_checkpoint.pth.tar', logger)
if cfg['dry_run']:
break
print('time for training: ', time.time()-start_time)
print('epoch ', epoch, ' finished!')
if not cfg['dry_run']:
save_checkpoint(model, optimizer, epoch, config, 'checkpoint.pth.tar', logger)
logger.info("All done.")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--exp_name", type=str, default="", help="Experiment name. Otherwise will use timestamp")
parser.add_argument("--cfg", type=str, default="", help="Config name. Otherwise will use default config")
parser.add_argument('--dry-run', action='store_true', help="Run just one iteration")
args = parser.parse_args()
if args.cfg != "": | cfg = load_config(args.cfg, exp_name=args.exp_name) | 7 | 2023-12-25 15:12:40+00:00 | 8k |
AzizKpln/AutoIOC-MISP | main.py | [
{
"identifier": "runAbuseIP",
"path": "Integrations/abuseipdb.py",
"snippet": "def runAbuseIP(mispapi,mispurl,mispeventid):\r\n misp_connect(mispapi,mispurl,mispeventid)\r\n url = 'https://api.abuseipdb.com/api/v2/blacklist'\r\n querystring = {\r\n 'confidenceMinimum':'85'\r\n }\r\n ... | from flask import Flask, render_template, redirect, request
from Integrations.abuseipdb import runAbuseIP
from Integrations.cinsscore import runCinsScore
from Integrations.killnet import runKillnet
from Integrations.emergingthreats import runEmergingThreats
from Integrations.honeydb import runHoneyDB
from Integrations.maltiverse import runMaltiverse
from Integrations.malware_bazar import runMalwareBazaar
from Integrations.openphish import runOpenPhish
from Integrations.phishunt import runPhishHunt
from Integrations.rescureme import runRescureMe
from Integrations.sslbl import runSSLbl
from Integrations.threatfox import runThreatFox
from Integrations.urlhaus import runURLHaus
from Integrations.virusshare import runVirusShare
from Integrations.vxvault import runVXVault
from Integrations.manual import runManually
import threading
| 3,649 | app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def hello_world():
if request.method == 'POST':
operation = request.form['operation']
if operation=="add_manually":
return redirect("/manually")
else:
return redirect('/automaticlly')
return render_template('main.html')
@app.route("/manually",methods=["GET","POST"])
def manually():
if request.method=="POST":
ioclist=request.form.getlist("iocList")
mispapi=request.form["mispapi"];mispurl=request.form["mispurl"];mispeventid=request.form["mispeventid"]
threading.Thread(target=runManually,args=(mispapi,mispurl,mispeventid,ioclist,)).start()
return render_template("manual.html")
@app.route("/automaticlly",methods=["GET","POST"])
def automaticlly():
if request.method=="POST":
selected_sources = request.form.getlist('sources')
mispapi=request.form["mispapi"];mispurl=request.form["mispurl"];mispeventid=request.form["mispeventid"]
with open("MISP/Info","w") as f:
f.write("MISPAPI:"+mispapi+"\n"+"MISPURL:"+mispurl+"\n"+"MISPEVENTID:"+mispeventid)
for i in selected_sources:
if i=="AbuseIPDB":
with open("Selected/sources","a+") as f:
f.write("AbuseIPDB\n")
threading.Thread(target=runAbuseIP,args=(mispapi,mispurl,mispeventid,)).start()
if i=="CinsScore":
with open("Selected/sources","a+") as f:
f.write("CinsScore\n")
threading.Thread(target=runCinsScore,args=(mispapi,mispurl,mispeventid,)).start()
if i=="KillNet":
with open("Selected/sources","a+") as f:
f.write("KillNet\n")
threading.Thread(target=runKillnet,args=(mispapi,mispurl,mispeventid,)).start()
if i=="Emerging Threats":
with open("Selected/sources","a+") as f:
f.write("Emerging_Threats\n")
threading.Thread(target=runEmergingThreats,args=(mispapi,mispurl,mispeventid,)).start()
if i=="HoneyDB":
with open("Selected/sources","a+") as f:
f.write("HoneyDB\n")
| app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def hello_world():
if request.method == 'POST':
operation = request.form['operation']
if operation=="add_manually":
return redirect("/manually")
else:
return redirect('/automaticlly')
return render_template('main.html')
@app.route("/manually",methods=["GET","POST"])
def manually():
if request.method=="POST":
ioclist=request.form.getlist("iocList")
mispapi=request.form["mispapi"];mispurl=request.form["mispurl"];mispeventid=request.form["mispeventid"]
threading.Thread(target=runManually,args=(mispapi,mispurl,mispeventid,ioclist,)).start()
return render_template("manual.html")
@app.route("/automaticlly",methods=["GET","POST"])
def automaticlly():
if request.method=="POST":
selected_sources = request.form.getlist('sources')
mispapi=request.form["mispapi"];mispurl=request.form["mispurl"];mispeventid=request.form["mispeventid"]
with open("MISP/Info","w") as f:
f.write("MISPAPI:"+mispapi+"\n"+"MISPURL:"+mispurl+"\n"+"MISPEVENTID:"+mispeventid)
for i in selected_sources:
if i=="AbuseIPDB":
with open("Selected/sources","a+") as f:
f.write("AbuseIPDB\n")
threading.Thread(target=runAbuseIP,args=(mispapi,mispurl,mispeventid,)).start()
if i=="CinsScore":
with open("Selected/sources","a+") as f:
f.write("CinsScore\n")
threading.Thread(target=runCinsScore,args=(mispapi,mispurl,mispeventid,)).start()
if i=="KillNet":
with open("Selected/sources","a+") as f:
f.write("KillNet\n")
threading.Thread(target=runKillnet,args=(mispapi,mispurl,mispeventid,)).start()
if i=="Emerging Threats":
with open("Selected/sources","a+") as f:
f.write("Emerging_Threats\n")
threading.Thread(target=runEmergingThreats,args=(mispapi,mispurl,mispeventid,)).start()
if i=="HoneyDB":
with open("Selected/sources","a+") as f:
f.write("HoneyDB\n")
| threading.Thread(target=runHoneyDB,args=(mispapi,mispurl,mispeventid,)).start()
| 4 | 2023-12-23 10:39:28+00:00 | 8k |
facebookresearch/ca_body | ca_body/nn/unet.py | [
{
"identifier": "weights_initializer",
"path": "ca_body/nn/blocks.py",
"snippet": "def weights_initializer(lrelu_slope=0.2):\n # pyre-ignore\n def init_fn(m):\n if isinstance(\n m,\n (\n nn.Conv2d,\n nn.Conv1d,\n nn.ConvTran... | import torch as th
import torch.nn as nn
import ca_body.nn.layers as la
from ca_body.nn.blocks import weights_initializer
from ca_body.nn.layers import Conv2dWNUB, ConvTranspose2dWNUB, glorot | 4,128 | ):
super().__init__()
F = n_init_ftrs
self.size = size
self.down1 = nn.Sequential(
la.Conv2dWNUB(in_channels, F, self.size // 2, self.size // 2, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.down2 = nn.Sequential(
la.Conv2dWNUB(F, 2 * F, self.size // 4, self.size // 4, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.down3 = nn.Sequential(
la.Conv2dWNUB(2 * F, 4 * F, self.size // 8, self.size // 8, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.down4 = nn.Sequential(
la.Conv2dWNUB(4 * F, 8 * F, self.size // 16, self.size // 16, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.down5 = nn.Sequential(
la.Conv2dWNUB(8 * F, 16 * F, self.size // 32, self.size // 32, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up1 = nn.Sequential(
la.ConvTranspose2dWNUB(16 * F, 8 * F, self.size // 16, self.size // 16, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up2 = nn.Sequential(
la.ConvTranspose2dWNUB(2 * 8 * F, 4 * F, self.size // 8, self.size // 8, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up3 = nn.Sequential(
la.ConvTranspose2dWNUB(2 * 4 * F, 2 * F, self.size // 4, self.size // 4, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up4 = nn.Sequential(
la.ConvTranspose2dWNUB(2 * 2 * F, F, self.size // 2, self.size // 2, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up5 = nn.Sequential(
la.ConvTranspose2dWNUB(2 * F, F, self.size, self.size, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.out = la.Conv2dWNUB(F + in_channels, out_channels, self.size, self.size, kernel_size=1)
self.apply(lambda x: la.glorot(x, 0.2))
la.glorot(self.out, 1.0)
def forward(self, x):
x1 = x
x2 = self.down1(x1)
x3 = self.down2(x2)
x4 = self.down3(x3)
x5 = self.down4(x4)
x6 = self.down5(x5)
x = th.cat([self.up1(x6), x5], 1)
x = th.cat([self.up2(x), x4], 1)
x = th.cat([self.up3(x), x3], 1)
x = th.cat([self.up4(x), x2], 1)
x = self.up5(x)
x = th.cat([x, x1], dim=1)
return self.out(x)
class UNetW(nn.Module):
def __init__(
self,
in_channels,
out_channels,
n_init_ftrs,
kernel_size=4,
out_scale=1.0,
):
super().__init__()
self.out_scale = out_scale
F = n_init_ftrs
self.down1 = nn.Sequential(
la.Conv2dWN(in_channels, F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.down2 = nn.Sequential(
la.Conv2dWN(F, 2 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.down3 = nn.Sequential(
la.Conv2dWN(2 * F, 4 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.down4 = nn.Sequential(
la.Conv2dWN(4 * F, 8 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.down5 = nn.Sequential(
la.Conv2dWN(8 * F, 16 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.up1 = nn.Sequential(
la.ConvTranspose2dWN(16 * F, 8 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.up2 = nn.Sequential(
la.ConvTranspose2dWN(8 * F, 4 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.up3 = nn.Sequential(
la.ConvTranspose2dWN(4 * F, 2 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.up4 = nn.Sequential(
la.ConvTranspose2dWN(2 * F, F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.up5 = nn.Sequential(la.ConvTranspose2dWN(F, F, kernel_size, 2, 1), nn.LeakyReLU(0.2))
self.out = la.Conv2dWN(F + in_channels, out_channels, kernel_size=1)
| # 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 UNetWB(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
size: int,
n_init_ftrs: int=8,
out_scale: float =0.1,
):
# super().__init__(*args, **kwargs)
super().__init__()
self.out_scale = out_scale
F = n_init_ftrs
self.size = size
self.down1 = nn.Sequential(
Conv2dWNUB(in_channels, F, self.size // 2, self.size // 2, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.down2 = nn.Sequential(
Conv2dWNUB(F, 2 * F, self.size // 4, self.size // 4, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.down3 = nn.Sequential(
Conv2dWNUB(2 * F, 4 * F, self.size // 8, self.size // 8, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.down4 = nn.Sequential(
Conv2dWNUB(4 * F, 8 * F, self.size // 16, self.size // 16, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.down5 = nn.Sequential(
Conv2dWNUB(8 * F, 16 * F, self.size // 32, self.size // 32, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up1 = nn.Sequential(
ConvTranspose2dWNUB(16 * F, 8 * F, self.size // 16, self.size // 16, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up2 = nn.Sequential(
ConvTranspose2dWNUB(8 * F, 4 * F, self.size // 8, self.size // 8, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up3 = nn.Sequential(
ConvTranspose2dWNUB(4 * F, 2 * F, self.size // 4, self.size // 4, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up4 = nn.Sequential(
ConvTranspose2dWNUB(2 * F, F, self.size // 2, self.size // 2, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up5 = nn.Sequential(
ConvTranspose2dWNUB(F, F, self.size, self.size, 4, 2, 1), nn.LeakyReLU(0.2)
)
self.out = Conv2dWNUB(F + in_channels, out_channels, self.size, self.size, kernel_size=1)
self.apply(lambda x: glorot(x, 0.2))
glorot(self.out, 1.0)
def forward(self, x):
x1 = x
x2 = self.down1(x1)
x3 = self.down2(x2)
x4 = self.down3(x3)
x5 = self.down4(x4)
x6 = self.down5(x5)
# TODO: switch to concat?
x = self.up1(x6) + x5
x = self.up2(x) + x4
x = self.up3(x) + x3
x = self.up4(x) + x2
x = self.up5(x)
x = th.cat([x, x1], dim=1)
return self.out(x) * self.out_scale
class UNetWBConcat(nn.Module):
def __init__(
self,
in_channels: int,
out_channels: int,
size: int,
n_init_ftrs: int = 8,
):
super().__init__()
F = n_init_ftrs
self.size = size
self.down1 = nn.Sequential(
la.Conv2dWNUB(in_channels, F, self.size // 2, self.size // 2, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.down2 = nn.Sequential(
la.Conv2dWNUB(F, 2 * F, self.size // 4, self.size // 4, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.down3 = nn.Sequential(
la.Conv2dWNUB(2 * F, 4 * F, self.size // 8, self.size // 8, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.down4 = nn.Sequential(
la.Conv2dWNUB(4 * F, 8 * F, self.size // 16, self.size // 16, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.down5 = nn.Sequential(
la.Conv2dWNUB(8 * F, 16 * F, self.size // 32, self.size // 32, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up1 = nn.Sequential(
la.ConvTranspose2dWNUB(16 * F, 8 * F, self.size // 16, self.size // 16, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up2 = nn.Sequential(
la.ConvTranspose2dWNUB(2 * 8 * F, 4 * F, self.size // 8, self.size // 8, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up3 = nn.Sequential(
la.ConvTranspose2dWNUB(2 * 4 * F, 2 * F, self.size // 4, self.size // 4, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up4 = nn.Sequential(
la.ConvTranspose2dWNUB(2 * 2 * F, F, self.size // 2, self.size // 2, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.up5 = nn.Sequential(
la.ConvTranspose2dWNUB(2 * F, F, self.size, self.size, 4, 2, 1),
nn.LeakyReLU(0.2),
)
self.out = la.Conv2dWNUB(F + in_channels, out_channels, self.size, self.size, kernel_size=1)
self.apply(lambda x: la.glorot(x, 0.2))
la.glorot(self.out, 1.0)
def forward(self, x):
x1 = x
x2 = self.down1(x1)
x3 = self.down2(x2)
x4 = self.down3(x3)
x5 = self.down4(x4)
x6 = self.down5(x5)
x = th.cat([self.up1(x6), x5], 1)
x = th.cat([self.up2(x), x4], 1)
x = th.cat([self.up3(x), x3], 1)
x = th.cat([self.up4(x), x2], 1)
x = self.up5(x)
x = th.cat([x, x1], dim=1)
return self.out(x)
class UNetW(nn.Module):
def __init__(
self,
in_channels,
out_channels,
n_init_ftrs,
kernel_size=4,
out_scale=1.0,
):
super().__init__()
self.out_scale = out_scale
F = n_init_ftrs
self.down1 = nn.Sequential(
la.Conv2dWN(in_channels, F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.down2 = nn.Sequential(
la.Conv2dWN(F, 2 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.down3 = nn.Sequential(
la.Conv2dWN(2 * F, 4 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.down4 = nn.Sequential(
la.Conv2dWN(4 * F, 8 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.down5 = nn.Sequential(
la.Conv2dWN(8 * F, 16 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.up1 = nn.Sequential(
la.ConvTranspose2dWN(16 * F, 8 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.up2 = nn.Sequential(
la.ConvTranspose2dWN(8 * F, 4 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.up3 = nn.Sequential(
la.ConvTranspose2dWN(4 * F, 2 * F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.up4 = nn.Sequential(
la.ConvTranspose2dWN(2 * F, F, kernel_size, 2, 1),
nn.LeakyReLU(0.2),
)
self.up5 = nn.Sequential(la.ConvTranspose2dWN(F, F, kernel_size, 2, 1), nn.LeakyReLU(0.2))
self.out = la.Conv2dWN(F + in_channels, out_channels, kernel_size=1) | self.apply(weights_initializer(0.2)) | 0 | 2023-12-27 15:31:35+00:00 | 8k |
0x00wolf/hkrsAI | src/dispatcher.py | [
{
"identifier": "InputParser",
"path": "src/inputparser.py",
"snippet": "class InputParser:\n @staticmethod\n def parse(user_input):\n \"\"\"parses user input and passes an Action to the Dispatcher\"\"\"\n if user_input.startswith('>'):\n if ' ' in user_input:\n ... | from typing import Type
from src.inputparser import InputParser
from src.action import Action
from src.gpt import GPT
from src.client import Client
from src.conversation import Conversation
from src.systemprompt import SystemPrompt
from src.logger import Logger
from src.cmdshelp import HELP_STRING
import openai
import subprocess
import ast
import sys
import os | 5,401 |
class Dispatcher:
"""Dispatches functions and manages conversation state."""
def __init__(self):
self.thinking: bool = False
def dispatch(self, action: Action):
"""Turns an Action into a function"""
if action.command == 'stop':
self.thinking = True # >stop
return self.silence
elif action.command == 'start':
self.thinking = False # >start
return self.silence
elif self.thinking and action.command == 'chat':
return self.think
elif action.command == 'chat':
return self.speak
elif action.command == 'exec':
return self.execute
elif action.command == 'insert':
return self.insert
elif action.command == 'show':
return self.show
elif action.command == 'flush':
return self.flush
elif action.command == 'save':
return self.save
elif action.command == 'set':
return self.set
elif action.command == 'reset':
return self.reset
elif action.command == 'help':
return self.help
elif action.command == 'exit':
return self.goodbye
else:
return self.silence
@staticmethod
|
class Dispatcher:
"""Dispatches functions and manages conversation state."""
def __init__(self):
self.thinking: bool = False
def dispatch(self, action: Action):
"""Turns an Action into a function"""
if action.command == 'stop':
self.thinking = True # >stop
return self.silence
elif action.command == 'start':
self.thinking = False # >start
return self.silence
elif self.thinking and action.command == 'chat':
return self.think
elif action.command == 'chat':
return self.speak
elif action.command == 'exec':
return self.execute
elif action.command == 'insert':
return self.insert
elif action.command == 'show':
return self.show
elif action.command == 'flush':
return self.flush
elif action.command == 'save':
return self.save
elif action.command == 'set':
return self.set
elif action.command == 'reset':
return self.reset
elif action.command == 'help':
return self.help
elif action.command == 'exit':
return self.goodbye
else:
return self.silence
@staticmethod | def silence(gpt: GPT, conversation: Conversation, action: Action, logger: Logger): | 6 | 2023-12-22 07:04:47+00:00 | 8k |
daswer123/rvc-python | rvc_python/infer.py | [
{
"identifier": "VC",
"path": "rvc_python/modules/vc/modules.py",
"snippet": "class VC:\n def __init__(self, lib_dir, config):\n self.lib_dir = lib_dir\n self.n_spk = None\n self.tgt_sr = None\n self.net_g = None\n self.pipeline = None\n self.cpt = None\n ... | from rvc_python.modules.vc.modules import VC
from rvc_python.configs.config import Config
from scipy.io import wavfile
from glob import glob
from rvc_python.modules.vc.modules import VC
from rvc_python.download_model import download_rvc_models
import os
import soundfile as sf | 6,923 |
def infer_file(
input_path,
model_path,
index_path = "",
device = "cpu:0",
f0method = "harvest",
opt_path = "out.wav",
index_rate = 0.5,
filter_radius = 3,
resample_sr = 0,
rms_mix_rate = 1,
protect = 0.33,
f0up_key = 0,
version = "v2"
):
lib_dir = os.path.dirname(os.path.abspath(__file__))
download_rvc_models(lib_dir)
config = Config(lib_dir,device)
|
def infer_file(
input_path,
model_path,
index_path = "",
device = "cpu:0",
f0method = "harvest",
opt_path = "out.wav",
index_rate = 0.5,
filter_radius = 3,
resample_sr = 0,
rms_mix_rate = 1,
protect = 0.33,
f0up_key = 0,
version = "v2"
):
lib_dir = os.path.dirname(os.path.abspath(__file__))
download_rvc_models(lib_dir)
config = Config(lib_dir,device) | vc = VC(lib_dir,config) | 2 | 2023-12-26 19:05:42+00:00 | 8k |
run-llama/rags | core/agent_builder/loader.py | [
{
"identifier": "BUILDER_LLM",
"path": "core/builder_config.py",
"snippet": "BUILDER_LLM = OpenAI(model=\"gpt-4-1106-preview\")"
},
{
"identifier": "ParamCache",
"path": "core/param_cache.py",
"snippet": "class ParamCache(BaseModel):\n \"\"\"Cache for RAG agent builder.\n\n Created... | from typing import List, cast, Optional
from llama_index.tools import FunctionTool
from llama_index.agent.types import BaseAgent
from core.builder_config import BUILDER_LLM
from typing import Tuple, Callable
from core.param_cache import ParamCache
from core.utils import (
load_meta_agent,
)
from core.agent_builder.registry import AgentCacheRegistry
from core.agent_builder.base import RAGAgentBuilder, BaseRAGAgentBuilder
from core.agent_builder.multimodal import MultimodalRAGAgentBuilder
import streamlit as st | 5,697 | """Loader agent."""
####################
#### META Agent ####
####################
RAG_BUILDER_SYS_STR = """\
You are helping to construct an agent given a user-specified task.
You should generally use the tools in this rough order to build the agent.
1) Create system prompt tool: to create the system prompt for the agent.
2) Load in user-specified data (based on file paths they specify).
3) Decide whether or not to add additional tools.
4) Set parameters for the RAG pipeline.
5) Build the agent
This will be a back and forth conversation with the user. You should
continue asking users if there's anything else they want to do until
they say they're done. To help guide them on the process,
you can give suggestions on parameters they can set based on the tools they
have available (e.g. "Do you want to set the number of documents to retrieve?")
"""
### DEFINE Agent ####
# NOTE: here we define a function that is dependent on the LLM,
# please make sure to update the LLM above if you change the function below
| """Loader agent."""
####################
#### META Agent ####
####################
RAG_BUILDER_SYS_STR = """\
You are helping to construct an agent given a user-specified task.
You should generally use the tools in this rough order to build the agent.
1) Create system prompt tool: to create the system prompt for the agent.
2) Load in user-specified data (based on file paths they specify).
3) Decide whether or not to add additional tools.
4) Set parameters for the RAG pipeline.
5) Build the agent
This will be a back and forth conversation with the user. You should
continue asking users if there's anything else they want to do until
they say they're done. To help guide them on the process,
you can give suggestions on parameters they can set based on the tools they
have available (e.g. "Do you want to set the number of documents to retrieve?")
"""
### DEFINE Agent ####
# NOTE: here we define a function that is dependent on the LLM,
# please make sure to update the LLM above if you change the function below
| def _get_builder_agent_tools(agent_builder: RAGAgentBuilder) -> List[FunctionTool]: | 4 | 2023-11-16 07:49:44+00:00 | 8k |
open-mmlab/Amphion | processors/content_extractor.py | [
{
"identifier": "TorchaudioDataset",
"path": "utils/io_optim.py",
"snippet": "class TorchaudioDataset(torch.utils.data.Dataset):\n def __init__(self, cfg, dataset, sr, accelerator=None, metadata=None):\n \"\"\"\n Args:\n cfg: config\n dataset: dataset name\n\n ... | import os
import torch
import numpy as np
import yaml
import copy
import whisper
from tqdm import tqdm
from torchaudio.compliance import kaldi
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader
from fairseq import checkpoint_utils
from transformers import AutoModel, Wav2Vec2FeatureExtractor
from utils.io_optim import (
TorchaudioDataset,
LibrosaDataset,
FFmpegDataset,
collate_batch,
)
from modules.wenet_extractor.utils.init_model import init_model
from modules.wenet_extractor.utils.checkpoint import load_checkpoint | 4,396 | frameshift = self.cfg.preprocess.mert_frameshift
else:
raise NotImplementedError
# calculate the number of valid frames
num_frames = int(np.ceil((duration - frameshift) / frameshift)) + 1
# (num_frames, dim) -> (valid_frames, dim)
assert (
len(content_feature.shape) == 2
), "content feature shape error, it should be (num_frames, dim)"
content_feature = content_feature[:num_frames, :]
np.save(save_path, content_feature.cpu().detach().numpy())
class WhisperExtractor(BaseExtractor):
def __init__(self, config):
super(WhisperExtractor, self).__init__(config)
self.extractor_type = "whisper"
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def load_model(self):
# load whisper checkpoint
print("Loading Whisper Model...")
if "whisper_model_path" in self.cfg.preprocess:
if os.path.isfile(self.cfg.preprocess.whisper_model_path):
# "pretrained/whisper/medium.pt"
download_root = os.path.dirname(self.cfg.preprocess.whisper_model_path)
elif os.path.isdir(self.cfg.preprocess.whisper_model_path):
# "pretrained/whisper"
download_root = self.cfg.preprocess.whisper_model_path
else:
# if the path does not exist, download the model to the path
download_root = self.cfg.preprocess.whisper_model_path
if download_root.endswith(".pt"):
download_root = os.path.dirname(download_root)
else:
download_root = None
model = whisper.load_model(
self.cfg.preprocess.whisper_model, self.device, download_root
)
if torch.cuda.is_available():
print("Using GPU...\n")
model = model.cuda()
else:
print("Using CPU...\n")
self.model = model.eval()
def extract_content_features(self, wavs, lens):
"""extract content features from a batch of dataloader
Args:
wavs: tensor (batch_size, T)
lens: list
"""
# wavs: (batch, max_len)
wavs = whisper.pad_or_trim(wavs)
# batch_mel: (batch, 80, 3000)
batch_mel = whisper.log_mel_spectrogram(wavs, device=self.model.device)
with torch.no_grad():
# (batch, 1500, 1024)
features = self.model.embed_audio(batch_mel)
return features
class ContentvecExtractor(BaseExtractor):
def __init__(self, cfg):
super(ContentvecExtractor, self).__init__(cfg)
self.extractor_type = "contentvec"
def load_model(self):
assert self.model == None
# Load model
ckpt_path = self.cfg.preprocess.contentvec_file
print("Load Contentvec Model...")
models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task(
[ckpt_path],
suffix="",
)
model = models[0]
model.eval()
if torch.cuda.is_available():
# print("Using GPU...\n")
model = model.cuda()
self.model = model
def extract_content_features(self, wavs, lens):
"""extract content features from a batch of dataloader
Args:
wavs: tensor (batch, T)
lens: list
"""
device = next(self.model.parameters()).device
wavs = wavs.to(device) # (batch, max_len)
padding_mask = torch.eq(wavs, torch.zeros_like(wavs)).to(device)
with torch.no_grad():
logits = self.model.extract_features(
source=wavs, padding_mask=padding_mask, output_layer=12
)
# feats: (batch, T, 256)
feats = self.model.final_proj(logits[0])
return feats
class WenetExtractor(BaseExtractor):
def __init__(self, config):
super(WenetExtractor, self).__init__(config)
self.extractor_type = "wenet"
def load_model(self):
wenet_cfg = self.cfg.preprocess.wenet_config
wenet_model_path = self.cfg.preprocess.wenet_model_path
# load Wenet config
with open(wenet_cfg, "r") as w:
wenet_configs = yaml.load(w, Loader=yaml.FullLoader)
self.extract_conf = copy.deepcopy(wenet_configs["dataset_conf"])
print("Loading Wenet Model...")
| # Copyright (c) 2023 Amphion.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Extractor for content features
1. whisper
2. contentvec
3. wenet
4. mert
Pipeline:
in preprocess.py:
call extract_utt_content_features() to extract content features for each utterance
extract_utt_content_features() envelopes the following steps:
1. load the model (whisper, contentvec, wenet)
2. extract the content features
3. save the content features into files
in svc_dataset.py:
call offline_align() to align the content features to the given target length
"""
"""
Extractor Usage:
1. initialize an instance of extractor
extractor = WhisperExtractor(cfg)
2. load the specified model
extractor.load_model()
3. extract the content features
extractor.extract_content(utt) for single utterance
extractor.extract_content_batch(utts) for batch utterances
4. save the content features
extractor.save_feature(utt, content_feature) for single utterance
"""
class BaseExtractor:
def __init__(self, cfg):
self.cfg = cfg
self.extractor_type = None
self.model = None
def offline_align(self, content, target_len):
"""
args:
content: (source_len, dim)
target_len: target length
return:
mapped_feature: (target_len, dim)
"""
target_hop = self.cfg.preprocess.hop_size
assert self.extractor_type in ["whisper", "contentvec", "wenet"]
if self.extractor_type == "whisper":
source_hop = (
self.cfg.preprocess.whisper_frameshift
* self.cfg.preprocess.whisper_downsample_rate
* self.cfg.preprocess.sample_rate
)
elif self.extractor_type == "contentvec":
source_hop = (
self.cfg.preprocess.contentvec_frameshift
* self.cfg.preprocess.sample_rate
)
elif self.extractor_type == "wenet":
source_hop = (
self.cfg.preprocess.wenet_frameshift
* self.cfg.preprocess.wenet_downsample_rate
* self.cfg.preprocess.sample_rate
)
source_hop = int(source_hop)
factor = np.gcd(source_hop, target_hop)
source_hop //= factor
target_hop //= factor
# (source_len, 256)
_, width = content.shape
# slice the content from padded feature
source_len = min(target_len * target_hop // source_hop + 1, len(content))
# const ~= target_len * target_hop
const = source_len * source_hop // target_hop * target_hop
# (source_len * source_hop, dim)
up_sampling_feats = np.repeat(content, source_hop, axis=0)
# (const, dim) -> (const/target_hop, target_hop, dim) -> (const/target_hop, dim)
down_sampling_feats = np.average(
up_sampling_feats[:const].reshape(-1, target_hop, width), axis=1
)
err = abs(target_len - len(down_sampling_feats))
if err > 8:
# err_log_dir is indeterminate
err_log_dir = os.path.join(
self.cfg.preprocess.processed_dir, "align_max_err.log"
)
try:
with open(err_log_dir, "r") as f:
err_num = int(f.read())
except:
with open(err_log_dir, "w") as f:
f.write("0")
err_num = 0
if err > err_num:
with open(err_log_dir, "w") as f:
f.write(str(err))
if len(down_sampling_feats) < target_len:
# (1, dim) -> (err, dim)
end = down_sampling_feats[-1][None, :].repeat(err, axis=0)
down_sampling_feats = np.concatenate([down_sampling_feats, end], axis=0)
# (target_len, dim)
mapped_feature = down_sampling_feats[:target_len]
return mapped_feature
def save_feature(self, utt, content_feature):
"""Save a single utternace to path {cfg.preprocess.processed_dir}
Args:
utt (dict): one item in metadata, containing information for one utterance
content_feature (tensor): content feature of one utterance
"""
uid = utt["Uid"]
assert self.extractor_type != None
out_dir = os.path.join(
self.cfg.preprocess.processed_dir, utt["Dataset"], self.extractor_type
)
os.makedirs(out_dir, exist_ok=True)
save_path = os.path.join(out_dir, uid + ".npy")
# only keep effective parts
duration = utt["Duration"]
if self.extractor_type == "whisper":
frameshift = (
self.cfg.preprocess.whisper_frameshift
* self.cfg.preprocess.whisper_downsample_rate
) # 20ms
elif self.extractor_type == "contentvec":
frameshift = self.cfg.preprocess.contentvec_frameshift # 20ms
elif self.extractor_type == "wenet":
frameshift = (
self.cfg.preprocess.wenet_frameshift
* self.cfg.preprocess.wenet_downsample_rate
) # 40ms
elif self.extractor_type == "mert":
frameshift = self.cfg.preprocess.mert_frameshift
else:
raise NotImplementedError
# calculate the number of valid frames
num_frames = int(np.ceil((duration - frameshift) / frameshift)) + 1
# (num_frames, dim) -> (valid_frames, dim)
assert (
len(content_feature.shape) == 2
), "content feature shape error, it should be (num_frames, dim)"
content_feature = content_feature[:num_frames, :]
np.save(save_path, content_feature.cpu().detach().numpy())
class WhisperExtractor(BaseExtractor):
def __init__(self, config):
super(WhisperExtractor, self).__init__(config)
self.extractor_type = "whisper"
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def load_model(self):
# load whisper checkpoint
print("Loading Whisper Model...")
if "whisper_model_path" in self.cfg.preprocess:
if os.path.isfile(self.cfg.preprocess.whisper_model_path):
# "pretrained/whisper/medium.pt"
download_root = os.path.dirname(self.cfg.preprocess.whisper_model_path)
elif os.path.isdir(self.cfg.preprocess.whisper_model_path):
# "pretrained/whisper"
download_root = self.cfg.preprocess.whisper_model_path
else:
# if the path does not exist, download the model to the path
download_root = self.cfg.preprocess.whisper_model_path
if download_root.endswith(".pt"):
download_root = os.path.dirname(download_root)
else:
download_root = None
model = whisper.load_model(
self.cfg.preprocess.whisper_model, self.device, download_root
)
if torch.cuda.is_available():
print("Using GPU...\n")
model = model.cuda()
else:
print("Using CPU...\n")
self.model = model.eval()
def extract_content_features(self, wavs, lens):
"""extract content features from a batch of dataloader
Args:
wavs: tensor (batch_size, T)
lens: list
"""
# wavs: (batch, max_len)
wavs = whisper.pad_or_trim(wavs)
# batch_mel: (batch, 80, 3000)
batch_mel = whisper.log_mel_spectrogram(wavs, device=self.model.device)
with torch.no_grad():
# (batch, 1500, 1024)
features = self.model.embed_audio(batch_mel)
return features
class ContentvecExtractor(BaseExtractor):
def __init__(self, cfg):
super(ContentvecExtractor, self).__init__(cfg)
self.extractor_type = "contentvec"
def load_model(self):
assert self.model == None
# Load model
ckpt_path = self.cfg.preprocess.contentvec_file
print("Load Contentvec Model...")
models, saved_cfg, task = checkpoint_utils.load_model_ensemble_and_task(
[ckpt_path],
suffix="",
)
model = models[0]
model.eval()
if torch.cuda.is_available():
# print("Using GPU...\n")
model = model.cuda()
self.model = model
def extract_content_features(self, wavs, lens):
"""extract content features from a batch of dataloader
Args:
wavs: tensor (batch, T)
lens: list
"""
device = next(self.model.parameters()).device
wavs = wavs.to(device) # (batch, max_len)
padding_mask = torch.eq(wavs, torch.zeros_like(wavs)).to(device)
with torch.no_grad():
logits = self.model.extract_features(
source=wavs, padding_mask=padding_mask, output_layer=12
)
# feats: (batch, T, 256)
feats = self.model.final_proj(logits[0])
return feats
class WenetExtractor(BaseExtractor):
def __init__(self, config):
super(WenetExtractor, self).__init__(config)
self.extractor_type = "wenet"
def load_model(self):
wenet_cfg = self.cfg.preprocess.wenet_config
wenet_model_path = self.cfg.preprocess.wenet_model_path
# load Wenet config
with open(wenet_cfg, "r") as w:
wenet_configs = yaml.load(w, Loader=yaml.FullLoader)
self.extract_conf = copy.deepcopy(wenet_configs["dataset_conf"])
print("Loading Wenet Model...") | self.model = init_model(wenet_configs) | 4 | 2023-11-15 09:19:27+00:00 | 8k |
KwaiKEG/KwaiAgents | kwaiagents/agent_start.py | [
{
"identifier": "Config",
"path": "kwaiagents/config.py",
"snippet": "class Config(object):\n def __init__(self) -> None:\n \"\"\"Initialize the Config class\"\"\"\n self.fast_llm_model = \"gpt-3.5-turbo\"\n self.smart_llm_model = \"gpt-4\"\n self.use_local_llm = False\n ... | import argparse
import json
import os
import sys
import time
import traceback
from datetime import datetime
from kwaiagents.config import Config, CFG
from kwaiagents.agents import KAgentSysLite, AgentProfile | 3,934 |
class AgentService(object):
def __init__(self, *args, **kwargs):
self.cfg = Config()
self.agent_profile = None
self.p_date = datetime.today().strftime('%Y%m%d')
@staticmethod
def parse_config(input_dict):
cfg = Config()
llm_name = input_dict.get("llm_name", "").lower()
cfg.fast_llm_model = llm_name
cfg.smart_llm_model = llm_name
cfg.max_tokens_num = input_dict.get("max_tokens_num", 4096)
if llm_name == "gpt-4":
cfg.fast_llm_model = "gpt-3.5-turbo"
return cfg
@staticmethod
def load_history(input_dict):
history = input_dict.get("history", list())
if not history:
history = list()
if isinstance(history, str):
history = json.loads(history)
return history
def chat(self, input_dict):
s = "============ INPUT_DICT ============\n"
for key, val in input_dict.items():
s += f"· {key.upper()}:\t{val}\n"
print(s)
chat_id = str(input_dict["id"])
history = self.load_history(input_dict)
self.cfg = self.parse_config(input_dict)
self.agent_profile = AgentProfile(input_dict)
print(self.cfg)
print(self.agent_profile)
try:
agent = KAgentSysLite(
cfg=self.cfg,
session_id=chat_id,
agent_profile=self.agent_profile,
lang=input_dict.get("lang", "en"))
print("\033[95m\033[1m" + "\n***** Question *****" + "\033[0m\033[0m")
print(input_dict["query"])
agent_results = agent.chat(
input_dict["query"],
history=history)
print("\033[95m\033[1m" + "\n***** Response *****" + "\033[0m\033[0m")
print(agent_results["response"])
result = {
"id": chat_id,
"response": agent_results["response"],
"history": json.dumps(agent_results["history"], ensure_ascii=False),
"chain_msg": agent_results["chain_msg"],
"chain_msg_str": agent_results["chain_msg_str"],
"more_info": agent_results["more_info"]
}
except KeyboardInterrupt:
exit()
except:
print(traceback.format_exc())
result = {
"id": chat_id,
"response": "error"
}
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--id", type=str, default="test", help="ID of this conversation")
parser.add_argument("--query", type=str, required=True, help="User query")
parser.add_argument("--history", type=str, default='[]', help="History of conversation")
parser.add_argument("--llm_name", type=str, default="gpt-3.5-turbo", help="the name of llm")
parser.add_argument("--use_local_llm", default=False, action='store_true', help="Whether to use local llm")
parser.add_argument("--local_llm_host", type=str, default="localhost", help="The host of local llm service")
parser.add_argument("--local_llm_port", type=int, default="8888", help="The port of local llm service")
parser.add_argument("--tool_names", type=str, default='["auto"]', help="the name of llm")
parser.add_argument("--max_iter_num", type=int, default=1, help="the number of iteration of agents")
parser.add_argument("--agent_name", type=str, default="", help="The agent name")
parser.add_argument("--agent_bio", type=str, default="", help="The agent bio, a short description")
parser.add_argument("--agent_instructions", type=str, default="", help="The instructions of how agent thinking, acting, or talking")
parser.add_argument("--external_knowledge", type=str, default="", help="The link of external knowledge")
parser.add_argument("--lang", type=str, default="en", choices=["en", "zh"], help="The language of the overall system")
parser.add_argument("--max_tokens_num", type=int, default=4096, help="Maximum length of model input")
args = parser.parse_args()
|
class AgentService(object):
def __init__(self, *args, **kwargs):
self.cfg = Config()
self.agent_profile = None
self.p_date = datetime.today().strftime('%Y%m%d')
@staticmethod
def parse_config(input_dict):
cfg = Config()
llm_name = input_dict.get("llm_name", "").lower()
cfg.fast_llm_model = llm_name
cfg.smart_llm_model = llm_name
cfg.max_tokens_num = input_dict.get("max_tokens_num", 4096)
if llm_name == "gpt-4":
cfg.fast_llm_model = "gpt-3.5-turbo"
return cfg
@staticmethod
def load_history(input_dict):
history = input_dict.get("history", list())
if not history:
history = list()
if isinstance(history, str):
history = json.loads(history)
return history
def chat(self, input_dict):
s = "============ INPUT_DICT ============\n"
for key, val in input_dict.items():
s += f"· {key.upper()}:\t{val}\n"
print(s)
chat_id = str(input_dict["id"])
history = self.load_history(input_dict)
self.cfg = self.parse_config(input_dict)
self.agent_profile = AgentProfile(input_dict)
print(self.cfg)
print(self.agent_profile)
try:
agent = KAgentSysLite(
cfg=self.cfg,
session_id=chat_id,
agent_profile=self.agent_profile,
lang=input_dict.get("lang", "en"))
print("\033[95m\033[1m" + "\n***** Question *****" + "\033[0m\033[0m")
print(input_dict["query"])
agent_results = agent.chat(
input_dict["query"],
history=history)
print("\033[95m\033[1m" + "\n***** Response *****" + "\033[0m\033[0m")
print(agent_results["response"])
result = {
"id": chat_id,
"response": agent_results["response"],
"history": json.dumps(agent_results["history"], ensure_ascii=False),
"chain_msg": agent_results["chain_msg"],
"chain_msg_str": agent_results["chain_msg_str"],
"more_info": agent_results["more_info"]
}
except KeyboardInterrupt:
exit()
except:
print(traceback.format_exc())
result = {
"id": chat_id,
"response": "error"
}
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--id", type=str, default="test", help="ID of this conversation")
parser.add_argument("--query", type=str, required=True, help="User query")
parser.add_argument("--history", type=str, default='[]', help="History of conversation")
parser.add_argument("--llm_name", type=str, default="gpt-3.5-turbo", help="the name of llm")
parser.add_argument("--use_local_llm", default=False, action='store_true', help="Whether to use local llm")
parser.add_argument("--local_llm_host", type=str, default="localhost", help="The host of local llm service")
parser.add_argument("--local_llm_port", type=int, default="8888", help="The port of local llm service")
parser.add_argument("--tool_names", type=str, default='["auto"]', help="the name of llm")
parser.add_argument("--max_iter_num", type=int, default=1, help="the number of iteration of agents")
parser.add_argument("--agent_name", type=str, default="", help="The agent name")
parser.add_argument("--agent_bio", type=str, default="", help="The agent bio, a short description")
parser.add_argument("--agent_instructions", type=str, default="", help="The instructions of how agent thinking, acting, or talking")
parser.add_argument("--external_knowledge", type=str, default="", help="The link of external knowledge")
parser.add_argument("--lang", type=str, default="en", choices=["en", "zh"], help="The language of the overall system")
parser.add_argument("--max_tokens_num", type=int, default=4096, help="Maximum length of model input")
args = parser.parse_args()
| CFG.local_llm_host = args.local_llm_host | 1 | 2023-11-13 03:37:02+00:00 | 8k |
EnVision-Research/LucidDreamer | scene/gaussian_model.py | [
{
"identifier": "inverse_sigmoid",
"path": "utils/general_utils.py",
"snippet": "def inverse_sigmoid(x):\n return torch.log(x/(1-x))"
},
{
"identifier": "get_expon_lr_func",
"path": "utils/general_utils.py",
"snippet": "def get_expon_lr_func(\n lr_init, lr_final, lr_delay_steps=0, ... | import torch
import numpy as np
import os
from utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation
from torch import nn
from utils.system_utils import mkdir_p
from plyfile import PlyData, PlyElement
from utils.sh_utils import RGB2SH,SH2RGB
from simple_knn._C import distCUDA2
from utils.graphics_utils import BasicPointCloud
from utils.general_utils import strip_symmetric, build_scaling_rotation | 4,875 | rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("rot")]
rot_names = sorted(rot_names, key = lambda x: int(x.split('_')[-1]))
rots = np.zeros((xyz.shape[0], len(rot_names)))
for idx, attr_name in enumerate(rot_names):
rots[:, idx] = np.asarray(plydata.elements[0][attr_name])
self._xyz = nn.Parameter(torch.tensor(xyz, dtype=torch.float, device="cuda").requires_grad_(True))
self._features_dc = nn.Parameter(torch.tensor(features_dc, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_(True))
self._features_rest = nn.Parameter(torch.tensor(features_extra, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_(True))
self._opacity = nn.Parameter(torch.tensor(opacities, dtype=torch.float, device="cuda").requires_grad_(True))
self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device="cuda").requires_grad_(True))
self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device="cuda").requires_grad_(True))
self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
self.active_sh_degree = self.max_sh_degree
def replace_tensor_to_optimizer(self, tensor, name):
optimizable_tensors = {}
for group in self.optimizer.param_groups:
if group["name"] not in ['background']:
if group["name"] == name:
stored_state = self.optimizer.state.get(group['params'][0], None)
stored_state["exp_avg"] = torch.zeros_like(tensor)
stored_state["exp_avg_sq"] = torch.zeros_like(tensor)
del self.optimizer.state[group['params'][0]]
group["params"][0] = nn.Parameter(tensor.requires_grad_(True))
self.optimizer.state[group['params'][0]] = stored_state
optimizable_tensors[group["name"]] = group["params"][0]
return optimizable_tensors
def _prune_optimizer(self, mask):
optimizable_tensors = {}
for group in self.optimizer.param_groups:
stored_state = self.optimizer.state.get(group['params'][0], None)
if group["name"] not in ['background']:
if stored_state is not None:
stored_state["exp_avg"] = stored_state["exp_avg"][mask]
stored_state["exp_avg_sq"] = stored_state["exp_avg_sq"][mask]
del self.optimizer.state[group['params'][0]]
group["params"][0] = nn.Parameter((group["params"][0][mask].requires_grad_(True)))
self.optimizer.state[group['params'][0]] = stored_state
optimizable_tensors[group["name"]] = group["params"][0]
else:
group["params"][0] = nn.Parameter(group["params"][0][mask].requires_grad_(True))
optimizable_tensors[group["name"]] = group["params"][0]
return optimizable_tensors
def prune_points(self, mask):
valid_points_mask = ~mask
optimizable_tensors = self._prune_optimizer(valid_points_mask)
self._xyz = optimizable_tensors["xyz"]
self._features_dc = optimizable_tensors["f_dc"]
self._features_rest = optimizable_tensors["f_rest"]
self._opacity = optimizable_tensors["opacity"]
self._scaling = optimizable_tensors["scaling"]
self._rotation = optimizable_tensors["rotation"]
self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]
self.denom = self.denom[valid_points_mask]
self.max_radii2D = self.max_radii2D[valid_points_mask]
def cat_tensors_to_optimizer(self, tensors_dict):
optimizable_tensors = {}
for group in self.optimizer.param_groups:
if group["name"] not in ['background']:
assert len(group["params"]) == 1
extension_tensor = tensors_dict[group["name"]]
stored_state = self.optimizer.state.get(group['params'][0], None)
if stored_state is not None:
stored_state["exp_avg"] = torch.cat((stored_state["exp_avg"], torch.zeros_like(extension_tensor)), dim=0)
stored_state["exp_avg_sq"] = torch.cat((stored_state["exp_avg_sq"], torch.zeros_like(extension_tensor)), dim=0)
del self.optimizer.state[group['params'][0]]
group["params"][0] = nn.Parameter(torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True))
self.optimizer.state[group['params'][0]] = stored_state
optimizable_tensors[group["name"]] = group["params"][0]
else:
group["params"][0] = nn.Parameter(torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True))
optimizable_tensors[group["name"]] = group["params"][0]
return optimizable_tensors
def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation):
d = {"xyz": new_xyz,
"f_dc": new_features_dc,
"f_rest": new_features_rest,
"opacity": new_opacities,
"scaling" : new_scaling,
"rotation" : new_rotation}
optimizable_tensors = self.cat_tensors_to_optimizer(d)
self._xyz = optimizable_tensors["xyz"]
self._features_dc = optimizable_tensors["f_dc"]
self._features_rest = optimizable_tensors["f_rest"]
self._opacity = optimizable_tensors["opacity"]
self._scaling = optimizable_tensors["scaling"]
self._rotation = optimizable_tensors["rotation"]
self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
def densify_and_split(self, grads, grad_threshold, scene_extent, N=2):
n_init_points = self.get_xyz.shape[0]
# Extract points that satisfy the gradient condition
padded_grad = torch.zeros((n_init_points), device="cuda")
padded_grad[:grads.shape[0]] = grads.squeeze()
selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)
selected_pts_mask = torch.logical_and(selected_pts_mask,
torch.max(self.get_scaling, dim=1).values > self.percent_dense*scene_extent)
stds = self.get_scaling[selected_pts_mask].repeat(N,1)
means =torch.zeros((stds.size(0), 3),device="cuda")
samples = torch.normal(mean=means, std=stds)
| #
# Copyright (C) 2023, Inria
# GRAPHDECO research group, https://team.inria.fr/graphdeco
# All rights reserved.
#
# This software is free for non-commercial, research and evaluation use
# under the terms of the LICENSE.md file.
#
# For inquiries contact george.drettakis@inria.fr
#
# from .resnet import *
class GaussianModel:
def setup_functions(self):
def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation):
L = build_scaling_rotation(scaling_modifier * scaling, rotation)
actual_covariance = L @ L.transpose(1, 2)
symm = strip_symmetric(actual_covariance)
return symm
self.scaling_activation = torch.exp
self.scaling_inverse_activation = torch.log
self.covariance_activation = build_covariance_from_scaling_rotation
self.opacity_activation = torch.sigmoid
self.inverse_opacity_activation = inverse_sigmoid
self.rotation_activation = torch.nn.functional.normalize
def __init__(self, sh_degree : int):
self.active_sh_degree = 0
self.max_sh_degree = sh_degree
self._xyz = torch.empty(0)
self._features_dc = torch.empty(0)
self._features_rest = torch.empty(0)
self._scaling = torch.empty(0)
self._rotation = torch.empty(0)
self._opacity = torch.empty(0)
self._background = torch.empty(0)
self.max_radii2D = torch.empty(0)
self.xyz_gradient_accum = torch.empty(0)
self.denom = torch.empty(0)
self.optimizer = None
self.percent_dense = 0
self.spatial_lr_scale = 0
self.setup_functions()
def capture(self):
return (
self.active_sh_degree,
self._xyz,
self._features_dc,
self._features_rest,
self._scaling,
self._rotation,
self._opacity,
self.max_radii2D,
self.xyz_gradient_accum,
self.denom,
self.optimizer.state_dict(),
self.spatial_lr_scale,
)
def restore(self, model_args, training_args):
(self.active_sh_degree,
self._xyz,
self._features_dc,
self._features_rest,
self._scaling,
self._rotation,
self._opacity,
self.max_radii2D,
xyz_gradient_accum,
denom,
opt_dict,
self.spatial_lr_scale) = model_args
self.training_setup(training_args)
self.xyz_gradient_accum = xyz_gradient_accum
self.denom = denom
self.optimizer.load_state_dict(opt_dict)
@property
def get_scaling(self):
return self.scaling_activation(self._scaling)
@property
def get_rotation(self):
return self.rotation_activation(self._rotation)
@property
def get_xyz(self):
return self._xyz
@property
def get_background(self):
return torch.sigmoid(self._background)
@property
def get_features(self):
features_dc = self._features_dc
features_rest = self._features_rest
return torch.cat((features_dc, features_rest), dim=1)
@property
def get_opacity(self):
return self.opacity_activation(self._opacity)
def get_covariance(self, scaling_modifier = 1):
return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation)
def oneupSHdegree(self):
if self.active_sh_degree < self.max_sh_degree:
self.active_sh_degree += 1
def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float):
self.spatial_lr_scale = spatial_lr_scale
fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda()
fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors))).float().cuda() #RGB2SH(
features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda()
features[:, :3, 0 ] = fused_color
features[:, 3:, 1:] = 0.0
print("Number of points at initialisation : ", fused_point_cloud.shape[0])
dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points)).float().cuda()), 0.0000001)
scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3)
rots = torch.zeros((fused_point_cloud.shape[0], 4), device="cuda")
rots[:, 0] = 1
opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device="cuda"))
self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True))
self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True))
self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True))
self._scaling = nn.Parameter(scales.requires_grad_(True))
self._rotation = nn.Parameter(rots.requires_grad_(True))
self._opacity = nn.Parameter(opacities.requires_grad_(True))
self._background = nn.Parameter(torch.zeros((3,1,1), device="cuda").requires_grad_(True))
self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
def training_setup(self, training_args):
self.percent_dense = training_args.percent_dense
self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
l = [
{'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, "name": "xyz"},
{'params': [self._features_dc], 'lr': training_args.feature_lr, "name": "f_dc"},
{'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, "name": "f_rest"},
{'params': [self._opacity], 'lr': training_args.opacity_lr, "name": "opacity"},
{'params': [self._scaling], 'lr': training_args.scaling_lr, "name": "scaling"},
{'params': [self._rotation], 'lr': training_args.rotation_lr, "name": "rotation"},
{'params': [self._background], 'lr': training_args.feature_lr, "name": "background"},
]
self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15)
self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale,
lr_final=training_args.position_lr_final*self.spatial_lr_scale,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
self.rotation_scheduler_args = get_expon_lr_func(lr_init=training_args.rotation_lr,
lr_final=training_args.rotation_lr_final,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
self.scaling_scheduler_args = get_expon_lr_func(lr_init=training_args.scaling_lr,
lr_final=training_args.scaling_lr_final,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
self.feature_scheduler_args = get_expon_lr_func(lr_init=training_args.feature_lr,
lr_final=training_args.feature_lr_final,
lr_delay_mult=training_args.position_lr_delay_mult,
max_steps=training_args.iterations)
def update_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.optimizer.param_groups:
if param_group["name"] == "xyz":
lr = self.xyz_scheduler_args(iteration)
param_group['lr'] = lr
return lr
def update_feature_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.optimizer.param_groups:
if param_group["name"] == "f_dc":
lr = self.feature_scheduler_args(iteration)
param_group['lr'] = lr
return lr
def update_rotation_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.optimizer.param_groups:
if param_group["name"] == "rotation":
lr = self.rotation_scheduler_args(iteration)
param_group['lr'] = lr
return lr
def update_scaling_learning_rate(self, iteration):
''' Learning rate scheduling per step '''
for param_group in self.optimizer.param_groups:
if param_group["name"] == "scaling":
lr = self.scaling_scheduler_args(iteration)
param_group['lr'] = lr
return lr
def construct_list_of_attributes(self):
l = ['x', 'y', 'z', 'nx', 'ny', 'nz']
# All channels except the 3 DC
for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]):
l.append('f_dc_{}'.format(i))
for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]):
l.append('f_rest_{}'.format(i))
l.append('opacity')
for i in range(self._scaling.shape[1]):
l.append('scale_{}'.format(i))
for i in range(self._rotation.shape[1]):
l.append('rot_{}'.format(i))
return l
def save_ply(self, path):
mkdir_p(os.path.dirname(path))
xyz = self._xyz.detach().cpu().numpy()
normals = np.zeros_like(xyz)
f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy()
opacities = self._opacity.detach().cpu().numpy()
scale = self._scaling.detach().cpu().numpy()
rotation = self._rotation.detach().cpu().numpy()
dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()]
elements = np.empty(xyz.shape[0], dtype=dtype_full)
attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1)
elements[:] = list(map(tuple, attributes))
el = PlyElement.describe(elements, 'vertex')
PlyData([el]).write(path)
np.savetxt(os.path.join(os.path.split(path)[0],"point_cloud_rgb.txt"),np.concatenate((xyz, SH2RGB(f_dc)), axis=1))
def reset_opacity(self):
opacities_new = inverse_sigmoid(torch.min(self.get_opacity, torch.ones_like(self.get_opacity)*0.01))
optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, "opacity")
self._opacity = optimizable_tensors["opacity"]
def load_ply(self, path):
plydata = PlyData.read(path)
xyz = np.stack((np.asarray(plydata.elements[0]["x"]),
np.asarray(plydata.elements[0]["y"]),
np.asarray(plydata.elements[0]["z"])), axis=1)
opacities = np.asarray(plydata.elements[0]["opacity"])[..., np.newaxis]
features_dc = np.zeros((xyz.shape[0], 3, 1))
features_dc[:, 0, 0] = np.asarray(plydata.elements[0]["f_dc_0"])
features_dc[:, 1, 0] = np.asarray(plydata.elements[0]["f_dc_1"])
features_dc[:, 2, 0] = np.asarray(plydata.elements[0]["f_dc_2"])
extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("f_rest_")]
extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1]))
assert len(extra_f_names)==3*(self.max_sh_degree + 1) ** 2 - 3
features_extra = np.zeros((xyz.shape[0], len(extra_f_names)))
for idx, attr_name in enumerate(extra_f_names):
features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name])
# Reshape (P,F*SH_coeffs) to (P, F, SH_coeffs except DC)
features_extra = features_extra.reshape((features_extra.shape[0], 3, (self.max_sh_degree + 1) ** 2 - 1))
scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("scale_")]
scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1]))
scales = np.zeros((xyz.shape[0], len(scale_names)))
for idx, attr_name in enumerate(scale_names):
scales[:, idx] = np.asarray(plydata.elements[0][attr_name])
rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("rot")]
rot_names = sorted(rot_names, key = lambda x: int(x.split('_')[-1]))
rots = np.zeros((xyz.shape[0], len(rot_names)))
for idx, attr_name in enumerate(rot_names):
rots[:, idx] = np.asarray(plydata.elements[0][attr_name])
self._xyz = nn.Parameter(torch.tensor(xyz, dtype=torch.float, device="cuda").requires_grad_(True))
self._features_dc = nn.Parameter(torch.tensor(features_dc, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_(True))
self._features_rest = nn.Parameter(torch.tensor(features_extra, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_(True))
self._opacity = nn.Parameter(torch.tensor(opacities, dtype=torch.float, device="cuda").requires_grad_(True))
self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device="cuda").requires_grad_(True))
self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device="cuda").requires_grad_(True))
self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
self.active_sh_degree = self.max_sh_degree
def replace_tensor_to_optimizer(self, tensor, name):
optimizable_tensors = {}
for group in self.optimizer.param_groups:
if group["name"] not in ['background']:
if group["name"] == name:
stored_state = self.optimizer.state.get(group['params'][0], None)
stored_state["exp_avg"] = torch.zeros_like(tensor)
stored_state["exp_avg_sq"] = torch.zeros_like(tensor)
del self.optimizer.state[group['params'][0]]
group["params"][0] = nn.Parameter(tensor.requires_grad_(True))
self.optimizer.state[group['params'][0]] = stored_state
optimizable_tensors[group["name"]] = group["params"][0]
return optimizable_tensors
def _prune_optimizer(self, mask):
optimizable_tensors = {}
for group in self.optimizer.param_groups:
stored_state = self.optimizer.state.get(group['params'][0], None)
if group["name"] not in ['background']:
if stored_state is not None:
stored_state["exp_avg"] = stored_state["exp_avg"][mask]
stored_state["exp_avg_sq"] = stored_state["exp_avg_sq"][mask]
del self.optimizer.state[group['params'][0]]
group["params"][0] = nn.Parameter((group["params"][0][mask].requires_grad_(True)))
self.optimizer.state[group['params'][0]] = stored_state
optimizable_tensors[group["name"]] = group["params"][0]
else:
group["params"][0] = nn.Parameter(group["params"][0][mask].requires_grad_(True))
optimizable_tensors[group["name"]] = group["params"][0]
return optimizable_tensors
def prune_points(self, mask):
valid_points_mask = ~mask
optimizable_tensors = self._prune_optimizer(valid_points_mask)
self._xyz = optimizable_tensors["xyz"]
self._features_dc = optimizable_tensors["f_dc"]
self._features_rest = optimizable_tensors["f_rest"]
self._opacity = optimizable_tensors["opacity"]
self._scaling = optimizable_tensors["scaling"]
self._rotation = optimizable_tensors["rotation"]
self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask]
self.denom = self.denom[valid_points_mask]
self.max_radii2D = self.max_radii2D[valid_points_mask]
def cat_tensors_to_optimizer(self, tensors_dict):
optimizable_tensors = {}
for group in self.optimizer.param_groups:
if group["name"] not in ['background']:
assert len(group["params"]) == 1
extension_tensor = tensors_dict[group["name"]]
stored_state = self.optimizer.state.get(group['params'][0], None)
if stored_state is not None:
stored_state["exp_avg"] = torch.cat((stored_state["exp_avg"], torch.zeros_like(extension_tensor)), dim=0)
stored_state["exp_avg_sq"] = torch.cat((stored_state["exp_avg_sq"], torch.zeros_like(extension_tensor)), dim=0)
del self.optimizer.state[group['params'][0]]
group["params"][0] = nn.Parameter(torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True))
self.optimizer.state[group['params'][0]] = stored_state
optimizable_tensors[group["name"]] = group["params"][0]
else:
group["params"][0] = nn.Parameter(torch.cat((group["params"][0], extension_tensor), dim=0).requires_grad_(True))
optimizable_tensors[group["name"]] = group["params"][0]
return optimizable_tensors
def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation):
d = {"xyz": new_xyz,
"f_dc": new_features_dc,
"f_rest": new_features_rest,
"opacity": new_opacities,
"scaling" : new_scaling,
"rotation" : new_rotation}
optimizable_tensors = self.cat_tensors_to_optimizer(d)
self._xyz = optimizable_tensors["xyz"]
self._features_dc = optimizable_tensors["f_dc"]
self._features_rest = optimizable_tensors["f_rest"]
self._opacity = optimizable_tensors["opacity"]
self._scaling = optimizable_tensors["scaling"]
self._rotation = optimizable_tensors["rotation"]
self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda")
self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda")
def densify_and_split(self, grads, grad_threshold, scene_extent, N=2):
n_init_points = self.get_xyz.shape[0]
# Extract points that satisfy the gradient condition
padded_grad = torch.zeros((n_init_points), device="cuda")
padded_grad[:grads.shape[0]] = grads.squeeze()
selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False)
selected_pts_mask = torch.logical_and(selected_pts_mask,
torch.max(self.get_scaling, dim=1).values > self.percent_dense*scene_extent)
stds = self.get_scaling[selected_pts_mask].repeat(N,1)
means =torch.zeros((stds.size(0), 3),device="cuda")
samples = torch.normal(mean=means, std=stds) | rots = build_rotation(self._rotation[selected_pts_mask]).repeat(N,1,1) | 2 | 2023-11-18 08:05:50+00:00 | 8k |
VRSEN/agency-swarm | agency_swarm/threads/thread.py | [
{
"identifier": "Agent",
"path": "agency_swarm/agents/agent.py",
"snippet": "class Agent():\n @property\n def assistant(self):\n if self._assistant is None:\n raise Exception(\"Assistant is not initialized. Please run init_oai() first.\")\n return self._assistant\n\n @a... | import inspect
import time
from typing import Literal
from agency_swarm.agents import Agent
from agency_swarm.messages import MessageOutput
from agency_swarm.user import User
from agency_swarm.util.oai import get_openai_client | 4,241 |
class Thread:
id: str = None
thread = None
run = None
|
class Thread:
id: str = None
thread = None
run = None
| def __init__(self, agent: Literal[Agent, User], recipient_agent: Agent): | 2 | 2023-11-16 02:29:26+00:00 | 8k |
pbelcak/UltraFastBERT | training/cramming/architectures/crammed_bert.py | [
{
"identifier": "FFF",
"path": "training/cramming/architectures/fff.py",
"snippet": "class FFF(nn.Module):\n\tdef __init__(self, input_width, output_width, depth, parallel_size, activation=nn.GELU):\n\t\tsuper().__init__()\n\n\t\tself.input_width = input_width\n\t\tself.output_width = output_width\n\t\t... | import torch
from transformers import PretrainedConfig, PreTrainedModel
from transformers import AutoConfig, AutoModel, AutoModelForMaskedLM, AutoModelForSequenceClassification, AutoModelForTokenClassification
from typing import Optional
from omegaconf import OmegaConf
from .fff import FFF
from .components import (
_get_norm_fn,
_get_nonlin_fn,
EmbeddingComponent,
PoolingComponent,
PredictionHeadComponent,
GLU,
get_extended_attention_mask,
_init_module,
)
from .attention import get_attention_mechanism | 5,579 | self.dense_out = torch.nn.Linear(intermed_output_size, hidden_size, bias=use_bias)
def forward(self, hidden_states):
return self.dense_out(self.nonlin(self.dense_in(hidden_states)))
class TransformerLayer(torch.nn.Module):
"""A transformer-encoder structure based on the components from above."""
def __init__(self, idx, cfg_arch):
super().__init__()
self.dropout = torch.nn.Dropout(cfg_arch.hidden_dropout_prob, inplace=False)
self.norm1 = _get_norm_fn(cfg_arch.norm)(cfg_arch.hidden_size, eps=cfg_arch.norm_eps)
self.norm2 = _get_norm_fn(cfg_arch.norm)(cfg_arch.hidden_size, eps=cfg_arch.norm_eps)
self.attn = AttentionComponent(
idx,
cfg_arch.hidden_size,
cfg_arch.attention,
cfg_arch.use_bias,
)
self.LAYOUT = self.attn.LAYOUT
UNDEFINED_VALUE = 3430323896892821
if OmegaConf.select(cfg_arch, "intermed_type", default=UNDEFINED_VALUE) == UNDEFINED_VALUE \
or cfg_arch.intermed_type == 'ff':
self.ffn = FFNComponent(
cfg_arch.hidden_size,
cfg_arch.intermed_size,
_get_nonlin_fn(cfg_arch.nonlin),
cfg_arch.use_bias,
)
elif cfg_arch.intermed_type == 'fff':
self.ffn = FFF(
cfg_arch.hidden_size,
cfg_arch.hidden_size,
cfg_arch.intermed_depth,
cfg_arch.intermed_size,
_get_nonlin_fn(cfg_arch.nonlin),
)
else:
raise ValueError(f"Invalid intermed_type {cfg_arch.intermed_type}")
def forward(self, states, attention_mask: Optional[torch.Tensor] = None):
states = states + self.dropout(self.attn(self.norm1(states), attention_mask))
states = states + self.dropout(self.ffn(self.norm2(states)))
return states
class ScriptableLM(PreTrainedModel):
"""Simplified transformer wrapper."""
config_class = crammedBertConfig
def __init__(self, config):
super().__init__(config)
self.cfg = OmegaConf.create(config.arch)
self.embedding = EmbeddingComponent(self.cfg.embedding, self.cfg.norm, self.cfg.norm_eps)
self.layers = torch.nn.ModuleList([TransformerLayer(idx, self.cfg) for idx in range(self.cfg.num_transformer_layers)])
self.seq_first = self.layers[0].LAYOUT == "[S B H]" if len(self.layers) > 0 else False
self.use_causal_attention = self.cfg.attention.causal_attention
if self.cfg.final_norm:
self.final_norm = _get_norm_fn(self.cfg.norm)(self.cfg.hidden_size, eps=self.cfg.norm_eps)
else:
self.final_norm = torch.nn.Identity()
def set_hardness(self, hardness: float):
for layer in self.layers:
if hasattr(layer, "set_hardness"):
layer.set_hardness(hardness)
def forward(self, input_ids, attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None):
if attention_mask is not None:
attention_mask = get_extended_attention_mask(attention_mask, input_ids.shape, self.use_causal_attention)
hidden_states = self.embedding(input_ids)
if self.seq_first:
hidden_states = hidden_states.transpose(0, 1).contiguous()
for i, layer_module in enumerate(self.layers):
hidden_states = layer_module(hidden_states, attention_mask)
if self.seq_first:
hidden_states = hidden_states.transpose(0, 1).contiguous()
return self.final_norm(hidden_states)
class ScriptableLMForPreTraining(PreTrainedModel):
"""Pretraining version with optional prediction head and variant for sparse prediction."""
config_class = crammedBertConfig
def __init__(self, config):
super().__init__(config)
self.cfg = OmegaConf.create(config.arch)
self.encoder = ScriptableLM(config)
if not self.cfg.skip_head_transform:
self.prediction_head = PredictionHeadComponent(self.cfg)
else:
self.prediction_head = torch.nn.Identity() # from linear in old version
self.decoder = torch.nn.Linear(self.cfg.embedding.embedding_dim, self.cfg.embedding.vocab_size, bias=self.cfg.decoder_bias)
self.decoder.weight = self.encoder.embedding.word_embedding.weight
self.loss_fn = torch.nn.CrossEntropyLoss()
self.sparse_prediction = self.cfg.sparse_prediction
self._init_weights()
def set_hardness(self, hardness: float):
self.encoder.set_hardness(hardness)
def _init_weights(self, module=None):
modules = self.modules() if module is None else [module]
for module in modules:
| """This rewrite is a simplified version of the proposed changes that actually compiles statically in torch 2.0.
This model is the final, optimized crammed model.
Not all ablations discussed in the paper are implemented as switches in this version,
for all those, check scriptable_bert.py on the old branch.
"""
class crammedBertConfig(PretrainedConfig):
model_type = "crammedBERT"
def __init__(self, cfg_arch_container: dict = {}, **kwargs):
self.arch = cfg_arch_container
super().__init__(**kwargs)
def construct_crammed_bert(cfg_arch, vocab_size, downstream_classes=None):
"""See the config file for details on what is possible."""
config = crammedBertConfig(OmegaConf.to_container(cfg_arch, resolve=True))
config.arch["embedding"]["vocab_size"] = vocab_size
config.arch["num_labels"] = downstream_classes
if downstream_classes is None:
if config.arch["objective_layout"] == "MLM":
model = ScriptableLMForPreTraining(config)
elif config.arch["objective_layout"] == "SCRIPT":
model = ScriptableLMForSCRIPTTraining(config)
else:
raise ValueError(f"Invalid layout {config.arch['objective_layout']} of training objective given.")
else:
model = ScriptableLMForSequenceClassification(config)
return model
class AttentionComponent(torch.nn.Module):
def __init__(self, idx, hidden_size, cfg_attention, use_bias=True):
super().__init__()
self.self_attention = get_attention_mechanism(idx, hidden_size, cfg_attention)
if cfg_attention.skip_output_projection:
self.dense = torch.nn.Identity()
else:
self.dense = torch.nn.Linear(self.self_attention.output_dim, hidden_size, bias=use_bias)
self.LAYOUT = self.self_attention.LAYOUT
def forward(self, hidden_states, attention_mask: Optional[torch.Tensor] = None):
return self.dense(self.self_attention(hidden_states, attention_mask))
class FFNComponent(torch.nn.Module):
"""Note: The FF layer is not auto-scaled when using a GLU type activation.
It actually turned out better not to scale it, so here the block is effectively smaller than may be expected.
The neox suggestion for approx. equal parameter count is int(4 * 2 / 3 * hidden_size) * 2 [this is ~5.33]
"""
def __init__(self, hidden_size, intermed_size, nonlin_fn=torch.nn.GELU, use_bias=True):
super().__init__()
self.dense_in = torch.nn.Linear(hidden_size, intermed_size, bias=use_bias)
self.nonlin = nonlin_fn()
if isinstance(self.nonlin, GLU):
intermed_output_size = intermed_size // 2
else:
intermed_output_size = intermed_size
self.dense_out = torch.nn.Linear(intermed_output_size, hidden_size, bias=use_bias)
def forward(self, hidden_states):
return self.dense_out(self.nonlin(self.dense_in(hidden_states)))
class TransformerLayer(torch.nn.Module):
"""A transformer-encoder structure based on the components from above."""
def __init__(self, idx, cfg_arch):
super().__init__()
self.dropout = torch.nn.Dropout(cfg_arch.hidden_dropout_prob, inplace=False)
self.norm1 = _get_norm_fn(cfg_arch.norm)(cfg_arch.hidden_size, eps=cfg_arch.norm_eps)
self.norm2 = _get_norm_fn(cfg_arch.norm)(cfg_arch.hidden_size, eps=cfg_arch.norm_eps)
self.attn = AttentionComponent(
idx,
cfg_arch.hidden_size,
cfg_arch.attention,
cfg_arch.use_bias,
)
self.LAYOUT = self.attn.LAYOUT
UNDEFINED_VALUE = 3430323896892821
if OmegaConf.select(cfg_arch, "intermed_type", default=UNDEFINED_VALUE) == UNDEFINED_VALUE \
or cfg_arch.intermed_type == 'ff':
self.ffn = FFNComponent(
cfg_arch.hidden_size,
cfg_arch.intermed_size,
_get_nonlin_fn(cfg_arch.nonlin),
cfg_arch.use_bias,
)
elif cfg_arch.intermed_type == 'fff':
self.ffn = FFF(
cfg_arch.hidden_size,
cfg_arch.hidden_size,
cfg_arch.intermed_depth,
cfg_arch.intermed_size,
_get_nonlin_fn(cfg_arch.nonlin),
)
else:
raise ValueError(f"Invalid intermed_type {cfg_arch.intermed_type}")
def forward(self, states, attention_mask: Optional[torch.Tensor] = None):
states = states + self.dropout(self.attn(self.norm1(states), attention_mask))
states = states + self.dropout(self.ffn(self.norm2(states)))
return states
class ScriptableLM(PreTrainedModel):
"""Simplified transformer wrapper."""
config_class = crammedBertConfig
def __init__(self, config):
super().__init__(config)
self.cfg = OmegaConf.create(config.arch)
self.embedding = EmbeddingComponent(self.cfg.embedding, self.cfg.norm, self.cfg.norm_eps)
self.layers = torch.nn.ModuleList([TransformerLayer(idx, self.cfg) for idx in range(self.cfg.num_transformer_layers)])
self.seq_first = self.layers[0].LAYOUT == "[S B H]" if len(self.layers) > 0 else False
self.use_causal_attention = self.cfg.attention.causal_attention
if self.cfg.final_norm:
self.final_norm = _get_norm_fn(self.cfg.norm)(self.cfg.hidden_size, eps=self.cfg.norm_eps)
else:
self.final_norm = torch.nn.Identity()
def set_hardness(self, hardness: float):
for layer in self.layers:
if hasattr(layer, "set_hardness"):
layer.set_hardness(hardness)
def forward(self, input_ids, attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None):
if attention_mask is not None:
attention_mask = get_extended_attention_mask(attention_mask, input_ids.shape, self.use_causal_attention)
hidden_states = self.embedding(input_ids)
if self.seq_first:
hidden_states = hidden_states.transpose(0, 1).contiguous()
for i, layer_module in enumerate(self.layers):
hidden_states = layer_module(hidden_states, attention_mask)
if self.seq_first:
hidden_states = hidden_states.transpose(0, 1).contiguous()
return self.final_norm(hidden_states)
class ScriptableLMForPreTraining(PreTrainedModel):
"""Pretraining version with optional prediction head and variant for sparse prediction."""
config_class = crammedBertConfig
def __init__(self, config):
super().__init__(config)
self.cfg = OmegaConf.create(config.arch)
self.encoder = ScriptableLM(config)
if not self.cfg.skip_head_transform:
self.prediction_head = PredictionHeadComponent(self.cfg)
else:
self.prediction_head = torch.nn.Identity() # from linear in old version
self.decoder = torch.nn.Linear(self.cfg.embedding.embedding_dim, self.cfg.embedding.vocab_size, bias=self.cfg.decoder_bias)
self.decoder.weight = self.encoder.embedding.word_embedding.weight
self.loss_fn = torch.nn.CrossEntropyLoss()
self.sparse_prediction = self.cfg.sparse_prediction
self._init_weights()
def set_hardness(self, hardness: float):
self.encoder.set_hardness(hardness)
def _init_weights(self, module=None):
modules = self.modules() if module is None else [module]
for module in modules: | _init_module( | 8 | 2023-11-12 17:52:59+00:00 | 8k |
resemble-ai/resemble-enhance | resemble_enhance/enhancer/enhancer.py | [
{
"identifier": "Normalizer",
"path": "resemble_enhance/common.py",
"snippet": "class Normalizer(nn.Module):\n def __init__(self, momentum=0.01, eps=1e-9):\n super().__init__()\n self.momentum = momentum\n self.eps = eps\n self.running_mean_unsafe: Tensor\n self.run... | import logging
import matplotlib.pyplot as plt
import pandas as pd
import torch
from torch import Tensor, nn
from torch.distributions import Beta
from ..common import Normalizer
from ..denoiser.inference import load_denoiser
from ..melspec import MelSpectrogram
from ..utils.distributed import global_leader_only
from ..utils.train_loop import TrainLoop
from .hparams import HParams
from .lcfm import CFM, IRMAE, LCFM
from .univnet import UnivNet | 6,410 |
logger = logging.getLogger(__name__)
def _maybe(fn):
def _fn(*args):
if args[0] is None:
return None
return fn(*args)
return _fn
def _normalize_wav(x: Tensor):
return x / (x.abs().max(dim=-1, keepdim=True).values + 1e-7)
class Enhancer(nn.Module):
def __init__(self, hp: HParams):
super().__init__()
self.hp = hp
n_mels = self.hp.num_mels
vocoder_input_dim = n_mels + self.hp.vocoder_extra_dim
latent_dim = self.hp.lcfm_latent_dim
self.lcfm = LCFM(
|
logger = logging.getLogger(__name__)
def _maybe(fn):
def _fn(*args):
if args[0] is None:
return None
return fn(*args)
return _fn
def _normalize_wav(x: Tensor):
return x / (x.abs().max(dim=-1, keepdim=True).values + 1e-7)
class Enhancer(nn.Module):
def __init__(self, hp: HParams):
super().__init__()
self.hp = hp
n_mels = self.hp.num_mels
vocoder_input_dim = n_mels + self.hp.vocoder_extra_dim
latent_dim = self.hp.lcfm_latent_dim
self.lcfm = LCFM( | IRMAE( | 6 | 2023-11-15 08:15:51+00:00 | 8k |
PKU-YuanGroup/Chat-UniVi | ChatUniVi/model/language_model/llama.py | [
{
"identifier": "MetaModel",
"path": "ChatUniVi/model/arch.py",
"snippet": "class MetaModel:\n def __init__(self, config):\n super(MetaModel, self).__init__(config)\n\n if hasattr(config, \"mm_vision_tower\"):\n self.vision_tower = build_vision_tower(config, delay_load=True)\... | from typing import List, Optional, Tuple, Union
from torch.nn import CrossEntropyLoss
from transformers import AutoConfig, AutoModelForCausalLM, \
LlamaConfig, LlamaModel, LlamaForCausalLM
from transformers.modeling_outputs import CausalLMOutputWithPast
from ChatUniVi.model.arch import MetaModel, ChatUniViMetaForCausalLM
import torch
import torch.nn as nn | 5,914 |
class ChatUniViConfig(LlamaConfig):
model_type = "ChatUniVi"
class ChatUniViLlamaModel(MetaModel, LlamaModel):
config_class = ChatUniViConfig
def __init__(self, config: LlamaConfig):
super(ChatUniViLlamaModel, self).__init__(config)
|
class ChatUniViConfig(LlamaConfig):
model_type = "ChatUniVi"
class ChatUniViLlamaModel(MetaModel, LlamaModel):
config_class = ChatUniViConfig
def __init__(self, config: LlamaConfig):
super(ChatUniViLlamaModel, self).__init__(config)
| class ChatUniViLlamaForCausalLM(LlamaForCausalLM, ChatUniViMetaForCausalLM): | 1 | 2023-11-13 11:52:56+00:00 | 8k |
banodoco/Steerable-Motion | imports/AdvancedControlNet/weight_nodes.py | [
{
"identifier": "TimestepKeyframeImport",
"path": "imports/AdvancedControlNet/control.py",
"snippet": "class TimestepKeyframeImport:\n def __init__(self,\n start_percent: float = 0.0,\n strength: float = 1.0,\n interpolation: str = StrengthInterpolation... | from torch import Tensor
from .control import TimestepKeyframeImport, TimestepKeyframeGroupImport, ControlWeightsImport, get_properly_arranged_t2i_weights, linear_conversion
from .logger import logger
import torch | 4,377 | else:
mask = linear_conversion(mask, x_min, x_max, min_base_multiplier, max_base_multiplier)
weights = ControlWeightsImport.universal_mask(weight_mask=mask)
return (weights, TimestepKeyframeGroupImport.default(TimestepKeyframeImport(control_weights=weights)))
class ScaledSoftUniversalWeightsImport:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"base_multiplier": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 1.0, "step": 0.001}, ),
"flip_weights": ("BOOLEAN", {"default": False}),
},
}
RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
RETURN_NAMES = WEIGHTS_RETURN_NAMES
FUNCTION = "load_weights"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
def load_weights(self, base_multiplier, flip_weights):
weights = ControlWeightsImport.universal(base_multiplier=base_multiplier, flip_weights=flip_weights)
return (weights, TimestepKeyframeGroupImport.default(TimestepKeyframeImport(control_weights=weights)))
class SoftControlNetWeightsImport:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"weight_00": ("FLOAT", {"default": 0.09941396206337118, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_01": ("FLOAT", {"default": 0.12050177219802567, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_02": ("FLOAT", {"default": 0.14606275417942507, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_03": ("FLOAT", {"default": 0.17704576264172736, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_04": ("FLOAT", {"default": 0.214600924414215, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_05": ("FLOAT", {"default": 0.26012233262329093, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_06": ("FLOAT", {"default": 0.3152997971191405, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_07": ("FLOAT", {"default": 0.3821815722656249, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_08": ("FLOAT", {"default": 0.4632503906249999, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_09": ("FLOAT", {"default": 0.561515625, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_10": ("FLOAT", {"default": 0.6806249999999999, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_11": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_12": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"flip_weights": ("BOOLEAN", {"default": False}),
},
}
RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
RETURN_NAMES = WEIGHTS_RETURN_NAMES
FUNCTION = "load_weights"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/ControlNet"
def load_weights(self, weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
weight_07, weight_08, weight_09, weight_10, weight_11, weight_12, flip_weights):
weights = [weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
weight_07, weight_08, weight_09, weight_10, weight_11, weight_12]
weights = ControlWeightsImport.controlnet(weights, flip_weights=flip_weights)
return (weights, TimestepKeyframeGroupImport.default(TimestepKeyframeImport(control_weights=weights)))
class CustomControlNetWeightsImport:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"weight_00": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_01": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_02": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_04": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_05": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_06": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_07": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_08": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_09": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_10": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_11": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_12": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"flip_weights": ("BOOLEAN", {"default": False}),
}
}
RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
RETURN_NAMES = WEIGHTS_RETURN_NAMES
FUNCTION = "load_weights"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/ControlNet"
def load_weights(self, weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
weight_07, weight_08, weight_09, weight_10, weight_11, weight_12, flip_weights):
weights = [weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
weight_07, weight_08, weight_09, weight_10, weight_11, weight_12]
weights = ControlWeightsImport.controlnet(weights, flip_weights=flip_weights)
return (weights, TimestepKeyframeGroupImport.default(TimestepKeyframeImport(control_weights=weights)))
class SoftT2IAdapterWeightsImport:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"weight_00": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_01": ("FLOAT", {"default": 0.62, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_02": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"flip_weights": ("BOOLEAN", {"default": False}),
},
}
RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
RETURN_NAMES = WEIGHTS_RETURN_NAMES
FUNCTION = "load_weights"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/T2IAdapter"
def load_weights(self, weight_00, weight_01, weight_02, weight_03, flip_weights):
weights = [weight_00, weight_01, weight_02, weight_03]
|
WEIGHTS_RETURN_NAMES = ("CN_WEIGHTS", "TK_SHORTCUT")
class DefaultWeightsImport:
@classmethod
def INPUT_TYPES(s):
return {
}
RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
RETURN_NAMES = WEIGHTS_RETURN_NAMES
FUNCTION = "load_weights"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
def load_weights(self):
weights = ControlWeightsImport.default()
return (weights, TimestepKeyframeGroupImport.default(TimestepKeyframeImport(control_weights=weights)))
class ScaledSoftMaskedUniversalWeightsImport:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"mask": ("MASK", ),
"min_base_multiplier": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}, ),
"max_base_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}, ),
#"lock_min": ("BOOLEAN", {"default": False}, ),
#"lock_max": ("BOOLEAN", {"default": False}, ),
},
}
RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
RETURN_NAMES = WEIGHTS_RETURN_NAMES
FUNCTION = "load_weights"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
def load_weights(self, mask: Tensor, min_base_multiplier: float, max_base_multiplier: float, lock_min=False, lock_max=False):
# normalize mask
mask = mask.clone()
x_min = 0.0 if lock_min else mask.min()
x_max = 1.0 if lock_max else mask.max()
if x_min == x_max:
mask = torch.ones_like(mask) * max_base_multiplier
else:
mask = linear_conversion(mask, x_min, x_max, min_base_multiplier, max_base_multiplier)
weights = ControlWeightsImport.universal_mask(weight_mask=mask)
return (weights, TimestepKeyframeGroupImport.default(TimestepKeyframeImport(control_weights=weights)))
class ScaledSoftUniversalWeightsImport:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"base_multiplier": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 1.0, "step": 0.001}, ),
"flip_weights": ("BOOLEAN", {"default": False}),
},
}
RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
RETURN_NAMES = WEIGHTS_RETURN_NAMES
FUNCTION = "load_weights"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
def load_weights(self, base_multiplier, flip_weights):
weights = ControlWeightsImport.universal(base_multiplier=base_multiplier, flip_weights=flip_weights)
return (weights, TimestepKeyframeGroupImport.default(TimestepKeyframeImport(control_weights=weights)))
class SoftControlNetWeightsImport:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"weight_00": ("FLOAT", {"default": 0.09941396206337118, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_01": ("FLOAT", {"default": 0.12050177219802567, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_02": ("FLOAT", {"default": 0.14606275417942507, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_03": ("FLOAT", {"default": 0.17704576264172736, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_04": ("FLOAT", {"default": 0.214600924414215, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_05": ("FLOAT", {"default": 0.26012233262329093, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_06": ("FLOAT", {"default": 0.3152997971191405, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_07": ("FLOAT", {"default": 0.3821815722656249, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_08": ("FLOAT", {"default": 0.4632503906249999, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_09": ("FLOAT", {"default": 0.561515625, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_10": ("FLOAT", {"default": 0.6806249999999999, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_11": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_12": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"flip_weights": ("BOOLEAN", {"default": False}),
},
}
RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
RETURN_NAMES = WEIGHTS_RETURN_NAMES
FUNCTION = "load_weights"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/ControlNet"
def load_weights(self, weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
weight_07, weight_08, weight_09, weight_10, weight_11, weight_12, flip_weights):
weights = [weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
weight_07, weight_08, weight_09, weight_10, weight_11, weight_12]
weights = ControlWeightsImport.controlnet(weights, flip_weights=flip_weights)
return (weights, TimestepKeyframeGroupImport.default(TimestepKeyframeImport(control_weights=weights)))
class CustomControlNetWeightsImport:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"weight_00": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_01": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_02": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_04": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_05": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_06": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_07": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_08": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_09": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_10": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_11": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_12": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"flip_weights": ("BOOLEAN", {"default": False}),
}
}
RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
RETURN_NAMES = WEIGHTS_RETURN_NAMES
FUNCTION = "load_weights"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/ControlNet"
def load_weights(self, weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
weight_07, weight_08, weight_09, weight_10, weight_11, weight_12, flip_weights):
weights = [weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
weight_07, weight_08, weight_09, weight_10, weight_11, weight_12]
weights = ControlWeightsImport.controlnet(weights, flip_weights=flip_weights)
return (weights, TimestepKeyframeGroupImport.default(TimestepKeyframeImport(control_weights=weights)))
class SoftT2IAdapterWeightsImport:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"weight_00": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_01": ("FLOAT", {"default": 0.62, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_02": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
"flip_weights": ("BOOLEAN", {"default": False}),
},
}
RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
RETURN_NAMES = WEIGHTS_RETURN_NAMES
FUNCTION = "load_weights"
CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/T2IAdapter"
def load_weights(self, weight_00, weight_01, weight_02, weight_03, flip_weights):
weights = [weight_00, weight_01, weight_02, weight_03] | weights = get_properly_arranged_t2i_weights(weights) | 3 | 2023-11-11 01:26:26+00:00 | 8k |
x0rzavi/github-readme-terminal | gifos/utils/fetch_github_stats.py | [
{
"identifier": "calc_github_rank",
"path": "gifos/utils/calc_github_rank.py",
"snippet": "def calc_github_rank(\n all_commits: bool,\n commits: int,\n prs: int,\n issues: int,\n reviews: int,\n stars: int,\n followers: int,\n) -> GithubUserRank:\n \"\"\"Calculate the GitHub rank... | import os
import requests
import sys
from dotenv import load_dotenv
from gifos.utils.calc_github_rank import calc_github_rank
from gifos.utils.schemas.github_user_stats import GithubUserStats | 3,685 | """
REST_API_URL = f"https://api.github.com/search/commits?q=author:{user_name}"
headers = {
"Content-Type": "application/json",
"User-Agent": "x0rzavi",
"Accept": "application/vnd.github+json",
"Authorization": f"token {GITHUB_TOKEN}",
}
response = requests.get(REST_API_URL, headers=headers)
if response.status_code == 200:
json_obj = response.json()
total_commits_all_time = json_obj["total_count"]
print(f"INFO: Total commits fetched for {user_name}")
return total_commits_all_time
else:
print(f"ERROR: {response.status_code}")
return None
def fetch_github_stats(
user_name: str, ignore_repos: list = None, include_all_commits: bool = False
) -> GithubUserStats:
"""Fetch GitHub statistics for a user.
This function fetches various statistics for a GitHub user. The function uses the
`GITHUB_TOKEN` environment variable for authentication.
:param user_name: The username of the user to fetch statistics for.
:type user_name: str
:param ignore_repos: A list of repository names to ignore when fetching statistics.
If not provided, all repositories are included.
:type ignore_repos: list, optional
:param include_all_commits: A boolean indicating whether to include all commits when
calculating the user's GitHub rank. If False, only commits from the last year
are included.
:type include_all_commits: bool, optional
:return: A `GithubUserStats` object containing the fetched statistics if the request
is successful, otherwise None.
:rtype: GithubUserStats or None
"""
if not GITHUB_TOKEN:
print("ERROR: Please provide GITHUB_TOKEN")
sys.exit(1)
repo_end_cursor = None
total_stargazers = 0
languages_dict = {}
def update_languages(languages, languages_dict):
for language in languages:
language_name = language["node"]["name"]
language_size = language["size"]
languages_dict[language_name] = (
languages_dict.get(language_name, 0) + language_size
)
def process_repo(repos, ignore_repos, languages_dict):
total_stargazers = 0
for repo in repos:
if repo["name"] not in (ignore_repos or []):
total_stargazers += repo["stargazerCount"]
if not repo["isFork"]:
update_languages(repo["languages"]["edges"], languages_dict)
return total_stargazers
while True: # paginate repository stats
repo_stats = fetch_repo_stats(user_name, repo_end_cursor)
if repo_stats:
total_stargazers = process_repo(
repo_stats["nodes"], ignore_repos, languages_dict
)
if repo_stats["pageInfo"]["hasNextPage"]:
repo_end_cursor = repo_stats["pageInfo"]["endCursor"]
else:
break
else:
break
total_commits_all_time = fetch_total_commits(user_name) # fetch only once
total_languages_size = sum(languages_dict.values())
languages_percentage = {
language: round((size / total_languages_size) * 100, 2)
for language, size in languages_dict.items()
}
languages_sorted = sorted(
languages_percentage.items(), key=lambda n: n[1], reverse=True
)
user_stats = fetch_user_stats(user_name)
if user_stats:
if user_stats["pullRequests"]["totalCount"] > 0:
pull_requests_merge_percentage = round(
(user_stats["mergedPullRequests"]["totalCount"] /
user_stats["pullRequests"]["totalCount"]) * 100,
2
)
else:
pull_requests_merge_percentage = 0
user_details = GithubUserStats(
account_name=user_stats["name"],
total_followers=user_stats["followers"]["totalCount"],
total_stargazers=total_stargazers,
total_issues=user_stats["issues"]["totalCount"],
total_commits_all_time=total_commits_all_time,
total_commits_last_year=(
user_stats["contributionsCollection"]["restrictedContributionsCount"]
+ user_stats["contributionsCollection"]["totalCommitContributions"]
),
total_pull_requests_made=user_stats["pullRequests"]["totalCount"],
total_pull_requests_merged=user_stats["mergedPullRequests"]["totalCount"],
pull_requests_merge_percentage=pull_requests_merge_percentage,
total_pull_requests_reviewed=user_stats["contributionsCollection"][
"totalPullRequestReviewContributions"
],
total_repo_contributions=user_stats["repositoriesContributedTo"][
"totalCount"
],
languages_sorted=languages_sorted[:6], # top 6 languages
| # TODO
# [] Language colors
# [] Profile image ascii art
# [] Optimize code
# [] Optimize API calls
# [] Catch errors
# [] Retry on error
"""This module contains a function for fetching a GitHub user's statistics."""
load_dotenv()
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
GRAPHQL_ENDPOINT = "https://api.github.com/graphql"
def fetch_repo_stats(user_name: str, repo_end_cursor: str = None) -> dict:
"""Fetch statistics for a user's repositories.
This function sends a GraphQL query to the GitHub API to fetch statistics for a
user's repositories. The function uses the `GITHUB_TOKEN` environment variable for
authentication and the `GRAPHQL_ENDPOINT` constant for the API endpoint.
:param user_name: The username of the user to fetch statistics for.
:type user_name: str
:param repo_end_cursor: The end cursor for pagination. If not provided, the function
fetches statistics from the beginning.
:type repo_end_cursor: str, optional
:return: A dictionary containing the fetched statistics if the request is
successful, otherwise None.
:rtype: dict or None
"""
query = """
query repoInfo(
$user_name: String!
$repo_end_cursor: String
) {
user(login: $user_name) {
repositories (
first: 100,
after: $repo_end_cursor
orderBy: { field: STARGAZERS, direction: DESC }
ownerAffiliations: OWNER
) {
totalCount
nodes {
name
isFork
stargazerCount
languages(
first: 10
orderBy: { field: SIZE, direction: DESC }
) {
edges {
node {
name
# color
}
size
}
}
}
pageInfo {
endCursor
hasNextPage
}
}
}
# rateLimit {
# cost
# limit
# remaining
# used
# resetAt
# }
}
"""
headers = {"Authorization": f"bearer {GITHUB_TOKEN}"}
variables = {"user_name": user_name, "repo_end_cursor": repo_end_cursor}
response = requests.post(
GRAPHQL_ENDPOINT, json={"query": query, "variables": variables}, headers=headers
)
if response.status_code == 200:
json_obj = response.json()
if "errors" in json_obj:
print(f"ERROR: {json_obj['errors']}")
return None
else:
print(f"INFO: Repository details fetched for {user_name}")
return json_obj["data"]["user"]["repositories"]
else:
print(f"ERROR: {response.status_code}")
return None
def fetch_user_stats(user_name: str) -> dict:
"""Fetch statistics for a GitHub user.
This function sends a GraphQL query to the GitHub API to fetch statistics for a
GitHub user. The function uses the `GITHUB_TOKEN` environment variable for
authentication and the `GRAPHQL_ENDPOINT` constant for the API endpoint.
:param user_name: The username of the user to fetch statistics for.
:type user_name: str
:return: A dictionary containing the fetched statistics if the request is
successful, otherwise None.
:rtype: dict or None
"""
query = """
query userInfo($user_name: String!) {
user(login: $user_name) {
name
followers (first: 1) {
totalCount
}
repositoriesContributedTo (
first: 1
contributionTypes: [COMMIT, ISSUE, PULL_REQUEST, REPOSITORY]
) {
totalCount
}
contributionsCollection {
# contributionCalendar {
# totalContributions
# }
totalCommitContributions
restrictedContributionsCount
totalPullRequestReviewContributions
}
issues(first: 1) {
totalCount
}
pullRequests(first: 1) {
totalCount
}
mergedPullRequests: pullRequests(states: MERGED, first: 1) {
totalCount
}
}
# rateLimit {
# cost
# limit
# remaining
# used
# resetAt
# }
}
"""
headers = {"Authorization": f"bearer {GITHUB_TOKEN}"}
variables = {"user_name": user_name}
response = requests.post(
GRAPHQL_ENDPOINT, json={"query": query, "variables": variables}, headers=headers
)
if response.status_code == 200:
json_obj = response.json()
if "errors" in json_obj:
print(f"ERROR: {json_obj['errors']}")
return None
else:
print(f"INFO: User details fetched for {user_name}")
return json_obj["data"]["user"]
else:
print(f"ERROR: {response.status_code}")
return None
# Reference: https://github.com/anuraghazra/github-readme-stats/blob/23472f40e81170ba452c38a99abc674db0000ce6/src/fetchers/stats-fetcher.js#L170
def fetch_total_commits(user_name: str) -> int:
"""Fetch the total number of commits (lifetime) made by a GitHub user.
This function sends a GET request to the GitHub REST API to fetch the total number
of commits made by a GitHub user. The function uses the `GITHUB_TOKEN` environment
variable for authentication.
:param user_name: The username of the user to fetch the total number of commits for.
:type user_name: str
:return: The total number of commits made by the user if the request is successful,
otherwise None.
:rtype: int or None
"""
REST_API_URL = f"https://api.github.com/search/commits?q=author:{user_name}"
headers = {
"Content-Type": "application/json",
"User-Agent": "x0rzavi",
"Accept": "application/vnd.github+json",
"Authorization": f"token {GITHUB_TOKEN}",
}
response = requests.get(REST_API_URL, headers=headers)
if response.status_code == 200:
json_obj = response.json()
total_commits_all_time = json_obj["total_count"]
print(f"INFO: Total commits fetched for {user_name}")
return total_commits_all_time
else:
print(f"ERROR: {response.status_code}")
return None
def fetch_github_stats(
user_name: str, ignore_repos: list = None, include_all_commits: bool = False
) -> GithubUserStats:
"""Fetch GitHub statistics for a user.
This function fetches various statistics for a GitHub user. The function uses the
`GITHUB_TOKEN` environment variable for authentication.
:param user_name: The username of the user to fetch statistics for.
:type user_name: str
:param ignore_repos: A list of repository names to ignore when fetching statistics.
If not provided, all repositories are included.
:type ignore_repos: list, optional
:param include_all_commits: A boolean indicating whether to include all commits when
calculating the user's GitHub rank. If False, only commits from the last year
are included.
:type include_all_commits: bool, optional
:return: A `GithubUserStats` object containing the fetched statistics if the request
is successful, otherwise None.
:rtype: GithubUserStats or None
"""
if not GITHUB_TOKEN:
print("ERROR: Please provide GITHUB_TOKEN")
sys.exit(1)
repo_end_cursor = None
total_stargazers = 0
languages_dict = {}
def update_languages(languages, languages_dict):
for language in languages:
language_name = language["node"]["name"]
language_size = language["size"]
languages_dict[language_name] = (
languages_dict.get(language_name, 0) + language_size
)
def process_repo(repos, ignore_repos, languages_dict):
total_stargazers = 0
for repo in repos:
if repo["name"] not in (ignore_repos or []):
total_stargazers += repo["stargazerCount"]
if not repo["isFork"]:
update_languages(repo["languages"]["edges"], languages_dict)
return total_stargazers
while True: # paginate repository stats
repo_stats = fetch_repo_stats(user_name, repo_end_cursor)
if repo_stats:
total_stargazers = process_repo(
repo_stats["nodes"], ignore_repos, languages_dict
)
if repo_stats["pageInfo"]["hasNextPage"]:
repo_end_cursor = repo_stats["pageInfo"]["endCursor"]
else:
break
else:
break
total_commits_all_time = fetch_total_commits(user_name) # fetch only once
total_languages_size = sum(languages_dict.values())
languages_percentage = {
language: round((size / total_languages_size) * 100, 2)
for language, size in languages_dict.items()
}
languages_sorted = sorted(
languages_percentage.items(), key=lambda n: n[1], reverse=True
)
user_stats = fetch_user_stats(user_name)
if user_stats:
if user_stats["pullRequests"]["totalCount"] > 0:
pull_requests_merge_percentage = round(
(user_stats["mergedPullRequests"]["totalCount"] /
user_stats["pullRequests"]["totalCount"]) * 100,
2
)
else:
pull_requests_merge_percentage = 0
user_details = GithubUserStats(
account_name=user_stats["name"],
total_followers=user_stats["followers"]["totalCount"],
total_stargazers=total_stargazers,
total_issues=user_stats["issues"]["totalCount"],
total_commits_all_time=total_commits_all_time,
total_commits_last_year=(
user_stats["contributionsCollection"]["restrictedContributionsCount"]
+ user_stats["contributionsCollection"]["totalCommitContributions"]
),
total_pull_requests_made=user_stats["pullRequests"]["totalCount"],
total_pull_requests_merged=user_stats["mergedPullRequests"]["totalCount"],
pull_requests_merge_percentage=pull_requests_merge_percentage,
total_pull_requests_reviewed=user_stats["contributionsCollection"][
"totalPullRequestReviewContributions"
],
total_repo_contributions=user_stats["repositoriesContributedTo"][
"totalCount"
],
languages_sorted=languages_sorted[:6], # top 6 languages | user_rank=calc_github_rank( | 0 | 2023-11-17 06:21:18+00:00 | 8k |
Zaloog/kanban-python | src/kanban_python/controls.py | [
{
"identifier": "cfg",
"path": "src/kanban_python/config.py",
"snippet": "class KanbanConfig:\n def __init__(self, path=CONFIG_FILE_PATH) -> None:\n def __repr__(self) -> str:\n def save(self):\n def config(self) -> configparser.ConfigParser:\n def active_board(self) -> str:\n def acti... | from json import dump, load
from rich.pretty import pprint
from .config import (
cfg,
check_if_board_name_exists_in_config,
check_if_current_active_board_in_board_list,
delete_board_from_config,
get_json_path,
)
from .constants import (
DUMMY_DB,
KANBAN_BOARDS_PATH,
REPORT_FILE_NAME,
REPORT_FILE_PATH,
TASK_FILE_NAME,
)
from .interface import (
create_config_table,
create_github_like_report_table,
create_table,
input_ask_for_action,
input_ask_for_action_settings,
input_ask_for_change_board,
input_ask_for_delete_board,
input_ask_for_new_board_name,
input_ask_which_task_to_update,
input_ask_which_tasks_to_show,
input_change_column_settings,
input_change_done_limit_settings,
input_change_files_to_scan_settings,
input_change_footer_settings,
input_change_min_col_width_settings,
input_change_patterns_to_scan_settings,
input_confirm_add_todos_to_board,
input_confirm_delete_board,
input_confirm_set_board_active,
input_create_new_task,
input_update_task,
)
from .utils import (
check_board_name_valid,
check_if_done_col_leq_X,
check_if_there_are_visible_tasks_in_board,
check_scanner_files_valid,
check_scanner_patterns_valid,
console,
create_report_document,
current_time_to_str,
delete_json_file,
get_tag_id_choices,
move_first_done_task_to_archive,
scan_files,
scan_for_todos,
split_todo_in_tag_and_title,
) | 6,639 | if not path:
path = cfg.active_board_path
if path == "all":
board_dict = {
b: read_single_board(b_path) for b, b_path in cfg.kanban_boards_dict.items()
}
return board_dict
try:
data = read_single_board(path)
return data
except FileNotFoundError:
print(path)
console.print(f":warning: No [orange3]{TASK_FILE_NAME}[/] file here anymore.")
console.print("Please change to another board.")
change_kanban_board()
console.print(f"[red]Seems like the previous {TASK_FILE_NAME} file was deleted[/]")
console.print(f"Create new [orange3]{TASK_FILE_NAME}[/] file here.")
create_new_db()
return read_db()
def read_single_board(path):
with open(path, "r") as file:
data = load(file)
return data
# User Action Controls
#####################################################################################
# Get User Action
def get_user_action():
return input_ask_for_action()
# Action 1
def add_new_task_to_db():
new_task = input_create_new_task()
add_tasks_to_db(tasks=new_task)
# Action 2
def update_task_from_db():
db_data = read_db()
if not check_if_there_are_visible_tasks_in_board(db_data, cfg.vis_cols):
console.print(":cross_mark:[red]No Tasks available on this Kanban board[/]")
return
selected_id = input_ask_which_task_to_update(db_data)
updated_task = input_update_task(current_task=db_data[selected_id])
db_data[selected_id] = updated_task
while not check_if_done_col_leq_X(cfg=cfg, data=db_data):
first_task_id, archive_task = move_first_done_task_to_archive(data=db_data)
db_data[first_task_id] = archive_task
save_db(data=db_data)
# Action 3
def change_kanban_board():
boards_dict = read_db(path="all")
new_active_board = input_ask_for_change_board(boards_dict)
cfg.active_board = new_active_board
# Action 4
def show_tasks():
db_data = read_db()
choices = get_tag_id_choices(db_data, cfg.vis_cols)
selection_criteria = input_ask_which_tasks_to_show(choices)
for i, task in db_data.items():
if selection_criteria in [i, task["Tag"]]:
console.print(
20 * "[bold blue]#[/]" + f" Task {i} " + 20 * "[bold blue]#[/]"
)
pprint(
{
key: val
for key, val in task.items()
if key in ["Title", "Description", "Tag", "Status", "Due_Date"]
},
console=console,
expand_all=True,
)
# Action 5
def delete_kanban_board():
board_to_delete = input_ask_for_delete_board()
if input_confirm_delete_board(board_to_delete):
board_to_delete_path = cfg.kanban_boards_dict[board_to_delete]
delete_json_file(board_to_delete_path)
delete_board_from_config(board_to_delete)
def show():
if not cfg.kanban_boards:
console.print(":warning: [red]No Boards created yet[/]:warning:")
console.print("Use 'kanban init' to create a new kanban board.")
raise KeyboardInterrupt
if not check_if_current_active_board_in_board_list():
console.print(
"[yellow]Hmm, Something went wrong.[/] "
+ f"The active board '{cfg.active_board}' is not in the list of boards."
)
change_kanban_board()
show()
return
db_data = read_db()
table = create_table(data=db_data)
console.print(table)
# Scan Functionality
#####################################################################################
def add_todos_to_board():
files = scan_files(endings=cfg.scanned_files)
| from __future__ import annotations
# DB Controls
#####################################################################################
def create_new_db() -> None:
while True:
while True:
new_board_name = input_ask_for_new_board_name()
if check_board_name_valid(new_board_name):
break
console.print(f":warning: '{new_board_name}' is [red]not[/] a valid Name.")
if not check_if_board_name_exists_in_config(new_board_name):
break
console.print(
f":warning: Board '{new_board_name}' already exists, choose another Name."
)
cfg.kanban_boards_dict = new_board_name
# Options:
# 1. ~/.kanban-python/<BOARDNAME>.json
# 2. ~/.kanban-python/kanban_boards/<BOARDNAME>.json
# 3. ~/.kanban-python/kanban_boards/<BOARDNAME>/pykanban.json <- THIS
# 4. ~/.kanban-python/kanban_boards/<BOARDNAME>/<BOARDNAME>.json
new_db_path = KANBAN_BOARDS_PATH / new_board_name
if not new_db_path.exists():
new_db_path.mkdir()
with open(get_json_path(new_board_name), "w", encoding="utf-8") as f:
dump(DUMMY_DB, f, ensure_ascii=False, indent=4)
console.print(
f"Created new [orange3]{TASK_FILE_NAME}[/] file at "
+ f"[orange3]{KANBAN_BOARDS_PATH / new_board_name}[/] to save tasks."
)
if input_confirm_set_board_active(name=new_board_name):
cfg.active_board = new_board_name
def save_db(data):
path = cfg.active_board_path
with open(path, "w", encoding="utf-8") as f:
dump(data, f, ensure_ascii=False, indent=4)
def add_tasks_to_db(tasks: dict | list[dict]) -> None:
db_data = read_db()
if isinstance(tasks, dict):
new_id = str(max(int(i) for i in db_data.keys()) + 1)
db_data[new_id] = tasks
else:
for task in tasks:
new_id = str(max(int(i) for i in db_data.keys()) + 1)
db_data[new_id] = task
save_db(data=db_data)
def read_db(path: str = None) -> dict:
if not path:
path = cfg.active_board_path
if path == "all":
board_dict = {
b: read_single_board(b_path) for b, b_path in cfg.kanban_boards_dict.items()
}
return board_dict
try:
data = read_single_board(path)
return data
except FileNotFoundError:
print(path)
console.print(f":warning: No [orange3]{TASK_FILE_NAME}[/] file here anymore.")
console.print("Please change to another board.")
change_kanban_board()
console.print(f"[red]Seems like the previous {TASK_FILE_NAME} file was deleted[/]")
console.print(f"Create new [orange3]{TASK_FILE_NAME}[/] file here.")
create_new_db()
return read_db()
def read_single_board(path):
with open(path, "r") as file:
data = load(file)
return data
# User Action Controls
#####################################################################################
# Get User Action
def get_user_action():
return input_ask_for_action()
# Action 1
def add_new_task_to_db():
new_task = input_create_new_task()
add_tasks_to_db(tasks=new_task)
# Action 2
def update_task_from_db():
db_data = read_db()
if not check_if_there_are_visible_tasks_in_board(db_data, cfg.vis_cols):
console.print(":cross_mark:[red]No Tasks available on this Kanban board[/]")
return
selected_id = input_ask_which_task_to_update(db_data)
updated_task = input_update_task(current_task=db_data[selected_id])
db_data[selected_id] = updated_task
while not check_if_done_col_leq_X(cfg=cfg, data=db_data):
first_task_id, archive_task = move_first_done_task_to_archive(data=db_data)
db_data[first_task_id] = archive_task
save_db(data=db_data)
# Action 3
def change_kanban_board():
boards_dict = read_db(path="all")
new_active_board = input_ask_for_change_board(boards_dict)
cfg.active_board = new_active_board
# Action 4
def show_tasks():
db_data = read_db()
choices = get_tag_id_choices(db_data, cfg.vis_cols)
selection_criteria = input_ask_which_tasks_to_show(choices)
for i, task in db_data.items():
if selection_criteria in [i, task["Tag"]]:
console.print(
20 * "[bold blue]#[/]" + f" Task {i} " + 20 * "[bold blue]#[/]"
)
pprint(
{
key: val
for key, val in task.items()
if key in ["Title", "Description", "Tag", "Status", "Due_Date"]
},
console=console,
expand_all=True,
)
# Action 5
def delete_kanban_board():
board_to_delete = input_ask_for_delete_board()
if input_confirm_delete_board(board_to_delete):
board_to_delete_path = cfg.kanban_boards_dict[board_to_delete]
delete_json_file(board_to_delete_path)
delete_board_from_config(board_to_delete)
def show():
if not cfg.kanban_boards:
console.print(":warning: [red]No Boards created yet[/]:warning:")
console.print("Use 'kanban init' to create a new kanban board.")
raise KeyboardInterrupt
if not check_if_current_active_board_in_board_list():
console.print(
"[yellow]Hmm, Something went wrong.[/] "
+ f"The active board '{cfg.active_board}' is not in the list of boards."
)
change_kanban_board()
show()
return
db_data = read_db()
table = create_table(data=db_data)
console.print(table)
# Scan Functionality
#####################################################################################
def add_todos_to_board():
files = scan_files(endings=cfg.scanned_files) | todos = scan_for_todos(file_paths=files, patterns=cfg.scanned_patterns) | 27 | 2023-11-11 14:43:55+00:00 | 8k |
AMAAI-Lab/mustango | diffusers/src/diffusers/loaders.py | [
{
"identifier": "LoRAAttnProcessor",
"path": "diffusers/src/diffusers/models/attention_processor.py",
"snippet": "class LoRAAttnProcessor(nn.Module):\n def __init__(self, hidden_size, cross_attention_dim=None, rank=4):\n super().__init__()\n\n self.hidden_size = hidden_size\n sel... | import os
import torch
import safetensors
from collections import defaultdict
from typing import Callable, Dict, List, Optional, Union
from .models.attention_processor import LoRAAttnProcessor
from .utils import (
DIFFUSERS_CACHE,
HF_HUB_OFFLINE,
_get_model_file,
deprecate,
is_safetensors_available,
is_transformers_available,
logging,
)
from transformers import PreTrainedModel, PreTrainedTokenizer | 4,281 | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
if is_safetensors_available():
if is_transformers_available():
logger = logging.get_logger(__name__)
LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
TEXT_INVERSION_NAME = "learned_embeds.bin"
TEXT_INVERSION_NAME_SAFE = "learned_embeds.safetensors"
class AttnProcsLayers(torch.nn.Module):
def __init__(self, state_dict: Dict[str, torch.Tensor]):
super().__init__()
self.layers = torch.nn.ModuleList(state_dict.values())
self.mapping = dict(enumerate(state_dict.keys()))
self.rev_mapping = {v: k for k, v in enumerate(state_dict.keys())}
# we add a hook to state_dict() and load_state_dict() so that the
# naming fits with `unet.attn_processors`
def map_to(module, state_dict, *args, **kwargs):
new_state_dict = {}
for key, value in state_dict.items():
num = int(key.split(".")[1]) # 0 is always "layers"
new_key = key.replace(f"layers.{num}", module.mapping[num])
new_state_dict[new_key] = value
return new_state_dict
def map_from(module, state_dict, *args, **kwargs):
all_keys = list(state_dict.keys())
for key in all_keys:
replace_key = key.split(".processor")[0] + ".processor"
new_key = key.replace(replace_key, f"layers.{module.rev_mapping[replace_key]}")
state_dict[new_key] = state_dict[key]
del state_dict[key]
self._register_state_dict_hook(map_to)
self._register_load_state_dict_pre_hook(map_from, with_module=True)
class UNet2DConditionLoadersMixin:
def load_attn_procs(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs):
r"""
Load pretrained attention processor layers into `UNet2DConditionModel`. Attention processor layers have to be
defined in
[cross_attention.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py)
and be a `torch.nn.Module` class.
<Tip warning={true}>
This function is experimental and might change in the future.
</Tip>
Parameters:
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
Can be either:
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
Valid model ids should have an organization name, like `google/ddpm-celebahq-256`.
- A path to a *directory* containing model weights saved using [`~ModelMixin.save_config`], e.g.,
`./my_model_directory/`.
- A [torch state
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
cache_dir (`Union[str, os.PathLike]`, *optional*):
Path to a directory in which a downloaded pretrained model configuration should be cached if the
standard cache should not be used.
force_download (`bool`, *optional*, defaults to `False`):
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
cached versions if they exist.
resume_download (`bool`, *optional*, defaults to `False`):
Whether or not to delete incompletely received files. Will attempt to resume the download if such a
file exists.
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
local_files_only(`bool`, *optional*, defaults to `False`):
Whether or not to only look at local files (i.e., do not try to download the model).
use_auth_token (`str` or *bool*, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `diffusers-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
identifier allowed by git.
subfolder (`str`, *optional*, defaults to `""`):
In case the relevant files are located inside a subfolder of the model repo (either remote in
huggingface.co or downloaded locally), you can specify the folder name here.
mirror (`str`, *optional*):
Mirror source to accelerate downloads in China. If you are from China and have an accessibility
problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety.
Please refer to the mirror site for more information.
<Tip>
It is required to be logged in (`huggingface-cli login`) when you want to use private or [gated
models](https://huggingface.co/docs/hub/models-gated#gated-models).
</Tip>
"""
| # 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.
if is_safetensors_available():
if is_transformers_available():
logger = logging.get_logger(__name__)
LORA_WEIGHT_NAME = "pytorch_lora_weights.bin"
LORA_WEIGHT_NAME_SAFE = "pytorch_lora_weights.safetensors"
TEXT_INVERSION_NAME = "learned_embeds.bin"
TEXT_INVERSION_NAME_SAFE = "learned_embeds.safetensors"
class AttnProcsLayers(torch.nn.Module):
def __init__(self, state_dict: Dict[str, torch.Tensor]):
super().__init__()
self.layers = torch.nn.ModuleList(state_dict.values())
self.mapping = dict(enumerate(state_dict.keys()))
self.rev_mapping = {v: k for k, v in enumerate(state_dict.keys())}
# we add a hook to state_dict() and load_state_dict() so that the
# naming fits with `unet.attn_processors`
def map_to(module, state_dict, *args, **kwargs):
new_state_dict = {}
for key, value in state_dict.items():
num = int(key.split(".")[1]) # 0 is always "layers"
new_key = key.replace(f"layers.{num}", module.mapping[num])
new_state_dict[new_key] = value
return new_state_dict
def map_from(module, state_dict, *args, **kwargs):
all_keys = list(state_dict.keys())
for key in all_keys:
replace_key = key.split(".processor")[0] + ".processor"
new_key = key.replace(replace_key, f"layers.{module.rev_mapping[replace_key]}")
state_dict[new_key] = state_dict[key]
del state_dict[key]
self._register_state_dict_hook(map_to)
self._register_load_state_dict_pre_hook(map_from, with_module=True)
class UNet2DConditionLoadersMixin:
def load_attn_procs(self, pretrained_model_name_or_path_or_dict: Union[str, Dict[str, torch.Tensor]], **kwargs):
r"""
Load pretrained attention processor layers into `UNet2DConditionModel`. Attention processor layers have to be
defined in
[cross_attention.py](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py)
and be a `torch.nn.Module` class.
<Tip warning={true}>
This function is experimental and might change in the future.
</Tip>
Parameters:
pretrained_model_name_or_path_or_dict (`str` or `os.PathLike` or `dict`):
Can be either:
- A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co.
Valid model ids should have an organization name, like `google/ddpm-celebahq-256`.
- A path to a *directory* containing model weights saved using [`~ModelMixin.save_config`], e.g.,
`./my_model_directory/`.
- A [torch state
dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).
cache_dir (`Union[str, os.PathLike]`, *optional*):
Path to a directory in which a downloaded pretrained model configuration should be cached if the
standard cache should not be used.
force_download (`bool`, *optional*, defaults to `False`):
Whether or not to force the (re-)download of the model weights and configuration files, overriding the
cached versions if they exist.
resume_download (`bool`, *optional*, defaults to `False`):
Whether or not to delete incompletely received files. Will attempt to resume the download if such a
file exists.
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
local_files_only(`bool`, *optional*, defaults to `False`):
Whether or not to only look at local files (i.e., do not try to download the model).
use_auth_token (`str` or *bool*, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
when running `diffusers-cli login` (stored in `~/.huggingface`).
revision (`str`, *optional*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
identifier allowed by git.
subfolder (`str`, *optional*, defaults to `""`):
In case the relevant files are located inside a subfolder of the model repo (either remote in
huggingface.co or downloaded locally), you can specify the folder name here.
mirror (`str`, *optional*):
Mirror source to accelerate downloads in China. If you are from China and have an accessibility
problem, you can set this option to resolve it. Note that we do not guarantee the timeliness or safety.
Please refer to the mirror site for more information.
<Tip>
It is required to be logged in (`huggingface-cli login`) when you want to use private or [gated
models](https://huggingface.co/docs/hub/models-gated#gated-models).
</Tip>
"""
| cache_dir = kwargs.pop("cache_dir", DIFFUSERS_CACHE) | 2 | 2023-11-14 23:29:31+00:00 | 8k |
ai-forever/Kandinsky-3 | kandinsky3/inpainting_pipeline.py | [
{
"identifier": "UNet",
"path": "kandinsky3/model/unet.py",
"snippet": "class UNet(nn.Module):\n\n def __init__(self,\n model_channels,\n init_channels=None,\n num_channels=3,\n out_channels=4,\n time_embed_dim=None,\n ... | from typing import Optional, Union, List
from tqdm import tqdm
from PIL import Image, ImageDraw, ImageFont
from torch import einsum
from einops import repeat
from kandinsky3.model.unet import UNet
from kandinsky3.movq import MoVQ
from kandinsky3.condition_encoders import T5TextConditionEncoder
from kandinsky3.condition_processors import T5TextConditionProcessor
from kandinsky3.model.diffusion import BaseDiffusion, get_named_beta_schedule
from kandinsky3.utils import resize_image_for_diffusion, resize_mask_for_diffusion
import PIL
import io
import os
import math
import random
import omegaconf
import numpy as np
import pandas as pd
import torch
import torchvision.transforms as T | 4,724 |
class Kandinsky3InpaintingPipeline:
def __init__(
self,
device: Union[str, torch.device],
unet: UNet,
null_embedding: torch.Tensor,
t5_processor: T5TextConditionProcessor,
t5_encoder: T5TextConditionEncoder,
movq: MoVQ,
fp16: bool = True
):
self.device = device
self.fp16 = fp16
self.to_pil = T.ToPILImage()
self.to_tensor = T.ToTensor()
self.unet = unet
self.null_embedding = null_embedding
self.t5_processor = t5_processor
self.t5_encoder = t5_encoder
self.movq = movq
def shared_step(self, batch: dict) -> dict:
image = batch['image']
condition_model_input = batch['text']
negative_condition_model_input = batch['negative_text']
bs = image.shape[0]
masked_latent = None
mask = batch['mask']
if 'masked_image' in batch:
masked_latent = batch['masked_image']
elif self.unet.in_layer.in_channels == 9:
masked_latent = image.masked_fill((1 - mask).bool(), 0)
else:
raise ValueError()
masked_latent = self.movq.encode(masked_latent)
mask = torch.nn.functional.interpolate(mask, size=(masked_latent.shape[2], masked_latent.shape[3]))
with torch.cuda.amp.autocast(enabled=self.fp16):
context, context_mask = self.t5_encoder(condition_model_input)
if negative_condition_model_input is not None:
negative_context, negative_context_mask = self.t5_encoder(negative_condition_model_input)
else:
negative_context, negative_context_mask = None, None
if self.fp16:
mask = mask.to(torch.float16)
masked_latent = masked_latent.to(torch.float16)
return {
'context': context,
'context_mask': context_mask,
'negative_context': negative_context,
'negative_context_mask': negative_context_mask,
'image': image,
'masked_latent': masked_latent,
'mask': mask
}
def prepare_batch(
self,
text: str,
negative_text: str,
image: PIL.Image.Image,
mask: np.ndarray,
) -> dict:
condition_model_input, negative_condition_model_input = self.t5_processor.encode(text=text, negative_text=negative_text)
batch = {
|
class Kandinsky3InpaintingPipeline:
def __init__(
self,
device: Union[str, torch.device],
unet: UNet,
null_embedding: torch.Tensor,
t5_processor: T5TextConditionProcessor,
t5_encoder: T5TextConditionEncoder,
movq: MoVQ,
fp16: bool = True
):
self.device = device
self.fp16 = fp16
self.to_pil = T.ToPILImage()
self.to_tensor = T.ToTensor()
self.unet = unet
self.null_embedding = null_embedding
self.t5_processor = t5_processor
self.t5_encoder = t5_encoder
self.movq = movq
def shared_step(self, batch: dict) -> dict:
image = batch['image']
condition_model_input = batch['text']
negative_condition_model_input = batch['negative_text']
bs = image.shape[0]
masked_latent = None
mask = batch['mask']
if 'masked_image' in batch:
masked_latent = batch['masked_image']
elif self.unet.in_layer.in_channels == 9:
masked_latent = image.masked_fill((1 - mask).bool(), 0)
else:
raise ValueError()
masked_latent = self.movq.encode(masked_latent)
mask = torch.nn.functional.interpolate(mask, size=(masked_latent.shape[2], masked_latent.shape[3]))
with torch.cuda.amp.autocast(enabled=self.fp16):
context, context_mask = self.t5_encoder(condition_model_input)
if negative_condition_model_input is not None:
negative_context, negative_context_mask = self.t5_encoder(negative_condition_model_input)
else:
negative_context, negative_context_mask = None, None
if self.fp16:
mask = mask.to(torch.float16)
masked_latent = masked_latent.to(torch.float16)
return {
'context': context,
'context_mask': context_mask,
'negative_context': negative_context,
'negative_context_mask': negative_context_mask,
'image': image,
'masked_latent': masked_latent,
'mask': mask
}
def prepare_batch(
self,
text: str,
negative_text: str,
image: PIL.Image.Image,
mask: np.ndarray,
) -> dict:
condition_model_input, negative_condition_model_input = self.t5_processor.encode(text=text, negative_text=negative_text)
batch = { | 'image': self.to_tensor(resize_image_for_diffusion(image.convert("RGB"))) * 2 - 1, | 6 | 2023-11-13 10:16:04+00:00 | 8k |
spfrommer/torchexplorer | torchexplorer/render/layout.py | [
{
"identifier": "utils",
"path": "torchexplorer/utils.py",
"snippet": "def iter_not_none(iterable: Iterable[Any]) -> Iterator[Any]:\ndef enum_not_none(iterable: Iterable[Any]) -> Iterator[tuple[int, Any]]:\ndef interleave(l1: list[Any], l2: list[Any]) -> list[Any]:\ndef list_add(l1: list[float], l2: lis... | import copy
import html
import json
import string
import numpy as np
import networkx as nx
from typing import Optional, Union
from subprocess import Popen, PIPE
from torchexplorer import utils
from torchexplorer import core
from torchexplorer.components.tooltip import Tooltip
from torchexplorer.core import ModuleInvocationHistograms, ModuleInvocationStructure
from torchexplorer.structure.structure import is_input_node, is_io_node
from torchexplorer.render.structs import (
EdgeLayout, TooltipLayout, NodeLayout
) | 4,089 | )[parent_invocation_id][io_index]
_add_tooltip(layout, Tooltip.create_io(io_tensor_shape))
has_io_hists = parent_invocation_id in parent_metadata.invocation_hists
if has_io_hists:
hists = parent_metadata.invocation_hists[parent_invocation_id]
hist = (hists.input_hists if is_input else hists.output_hists)[io_index]
has_grad_hists = parent_invocation_id in parent_metadata.invocation_grad_hists
if has_grad_hists:
grad_hists = parent_metadata.invocation_grad_hists[parent_invocation_id]
grad_hist = (
grad_hists.input_hists if is_input else grad_hists.output_hists
)[io_index]
layout.invocation_hists = ModuleInvocationHistograms(
input_hists=[hist] if has_io_hists else [],
output_hists=[hist] if has_io_hists else []
)
layout.invocation_grad_hists = ModuleInvocationHistograms(
input_hists=[grad_hist] if has_grad_hists else [],
output_hists=[grad_hist] if has_grad_hists else []
)
def _layout_moduleinvocation_node(
layout: NodeLayout, parent_structure: ModuleInvocationStructure, object: dict
) -> ModuleInvocationStructure:
structure_id = int(object['structure_id'])
object_struct = parent_structure.get_inner_structure_from_id(structure_id)
assert object_struct is not None
if isinstance(object_struct.module, core.DummyAttachModule):
_add_tooltip(layout, Tooltip.create_attach(object_struct.module))
else:
_add_tooltip(layout, Tooltip.create_moduleinvocation(
object_struct.module, parent_structure.module, object_struct.invocation_id
))
metadata = object_struct.module_metadata()
if object_struct.invocation_id in metadata.invocation_hists:
layout.invocation_hists = (
metadata.invocation_hists[object_struct.invocation_id]
)
if object_struct.invocation_id in metadata.invocation_grad_hists:
layout.invocation_grad_hists = (
metadata.invocation_grad_hists[object_struct.invocation_id]
)
layout.shared_hists = metadata.shared_hists
return object_struct
def _add_tooltip(layout: NodeLayout, tooltip: Tooltip) -> None:
tooltip_title_size, tooltip_font_size = 14, 11
def _handle_string(str, truncate=False, title=False):
font_size = tooltip_title_size if title else tooltip_font_size
truncate_width = 70
return _truncate_string_width(str, font_size, truncate_width, truncate)
for i, key in enumerate(tooltip.keys):
tooltip.keys[i] = _handle_string(key, True)[0]
line_widths = [_handle_string(tooltip.title, False, True)[1]]
for key, val in zip(tooltip.keys, tooltip.vals):
line_widths.append(_handle_string(f'{key}{val}', False)[1])
tooltip_width = max(line_widths) * 0.95 + 20
tooltip_lines = 1 + len(tooltip.keys)
tooltip_height = 20 + (tooltip_font_size + 2) * tooltip_lines
tooltip_bl = [
layout.top_right_corner[0] + 20, _center(layout)[1] - tooltip_height / 2
]
tooltip_tr = [tooltip_bl[0] + tooltip_width, tooltip_bl[1] + tooltip_height]
layout.tooltip = TooltipLayout(
tooltip, bottom_left_corner=tooltip_bl, top_right_corner=tooltip_tr
)
def _process_graph(layout: NodeLayout):
layout_id_counter = 0
def process_graph_layout(
l: NodeLayout, parent_id: int, parent_stack: list[tuple[str, int]]
) -> list[int]:
nonlocal layout_id_counter
new_id = layout_id_counter
layout_id_counter += 1
assert l.display_name is not None
new_stack = parent_stack + [(l.display_name, new_id)]
child_ids = []
for inner_r in l.inner_graph_layouts:
child_ids += process_graph_layout(inner_r, new_id, new_stack)
l.id = new_id
l.parent_id = parent_id
l.parent_stack = new_stack
l.child_ids = child_ids
return [new_id] + child_ids
process_graph_layout(layout, -1, [])
def _translate_inner_layouts(layout: NodeLayout) -> None:
"""Translate visual components to be centered around the input node."""
target_input_pos = [0.0, 0.0] # Based on where vega spec expects input to be
input_centers = []
for l in layout.inner_graph_layouts:
if is_input_node(l.display_name):
input_centers.append(_center(l))
center = np.mean(np.array(input_centers), axis=0)
| from __future__ import annotations
def layout(
structure: ModuleInvocationStructure, cache: Optional[dict] = None
) -> tuple[NodeLayout, dict]:
name = structure.module.__class__.__name__
if is_io_node(name):
raise RuntimeError(f'Invalid module name: {name}')
layout = NodeLayout(display_name=name)
if cache is None:
_layout_into(layout, structure, None)
cache = {'cached_structure': structure}
else:
_layout_into(layout, structure, cache['cached_structure'])
_process_graph(layout)
return layout, cache
def _layout_into(
layout: NodeLayout,
structure: ModuleInvocationStructure,
cached_structure: Optional[ModuleInvocationStructure] = None
):
json_data = _get_graphviz_json_with_caching(structure, cached_structure)
for object in json_data['objects']:
draw_points = np.array(object['_draw_'][1]['points'])
draw_xs, draw_ys = draw_points[:, 0], draw_points[:, 1]
inner_layout = NodeLayout()
# Replace the attach module label
inner_layout.display_name = object['label'].replace('<>', ' ᴬ')
inner_layout.bottom_left_corner = [draw_xs.min(), draw_ys.min()]
inner_layout.top_right_corner = [draw_xs.max(), draw_ys.max()]
if is_io_node(object['label']):
_layout_io_node(inner_layout, structure, object)
else:
struct = _layout_moduleinvocation_node(inner_layout, structure, object)
_layout_into(inner_layout, struct, object['cached_structure'])
layout.inner_graph_layouts.append(inner_layout)
if 'edges' in json_data:
for edge in json_data['edges']:
layout.inner_graph_edges.append(EdgeLayout(
path_points=edge['_draw_'][-1]['points'],
arrowhead_points=edge['_hdraw_'][-1]['points'],
downstream_input_index=int(edge['downstream_input_index']),
upstream_output_index=int(edge['upstream_output_index']),
))
_translate_inner_layouts(layout)
def _layout_io_node(
layout: NodeLayout, parent_structure: ModuleInvocationStructure, object: dict
) -> None:
is_input = is_input_node(object['label'])
parent_metadata = parent_structure.module_metadata()
parent_invocation_id = parent_structure.invocation_id
io_index = int(object['name'].split(' ')[-1])
io_tensor_shape = (
parent_metadata.input_sizes if is_input else parent_metadata.output_sizes
)[parent_invocation_id][io_index]
_add_tooltip(layout, Tooltip.create_io(io_tensor_shape))
has_io_hists = parent_invocation_id in parent_metadata.invocation_hists
if has_io_hists:
hists = parent_metadata.invocation_hists[parent_invocation_id]
hist = (hists.input_hists if is_input else hists.output_hists)[io_index]
has_grad_hists = parent_invocation_id in parent_metadata.invocation_grad_hists
if has_grad_hists:
grad_hists = parent_metadata.invocation_grad_hists[parent_invocation_id]
grad_hist = (
grad_hists.input_hists if is_input else grad_hists.output_hists
)[io_index]
layout.invocation_hists = ModuleInvocationHistograms(
input_hists=[hist] if has_io_hists else [],
output_hists=[hist] if has_io_hists else []
)
layout.invocation_grad_hists = ModuleInvocationHistograms(
input_hists=[grad_hist] if has_grad_hists else [],
output_hists=[grad_hist] if has_grad_hists else []
)
def _layout_moduleinvocation_node(
layout: NodeLayout, parent_structure: ModuleInvocationStructure, object: dict
) -> ModuleInvocationStructure:
structure_id = int(object['structure_id'])
object_struct = parent_structure.get_inner_structure_from_id(structure_id)
assert object_struct is not None
if isinstance(object_struct.module, core.DummyAttachModule):
_add_tooltip(layout, Tooltip.create_attach(object_struct.module))
else:
_add_tooltip(layout, Tooltip.create_moduleinvocation(
object_struct.module, parent_structure.module, object_struct.invocation_id
))
metadata = object_struct.module_metadata()
if object_struct.invocation_id in metadata.invocation_hists:
layout.invocation_hists = (
metadata.invocation_hists[object_struct.invocation_id]
)
if object_struct.invocation_id in metadata.invocation_grad_hists:
layout.invocation_grad_hists = (
metadata.invocation_grad_hists[object_struct.invocation_id]
)
layout.shared_hists = metadata.shared_hists
return object_struct
def _add_tooltip(layout: NodeLayout, tooltip: Tooltip) -> None:
tooltip_title_size, tooltip_font_size = 14, 11
def _handle_string(str, truncate=False, title=False):
font_size = tooltip_title_size if title else tooltip_font_size
truncate_width = 70
return _truncate_string_width(str, font_size, truncate_width, truncate)
for i, key in enumerate(tooltip.keys):
tooltip.keys[i] = _handle_string(key, True)[0]
line_widths = [_handle_string(tooltip.title, False, True)[1]]
for key, val in zip(tooltip.keys, tooltip.vals):
line_widths.append(_handle_string(f'{key}{val}', False)[1])
tooltip_width = max(line_widths) * 0.95 + 20
tooltip_lines = 1 + len(tooltip.keys)
tooltip_height = 20 + (tooltip_font_size + 2) * tooltip_lines
tooltip_bl = [
layout.top_right_corner[0] + 20, _center(layout)[1] - tooltip_height / 2
]
tooltip_tr = [tooltip_bl[0] + tooltip_width, tooltip_bl[1] + tooltip_height]
layout.tooltip = TooltipLayout(
tooltip, bottom_left_corner=tooltip_bl, top_right_corner=tooltip_tr
)
def _process_graph(layout: NodeLayout):
layout_id_counter = 0
def process_graph_layout(
l: NodeLayout, parent_id: int, parent_stack: list[tuple[str, int]]
) -> list[int]:
nonlocal layout_id_counter
new_id = layout_id_counter
layout_id_counter += 1
assert l.display_name is not None
new_stack = parent_stack + [(l.display_name, new_id)]
child_ids = []
for inner_r in l.inner_graph_layouts:
child_ids += process_graph_layout(inner_r, new_id, new_stack)
l.id = new_id
l.parent_id = parent_id
l.parent_stack = new_stack
l.child_ids = child_ids
return [new_id] + child_ids
process_graph_layout(layout, -1, [])
def _translate_inner_layouts(layout: NodeLayout) -> None:
"""Translate visual components to be centered around the input node."""
target_input_pos = [0.0, 0.0] # Based on where vega spec expects input to be
input_centers = []
for l in layout.inner_graph_layouts:
if is_input_node(l.display_name):
input_centers.append(_center(l))
center = np.mean(np.array(input_centers), axis=0) | trans = utils.list_add(target_input_pos, [-center[0], -center[1]]) | 0 | 2023-11-13 05:56:04+00:00 | 8k |
namin/llm-verified-with-monte-carlo-tree-search | run_meta.py | [
{
"identifier": "args",
"path": "cmdline.py",
"snippet": "class CommonArguments:\ndef get_args():"
},
{
"identifier": "Node",
"path": "montecarlo/node.py",
"snippet": "class Node:\n def __init__(self, state):\n self.state = state\n self.win_value = 0\n self.policy... | from cmdline import args
from montecarlo.node import Node
from montecarlo.montecarlo import MonteCarlo
from lang_config import LANG
from lang import can_be_solution, filter_code
from coq import give_context, extract_lemma, lemma_statement, lemma_args, new_conclusion
from coq import score_func_code as uncached_score_func_code
from prompts import prompt, expansion_count, min_lines, check_func
from common import limit_depth, max_completion_depth
from common_cache import score_first, create_score_predicate, create_cached_func
from common_diversity import select_diversely_with_scores, DIVERSITY, limit
from common_interactive import ask_keep, diffprompt
from common_stats import stats
from common_bad_words import bad_words_ids
import re
import llm | 3,845 |
USE_HAMMER = args.use_hammer
EXTRACT_LEMMA_DEPTH = args.extract_lemma_depth
EXPLORE_MANY = args.explore_many
assert LANG=='Coq'
score_func_code, cache_stats = create_cached_func(uncached_score_func_code)
score_predicate = create_score_predicate(score_first)
class FocusNode:
def __init__(self, instructions, code, stack, lemma_counter):
(context, outlog) = give_context(code)
self.instructions = instructions
self.context = context
self.code = code
self.outlog = outlog
self.stack = stack
self.lemma_counter = lemma_counter
def update(self, text):
code = filter_code(text+"```").lstrip()
return FocusNode(self.instructions, code, self.stack, self.lemma_counter)
def update_lemma(self, goal, code):
name = self.lemma_name(self.lemma_counter)
statement = lemma_statement(goal)
args = lemma_args(goal)
last_lemma_index = list(re.finditer(r"Lemma|Theorem", code))[-1].start(0)
last_lemma = code[last_lemma_index:]
code = code[:last_lemma_index]
last_lemma += f" apply (@{name} {args}).\n"
stack = [last_lemma] + self.stack
code += "\n"
code += f"Lemma {name}: {statement}.\nProof.\n"
if USE_HAMMER:
code += "(* do not use induction, try using hammer *)\n"
print(f'Created Lemma {name}.')
return FocusNode(self.instructions, code, stack, self.lemma_counter+1)
def update_pop(self, text):
code = filter_code(text+"```").lstrip()
last_lemma = self.stack[0]
stack = self.stack[1:]
code += "\n\n"
code += last_lemma
return FocusNode(self.instructions, code, stack, self.lemma_counter)
def lemma_name(self, counter):
return "helper"+str(counter)
def text(self):
return f"""
<s>[INST] <<SYS>>
You are a Coq programmer that writes functional code and prove properties about it. When you are unsure of which lemmas to use, you use the `Search` function, for example `Search (0 < _).`. You can see the output of the Coq verifier in the Out section, and the context of the current proof, comprising the current goal and assumptions, in the Context section. The assumptions have names that you can use in your proofs.
{'''You can use Coq Hammer, including the tactic `hammer` to attempt to discharge a goal automatically.
To use Coq Hammer effectively, combine it with destruct using `;`: `destruct e1; destruct e2; hammer`.''' if USE_HAMMER else ''}
You take a single step and will be given feedback -- listen to the feedback in the instructions.
<</SYS>>
## Instructions
{self.instructions}
## Out
{limit(self.outlog)}
## Context
{limit(self.context)}
[/INST]
## Code
```{LANG}
{self.code}"""
def generate_complete(focus, montecarlo):
text = focus.text()
prev = text
if DIVERSITY:
texts, features = llm.generate(text, 5, return_hiddens=True, bad_words_ids=bad_words_ids)
scores = [score_func_code(text) for text in texts]
text, (score, code) = select_diversely_with_scores(texts, scores, score_predicate, features, montecarlo)
elif EXPLORE_MANY:
texts = llm.generate(text, 5, bad_words_ids=bad_words_ids)
idx = 0
for i in range(len(texts)):
if score_predicate(score_func_code(texts[i])):
idx = i
break
text = texts[idx]
score, code = score_func_code(text)
else:
texts = llm.generate(text, 1, bad_words_ids=bad_words_ids)
text = texts[0]
score, code = score_func_code(text)
|
USE_HAMMER = args.use_hammer
EXTRACT_LEMMA_DEPTH = args.extract_lemma_depth
EXPLORE_MANY = args.explore_many
assert LANG=='Coq'
score_func_code, cache_stats = create_cached_func(uncached_score_func_code)
score_predicate = create_score_predicate(score_first)
class FocusNode:
def __init__(self, instructions, code, stack, lemma_counter):
(context, outlog) = give_context(code)
self.instructions = instructions
self.context = context
self.code = code
self.outlog = outlog
self.stack = stack
self.lemma_counter = lemma_counter
def update(self, text):
code = filter_code(text+"```").lstrip()
return FocusNode(self.instructions, code, self.stack, self.lemma_counter)
def update_lemma(self, goal, code):
name = self.lemma_name(self.lemma_counter)
statement = lemma_statement(goal)
args = lemma_args(goal)
last_lemma_index = list(re.finditer(r"Lemma|Theorem", code))[-1].start(0)
last_lemma = code[last_lemma_index:]
code = code[:last_lemma_index]
last_lemma += f" apply (@{name} {args}).\n"
stack = [last_lemma] + self.stack
code += "\n"
code += f"Lemma {name}: {statement}.\nProof.\n"
if USE_HAMMER:
code += "(* do not use induction, try using hammer *)\n"
print(f'Created Lemma {name}.')
return FocusNode(self.instructions, code, stack, self.lemma_counter+1)
def update_pop(self, text):
code = filter_code(text+"```").lstrip()
last_lemma = self.stack[0]
stack = self.stack[1:]
code += "\n\n"
code += last_lemma
return FocusNode(self.instructions, code, stack, self.lemma_counter)
def lemma_name(self, counter):
return "helper"+str(counter)
def text(self):
return f"""
<s>[INST] <<SYS>>
You are a Coq programmer that writes functional code and prove properties about it. When you are unsure of which lemmas to use, you use the `Search` function, for example `Search (0 < _).`. You can see the output of the Coq verifier in the Out section, and the context of the current proof, comprising the current goal and assumptions, in the Context section. The assumptions have names that you can use in your proofs.
{'''You can use Coq Hammer, including the tactic `hammer` to attempt to discharge a goal automatically.
To use Coq Hammer effectively, combine it with destruct using `;`: `destruct e1; destruct e2; hammer`.''' if USE_HAMMER else ''}
You take a single step and will be given feedback -- listen to the feedback in the instructions.
<</SYS>>
## Instructions
{self.instructions}
## Out
{limit(self.outlog)}
## Context
{limit(self.context)}
[/INST]
## Code
```{LANG}
{self.code}"""
def generate_complete(focus, montecarlo):
text = focus.text()
prev = text
if DIVERSITY:
texts, features = llm.generate(text, 5, return_hiddens=True, bad_words_ids=bad_words_ids)
scores = [score_func_code(text) for text in texts]
text, (score, code) = select_diversely_with_scores(texts, scores, score_predicate, features, montecarlo)
elif EXPLORE_MANY:
texts = llm.generate(text, 5, bad_words_ids=bad_words_ids)
idx = 0
for i in range(len(texts)):
if score_predicate(score_func_code(texts[i])):
idx = i
break
text = texts[idx]
score, code = score_func_code(text)
else:
texts = llm.generate(text, 1, bad_words_ids=bad_words_ids)
text = texts[0]
score, code = score_func_code(text) | print(diffprompt(prev, texts)) | 20 | 2023-11-11 19:56:04+00:00 | 8k |
BraveGroup/Drive-WM | src/diffusers/models/resnet.py | [
{
"identifier": "USE_PEFT_BACKEND",
"path": "src/diffusers/utils/constants.py",
"snippet": "USE_PEFT_BACKEND = _required_peft_version and _required_transformers_version"
},
{
"identifier": "get_activation",
"path": "src/diffusers/models/activations.py",
"snippet": "def get_activation(act... | from functools import partial
from typing import Optional, Tuple, Union
from ..utils import USE_PEFT_BACKEND
from .activations import get_activation
from .attention_processor import SpatialNorm
from .lora import LoRACompatibleConv, LoRACompatibleLinear
from .normalization import AdaGroupNorm
import torch
import torch.nn as nn
import torch.nn.functional as F | 5,697 | class KDownsample2D(nn.Module):
r"""A 2D K-downsampling layer.
Parameters:
pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
"""
def __init__(self, pad_mode: str = "reflect"):
super().__init__()
self.pad_mode = pad_mode
kernel_1d = torch.tensor([[1 / 8, 3 / 8, 3 / 8, 1 / 8]])
self.pad = kernel_1d.shape[1] // 2 - 1
self.register_buffer("kernel", kernel_1d.T @ kernel_1d, persistent=False)
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
inputs = F.pad(inputs, (self.pad,) * 4, self.pad_mode)
weight = inputs.new_zeros([inputs.shape[1], inputs.shape[1], self.kernel.shape[0], self.kernel.shape[1]])
indices = torch.arange(inputs.shape[1], device=inputs.device)
kernel = self.kernel.to(weight)[None, :].expand(inputs.shape[1], -1, -1)
weight[indices, indices] = kernel
return F.conv2d(inputs, weight, stride=2)
class KUpsample2D(nn.Module):
r"""A 2D K-upsampling layer.
Parameters:
pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
"""
def __init__(self, pad_mode: str = "reflect"):
super().__init__()
self.pad_mode = pad_mode
kernel_1d = torch.tensor([[1 / 8, 3 / 8, 3 / 8, 1 / 8]]) * 2
self.pad = kernel_1d.shape[1] // 2 - 1
self.register_buffer("kernel", kernel_1d.T @ kernel_1d, persistent=False)
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
inputs = F.pad(inputs, ((self.pad + 1) // 2,) * 4, self.pad_mode)
weight = inputs.new_zeros([inputs.shape[1], inputs.shape[1], self.kernel.shape[0], self.kernel.shape[1]])
indices = torch.arange(inputs.shape[1], device=inputs.device)
kernel = self.kernel.to(weight)[None, :].expand(inputs.shape[1], -1, -1)
weight[indices, indices] = kernel
return F.conv_transpose2d(inputs, weight, stride=2, padding=self.pad * 2 + 1)
class ResnetBlock2D(nn.Module):
r"""
A Resnet block.
Parameters:
in_channels (`int`): The number of channels in the input.
out_channels (`int`, *optional*, default to be `None`):
The number of output channels for the first conv2d layer. If None, same as `in_channels`.
dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
temb_channels (`int`, *optional*, default to `512`): the number of channels in timestep embedding.
groups (`int`, *optional*, default to `32`): The number of groups to use for the first normalization layer.
groups_out (`int`, *optional*, default to None):
The number of groups to use for the second normalization layer. if set to None, same as `groups`.
eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
non_linearity (`str`, *optional*, default to `"swish"`): the activation function to use.
time_embedding_norm (`str`, *optional*, default to `"default"` ): Time scale shift config.
By default, apply timestep embedding conditioning with a simple shift mechanism. Choose "scale_shift" or
"ada_group" for a stronger conditioning with scale and shift.
kernel (`torch.FloatTensor`, optional, default to None): FIR filter, see
[`~models.resnet.FirUpsample2D`] and [`~models.resnet.FirDownsample2D`].
output_scale_factor (`float`, *optional*, default to be `1.0`): the scale factor to use for the output.
use_in_shortcut (`bool`, *optional*, default to `True`):
If `True`, add a 1x1 nn.conv2d layer for skip-connection.
up (`bool`, *optional*, default to `False`): If `True`, add an upsample layer.
down (`bool`, *optional*, default to `False`): If `True`, add a downsample layer.
conv_shortcut_bias (`bool`, *optional*, default to `True`): If `True`, adds a learnable bias to the
`conv_shortcut` output.
conv_2d_out_channels (`int`, *optional*, default to `None`): the number of channels in the output.
If None, same as `out_channels`.
"""
def __init__(
self,
*,
in_channels: int,
out_channels: Optional[int] = None,
conv_shortcut: bool = False,
dropout: float = 0.0,
temb_channels: int = 512,
groups: int = 32,
groups_out: Optional[int] = None,
pre_norm: bool = True,
eps: float = 1e-6,
non_linearity: str = "swish",
skip_time_act: bool = False,
time_embedding_norm: str = "default", # default, scale_shift, ada_group, spatial
kernel: Optional[torch.FloatTensor] = None,
output_scale_factor: float = 1.0,
use_in_shortcut: Optional[bool] = None,
up: bool = False,
down: bool = False,
conv_shortcut_bias: bool = True,
conv_2d_out_channels: Optional[int] = None,
):
super().__init__()
self.pre_norm = pre_norm
self.pre_norm = True
self.in_channels = in_channels
out_channels = in_channels if out_channels is None else out_channels
self.out_channels = out_channels
self.use_conv_shortcut = conv_shortcut
self.up = up
self.down = down
self.output_scale_factor = output_scale_factor
self.time_embedding_norm = time_embedding_norm
self.skip_time_act = skip_time_act
linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear
conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
if groups_out is None:
groups_out = groups
if self.time_embedding_norm == "ada_group":
| # Copyright 2023 The HuggingFace Team. All rights reserved.
# `TemporalConvLayer` Copyright 2023 Alibaba DAMO-VILAB, The ModelScope Team and 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.
class Upsample1D(nn.Module):
"""A 1D upsampling layer with an optional convolution.
Parameters:
channels (`int`):
number of channels in the inputs and outputs.
use_conv (`bool`, default `False`):
option to use a convolution.
use_conv_transpose (`bool`, default `False`):
option to use a convolution transpose.
out_channels (`int`, optional):
number of output channels. Defaults to `channels`.
name (`str`, default `conv`):
name of the upsampling 1D layer.
"""
def __init__(
self,
channels: int,
use_conv: bool = False,
use_conv_transpose: bool = False,
out_channels: Optional[int] = None,
name: str = "conv",
):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.use_conv_transpose = use_conv_transpose
self.name = name
self.conv = None
if use_conv_transpose:
self.conv = nn.ConvTranspose1d(channels, self.out_channels, 4, 2, 1)
elif use_conv:
self.conv = nn.Conv1d(self.channels, self.out_channels, 3, padding=1)
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
assert inputs.shape[1] == self.channels
if self.use_conv_transpose:
return self.conv(inputs)
outputs = F.interpolate(inputs, scale_factor=2.0, mode="nearest")
if self.use_conv:
outputs = self.conv(outputs)
return outputs
class Downsample1D(nn.Module):
"""A 1D downsampling layer with an optional convolution.
Parameters:
channels (`int`):
number of channels in the inputs and outputs.
use_conv (`bool`, default `False`):
option to use a convolution.
out_channels (`int`, optional):
number of output channels. Defaults to `channels`.
padding (`int`, default `1`):
padding for the convolution.
name (`str`, default `conv`):
name of the downsampling 1D layer.
"""
def __init__(
self,
channels: int,
use_conv: bool = False,
out_channels: Optional[int] = None,
padding: int = 1,
name: str = "conv",
):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.padding = padding
stride = 2
self.name = name
if use_conv:
self.conv = nn.Conv1d(self.channels, self.out_channels, 3, stride=stride, padding=padding)
else:
assert self.channels == self.out_channels
self.conv = nn.AvgPool1d(kernel_size=stride, stride=stride)
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
assert inputs.shape[1] == self.channels
return self.conv(inputs)
class Upsample2D(nn.Module):
"""A 2D upsampling layer with an optional convolution.
Parameters:
channels (`int`):
number of channels in the inputs and outputs.
use_conv (`bool`, default `False`):
option to use a convolution.
use_conv_transpose (`bool`, default `False`):
option to use a convolution transpose.
out_channels (`int`, optional):
number of output channels. Defaults to `channels`.
name (`str`, default `conv`):
name of the upsampling 2D layer.
"""
def __init__(
self,
channels: int,
use_conv: bool = False,
use_conv_transpose: bool = False,
out_channels: Optional[int] = None,
name: str = "conv",
):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.use_conv_transpose = use_conv_transpose
self.name = name
conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
conv = None
if use_conv_transpose:
conv = nn.ConvTranspose2d(channels, self.out_channels, 4, 2, 1)
elif use_conv:
conv = conv_cls(self.channels, self.out_channels, 3, padding=1)
# TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
if name == "conv":
self.conv = conv
else:
self.Conv2d_0 = conv
def forward(
self, hidden_states: torch.FloatTensor, output_size: Optional[int] = None, scale: float = 1.0
) -> torch.FloatTensor:
assert hidden_states.shape[1] == self.channels
if self.use_conv_transpose:
return self.conv(hidden_states)
# Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16
# TODO(Suraj): Remove this cast once the issue is fixed in PyTorch
# https://github.com/pytorch/pytorch/issues/86679
dtype = hidden_states.dtype
if dtype == torch.bfloat16:
hidden_states = hidden_states.to(torch.float32)
# upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
if hidden_states.shape[0] >= 64:
hidden_states = hidden_states.contiguous()
# if `output_size` is passed we force the interpolation output
# size and do not make use of `scale_factor=2`
if output_size is None:
hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
else:
hidden_states = F.interpolate(hidden_states, size=output_size, mode="nearest")
# If the input is bfloat16, we cast back to bfloat16
if dtype == torch.bfloat16:
hidden_states = hidden_states.to(dtype)
# TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
if self.use_conv:
if self.name == "conv":
if isinstance(self.conv, LoRACompatibleConv) and not USE_PEFT_BACKEND:
hidden_states = self.conv(hidden_states, scale)
else:
hidden_states = self.conv(hidden_states)
else:
if isinstance(self.Conv2d_0, LoRACompatibleConv) and not USE_PEFT_BACKEND:
hidden_states = self.Conv2d_0(hidden_states, scale)
else:
hidden_states = self.Conv2d_0(hidden_states)
return hidden_states
class Downsample2D(nn.Module):
"""A 2D downsampling layer with an optional convolution.
Parameters:
channels (`int`):
number of channels in the inputs and outputs.
use_conv (`bool`, default `False`):
option to use a convolution.
out_channels (`int`, optional):
number of output channels. Defaults to `channels`.
padding (`int`, default `1`):
padding for the convolution.
name (`str`, default `conv`):
name of the downsampling 2D layer.
"""
def __init__(
self,
channels: int,
use_conv: bool = False,
out_channels: Optional[int] = None,
padding: int = 1,
name: str = "conv",
):
super().__init__()
self.channels = channels
self.out_channels = out_channels or channels
self.use_conv = use_conv
self.padding = padding
stride = 2
self.name = name
conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
if use_conv:
conv = conv_cls(self.channels, self.out_channels, 3, stride=stride, padding=padding)
else:
assert self.channels == self.out_channels
conv = nn.AvgPool2d(kernel_size=stride, stride=stride)
# TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
if name == "conv":
self.Conv2d_0 = conv
self.conv = conv
elif name == "Conv2d_0":
self.conv = conv
else:
self.conv = conv
def forward(self, hidden_states: torch.FloatTensor, scale: float = 1.0) -> torch.FloatTensor:
assert hidden_states.shape[1] == self.channels
if self.use_conv and self.padding == 0:
pad = (0, 1, 0, 1)
hidden_states = F.pad(hidden_states, pad, mode="constant", value=0)
assert hidden_states.shape[1] == self.channels
if not USE_PEFT_BACKEND:
if isinstance(self.conv, LoRACompatibleConv):
hidden_states = self.conv(hidden_states, scale)
else:
hidden_states = self.conv(hidden_states)
else:
hidden_states = self.conv(hidden_states)
return hidden_states
class FirUpsample2D(nn.Module):
"""A 2D FIR upsampling layer with an optional convolution.
Parameters:
channels (`int`, optional):
number of channels in the inputs and outputs.
use_conv (`bool`, default `False`):
option to use a convolution.
out_channels (`int`, optional):
number of output channels. Defaults to `channels`.
fir_kernel (`tuple`, default `(1, 3, 3, 1)`):
kernel for the FIR filter.
"""
def __init__(
self,
channels: Optional[int] = None,
out_channels: Optional[int] = None,
use_conv: bool = False,
fir_kernel: Tuple[int, int, int, int] = (1, 3, 3, 1),
):
super().__init__()
out_channels = out_channels if out_channels else channels
if use_conv:
self.Conv2d_0 = nn.Conv2d(channels, out_channels, kernel_size=3, stride=1, padding=1)
self.use_conv = use_conv
self.fir_kernel = fir_kernel
self.out_channels = out_channels
def _upsample_2d(
self,
hidden_states: torch.FloatTensor,
weight: Optional[torch.FloatTensor] = None,
kernel: Optional[torch.FloatTensor] = None,
factor: int = 2,
gain: float = 1,
) -> torch.FloatTensor:
"""Fused `upsample_2d()` followed by `Conv2d()`.
Padding is performed only once at the beginning, not between the operations. The fused op is considerably more
efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of
arbitrary order.
Args:
hidden_states (`torch.FloatTensor`):
Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
weight (`torch.FloatTensor`, *optional*):
Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be
performed by `inChannels = x.shape[0] // numGroups`.
kernel (`torch.FloatTensor`, *optional*):
FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
corresponds to nearest-neighbor upsampling.
factor (`int`, *optional*): Integer upsampling factor (default: 2).
gain (`float`, *optional*): Scaling factor for signal magnitude (default: 1.0).
Returns:
output (`torch.FloatTensor`):
Tensor of the shape `[N, C, H * factor, W * factor]` or `[N, H * factor, W * factor, C]`, and same
datatype as `hidden_states`.
"""
assert isinstance(factor, int) and factor >= 1
# Setup filter kernel.
if kernel is None:
kernel = [1] * factor
# setup kernel
kernel = torch.tensor(kernel, dtype=torch.float32)
if kernel.ndim == 1:
kernel = torch.outer(kernel, kernel)
kernel /= torch.sum(kernel)
kernel = kernel * (gain * (factor**2))
if self.use_conv:
convH = weight.shape[2]
convW = weight.shape[3]
inC = weight.shape[1]
pad_value = (kernel.shape[0] - factor) - (convW - 1)
stride = (factor, factor)
# Determine data dimensions.
output_shape = (
(hidden_states.shape[2] - 1) * factor + convH,
(hidden_states.shape[3] - 1) * factor + convW,
)
output_padding = (
output_shape[0] - (hidden_states.shape[2] - 1) * stride[0] - convH,
output_shape[1] - (hidden_states.shape[3] - 1) * stride[1] - convW,
)
assert output_padding[0] >= 0 and output_padding[1] >= 0
num_groups = hidden_states.shape[1] // inC
# Transpose weights.
weight = torch.reshape(weight, (num_groups, -1, inC, convH, convW))
weight = torch.flip(weight, dims=[3, 4]).permute(0, 2, 1, 3, 4)
weight = torch.reshape(weight, (num_groups * inC, -1, convH, convW))
inverse_conv = F.conv_transpose2d(
hidden_states, weight, stride=stride, output_padding=output_padding, padding=0
)
output = upfirdn2d_native(
inverse_conv,
torch.tensor(kernel, device=inverse_conv.device),
pad=((pad_value + 1) // 2 + factor - 1, pad_value // 2 + 1),
)
else:
pad_value = kernel.shape[0] - factor
output = upfirdn2d_native(
hidden_states,
torch.tensor(kernel, device=hidden_states.device),
up=factor,
pad=((pad_value + 1) // 2 + factor - 1, pad_value // 2),
)
return output
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
if self.use_conv:
height = self._upsample_2d(hidden_states, self.Conv2d_0.weight, kernel=self.fir_kernel)
height = height + self.Conv2d_0.bias.reshape(1, -1, 1, 1)
else:
height = self._upsample_2d(hidden_states, kernel=self.fir_kernel, factor=2)
return height
class FirDownsample2D(nn.Module):
"""A 2D FIR downsampling layer with an optional convolution.
Parameters:
channels (`int`):
number of channels in the inputs and outputs.
use_conv (`bool`, default `False`):
option to use a convolution.
out_channels (`int`, optional):
number of output channels. Defaults to `channels`.
fir_kernel (`tuple`, default `(1, 3, 3, 1)`):
kernel for the FIR filter.
"""
def __init__(
self,
channels: Optional[int] = None,
out_channels: Optional[int] = None,
use_conv: bool = False,
fir_kernel: Tuple[int, int, int, int] = (1, 3, 3, 1),
):
super().__init__()
out_channels = out_channels if out_channels else channels
if use_conv:
self.Conv2d_0 = nn.Conv2d(channels, out_channels, kernel_size=3, stride=1, padding=1)
self.fir_kernel = fir_kernel
self.use_conv = use_conv
self.out_channels = out_channels
def _downsample_2d(
self,
hidden_states: torch.FloatTensor,
weight: Optional[torch.FloatTensor] = None,
kernel: Optional[torch.FloatTensor] = None,
factor: int = 2,
gain: float = 1,
) -> torch.FloatTensor:
"""Fused `Conv2d()` followed by `downsample_2d()`.
Padding is performed only once at the beginning, not between the operations. The fused op is considerably more
efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of
arbitrary order.
Args:
hidden_states (`torch.FloatTensor`):
Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
weight (`torch.FloatTensor`, *optional*):
Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be
performed by `inChannels = x.shape[0] // numGroups`.
kernel (`torch.FloatTensor`, *optional*):
FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
corresponds to average pooling.
factor (`int`, *optional*, default to `2`):
Integer downsampling factor.
gain (`float`, *optional*, default to `1.0`):
Scaling factor for signal magnitude.
Returns:
output (`torch.FloatTensor`):
Tensor of the shape `[N, C, H // factor, W // factor]` or `[N, H // factor, W // factor, C]`, and same
datatype as `x`.
"""
assert isinstance(factor, int) and factor >= 1
if kernel is None:
kernel = [1] * factor
# setup kernel
kernel = torch.tensor(kernel, dtype=torch.float32)
if kernel.ndim == 1:
kernel = torch.outer(kernel, kernel)
kernel /= torch.sum(kernel)
kernel = kernel * gain
if self.use_conv:
_, _, convH, convW = weight.shape
pad_value = (kernel.shape[0] - factor) + (convW - 1)
stride_value = [factor, factor]
upfirdn_input = upfirdn2d_native(
hidden_states,
torch.tensor(kernel, device=hidden_states.device),
pad=((pad_value + 1) // 2, pad_value // 2),
)
output = F.conv2d(upfirdn_input, weight, stride=stride_value, padding=0)
else:
pad_value = kernel.shape[0] - factor
output = upfirdn2d_native(
hidden_states,
torch.tensor(kernel, device=hidden_states.device),
down=factor,
pad=((pad_value + 1) // 2, pad_value // 2),
)
return output
def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
if self.use_conv:
downsample_input = self._downsample_2d(hidden_states, weight=self.Conv2d_0.weight, kernel=self.fir_kernel)
hidden_states = downsample_input + self.Conv2d_0.bias.reshape(1, -1, 1, 1)
else:
hidden_states = self._downsample_2d(hidden_states, kernel=self.fir_kernel, factor=2)
return hidden_states
# downsample/upsample layer used in k-upscaler, might be able to use FirDownsample2D/DirUpsample2D instead
class KDownsample2D(nn.Module):
r"""A 2D K-downsampling layer.
Parameters:
pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
"""
def __init__(self, pad_mode: str = "reflect"):
super().__init__()
self.pad_mode = pad_mode
kernel_1d = torch.tensor([[1 / 8, 3 / 8, 3 / 8, 1 / 8]])
self.pad = kernel_1d.shape[1] // 2 - 1
self.register_buffer("kernel", kernel_1d.T @ kernel_1d, persistent=False)
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
inputs = F.pad(inputs, (self.pad,) * 4, self.pad_mode)
weight = inputs.new_zeros([inputs.shape[1], inputs.shape[1], self.kernel.shape[0], self.kernel.shape[1]])
indices = torch.arange(inputs.shape[1], device=inputs.device)
kernel = self.kernel.to(weight)[None, :].expand(inputs.shape[1], -1, -1)
weight[indices, indices] = kernel
return F.conv2d(inputs, weight, stride=2)
class KUpsample2D(nn.Module):
r"""A 2D K-upsampling layer.
Parameters:
pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
"""
def __init__(self, pad_mode: str = "reflect"):
super().__init__()
self.pad_mode = pad_mode
kernel_1d = torch.tensor([[1 / 8, 3 / 8, 3 / 8, 1 / 8]]) * 2
self.pad = kernel_1d.shape[1] // 2 - 1
self.register_buffer("kernel", kernel_1d.T @ kernel_1d, persistent=False)
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
inputs = F.pad(inputs, ((self.pad + 1) // 2,) * 4, self.pad_mode)
weight = inputs.new_zeros([inputs.shape[1], inputs.shape[1], self.kernel.shape[0], self.kernel.shape[1]])
indices = torch.arange(inputs.shape[1], device=inputs.device)
kernel = self.kernel.to(weight)[None, :].expand(inputs.shape[1], -1, -1)
weight[indices, indices] = kernel
return F.conv_transpose2d(inputs, weight, stride=2, padding=self.pad * 2 + 1)
class ResnetBlock2D(nn.Module):
r"""
A Resnet block.
Parameters:
in_channels (`int`): The number of channels in the input.
out_channels (`int`, *optional*, default to be `None`):
The number of output channels for the first conv2d layer. If None, same as `in_channels`.
dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
temb_channels (`int`, *optional*, default to `512`): the number of channels in timestep embedding.
groups (`int`, *optional*, default to `32`): The number of groups to use for the first normalization layer.
groups_out (`int`, *optional*, default to None):
The number of groups to use for the second normalization layer. if set to None, same as `groups`.
eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
non_linearity (`str`, *optional*, default to `"swish"`): the activation function to use.
time_embedding_norm (`str`, *optional*, default to `"default"` ): Time scale shift config.
By default, apply timestep embedding conditioning with a simple shift mechanism. Choose "scale_shift" or
"ada_group" for a stronger conditioning with scale and shift.
kernel (`torch.FloatTensor`, optional, default to None): FIR filter, see
[`~models.resnet.FirUpsample2D`] and [`~models.resnet.FirDownsample2D`].
output_scale_factor (`float`, *optional*, default to be `1.0`): the scale factor to use for the output.
use_in_shortcut (`bool`, *optional*, default to `True`):
If `True`, add a 1x1 nn.conv2d layer for skip-connection.
up (`bool`, *optional*, default to `False`): If `True`, add an upsample layer.
down (`bool`, *optional*, default to `False`): If `True`, add a downsample layer.
conv_shortcut_bias (`bool`, *optional*, default to `True`): If `True`, adds a learnable bias to the
`conv_shortcut` output.
conv_2d_out_channels (`int`, *optional*, default to `None`): the number of channels in the output.
If None, same as `out_channels`.
"""
def __init__(
self,
*,
in_channels: int,
out_channels: Optional[int] = None,
conv_shortcut: bool = False,
dropout: float = 0.0,
temb_channels: int = 512,
groups: int = 32,
groups_out: Optional[int] = None,
pre_norm: bool = True,
eps: float = 1e-6,
non_linearity: str = "swish",
skip_time_act: bool = False,
time_embedding_norm: str = "default", # default, scale_shift, ada_group, spatial
kernel: Optional[torch.FloatTensor] = None,
output_scale_factor: float = 1.0,
use_in_shortcut: Optional[bool] = None,
up: bool = False,
down: bool = False,
conv_shortcut_bias: bool = True,
conv_2d_out_channels: Optional[int] = None,
):
super().__init__()
self.pre_norm = pre_norm
self.pre_norm = True
self.in_channels = in_channels
out_channels = in_channels if out_channels is None else out_channels
self.out_channels = out_channels
self.use_conv_shortcut = conv_shortcut
self.up = up
self.down = down
self.output_scale_factor = output_scale_factor
self.time_embedding_norm = time_embedding_norm
self.skip_time_act = skip_time_act
linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear
conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
if groups_out is None:
groups_out = groups
if self.time_embedding_norm == "ada_group": | self.norm1 = AdaGroupNorm(temb_channels, in_channels, groups, eps=eps) | 5 | 2023-11-18 01:40:55+00:00 | 8k |
basnijholt/unidep | tests/test_unidep.py | [
{
"identifier": "create_conda_env_specification",
"path": "unidep/_conda_env.py",
"snippet": "def create_conda_env_specification( # noqa: PLR0912\n resolved: dict[str, dict[Platform | None, dict[CondaPip, Spec]]],\n channels: list[str],\n platforms: list[Platform],\n selector: Literal[\"sel... | import textwrap
import pytest
import sys
from pathlib import Path
from typing import TYPE_CHECKING
from ruamel.yaml import YAML
from unidep import (
create_conda_env_specification,
filter_python_dependencies,
find_requirements_files,
get_python_dependencies,
parse_requirements,
resolve_conflicts,
write_conda_environment_file,
)
from unidep._conda_env import CondaEnvironmentSpec
from unidep._conflicts import VersionConflictError
from unidep._dependencies_parsing import yaml_to_toml
from unidep.platform_definitions import Platform, Spec
from typing import Literal
from typing_extensions import Literal | 4,985 | """unidep tests."""
from __future__ import annotations
if TYPE_CHECKING:
if sys.version_info >= (3, 8):
else: # pragma: no cover
REPO_ROOT = Path(__file__).parent.parent
def maybe_as_toml(toml_or_yaml: Literal["toml", "yaml"], p: Path) -> Path:
if toml_or_yaml == "toml":
toml = yaml_to_toml(p)
p.unlink()
p = p.with_name("pyproject.toml")
p.write_text(toml)
return p
@pytest.fixture(params=["toml", "yaml"])
def setup_test_files(
request: pytest.FixtureRequest,
tmp_path: Path,
) -> tuple[Path, Path]:
d1 = tmp_path / "dir1"
d1.mkdir()
f1 = d1 / "requirements.yaml"
f1.write_text("dependencies:\n - numpy\n - conda: mumps")
d2 = tmp_path / "dir2"
d2.mkdir()
f2 = d2 / "requirements.yaml"
f2.write_text("dependencies:\n - pip: pandas")
f1 = maybe_as_toml(request.param, f1)
f2 = maybe_as_toml(request.param, f2)
return (f1, f2)
def test_find_requirements_files(
tmp_path: Path,
setup_test_files: tuple[Path, Path],
) -> None:
# Make sure to pass the depth argument correctly if your function expects it.
found_files = find_requirements_files(
tmp_path,
depth=1,
verbose=True,
)
# Convert found_files to absolute paths for comparison
absolute_results = sorted(str(p.resolve()) for p in found_files)
absolute_test_files = sorted(str(p.resolve()) for p in setup_test_files)
assert absolute_results == absolute_test_files
def test_find_requirements_files_depth(tmp_path: Path) -> None:
# Create a nested directory structure
(tmp_path / "dir1").mkdir()
(tmp_path / "dir1/dir2").mkdir()
(tmp_path / "dir1/dir2/dir3").mkdir()
# Create test files
(tmp_path / "requirements.yaml").touch()
(tmp_path / "dir1/requirements.yaml").touch()
(tmp_path / "dir1/dir2/requirements.yaml").touch()
(tmp_path / "dir1/dir2/dir3/requirements.yaml").touch()
# Test depth=0
assert len(find_requirements_files(tmp_path, depth=0)) == 1
# Test depth=1
assert len(find_requirements_files(tmp_path, depth=1)) == 2
# Test depth=2
assert len(find_requirements_files(tmp_path, depth=2)) == 3
# Test depth=3
assert len(find_requirements_files(tmp_path, depth=3)) == 4
# Test depth=4 (or more)
assert len(find_requirements_files(tmp_path, depth=4)) == 4
@pytest.mark.parametrize("toml_or_yaml", ["toml", "yaml"])
def test_parse_requirements(
toml_or_yaml: Literal["toml", "yaml"],
tmp_path: Path,
) -> None:
p = tmp_path / "requirements.yaml"
p.write_text(
textwrap.dedent(
"""\
dependencies:
- foo >1 # [linux64]
- foo # [unix]
- bar >1
- bar
""",
),
)
p = maybe_as_toml(toml_or_yaml, p)
| """unidep tests."""
from __future__ import annotations
if TYPE_CHECKING:
if sys.version_info >= (3, 8):
else: # pragma: no cover
REPO_ROOT = Path(__file__).parent.parent
def maybe_as_toml(toml_or_yaml: Literal["toml", "yaml"], p: Path) -> Path:
if toml_or_yaml == "toml":
toml = yaml_to_toml(p)
p.unlink()
p = p.with_name("pyproject.toml")
p.write_text(toml)
return p
@pytest.fixture(params=["toml", "yaml"])
def setup_test_files(
request: pytest.FixtureRequest,
tmp_path: Path,
) -> tuple[Path, Path]:
d1 = tmp_path / "dir1"
d1.mkdir()
f1 = d1 / "requirements.yaml"
f1.write_text("dependencies:\n - numpy\n - conda: mumps")
d2 = tmp_path / "dir2"
d2.mkdir()
f2 = d2 / "requirements.yaml"
f2.write_text("dependencies:\n - pip: pandas")
f1 = maybe_as_toml(request.param, f1)
f2 = maybe_as_toml(request.param, f2)
return (f1, f2)
def test_find_requirements_files(
tmp_path: Path,
setup_test_files: tuple[Path, Path],
) -> None:
# Make sure to pass the depth argument correctly if your function expects it.
found_files = find_requirements_files(
tmp_path,
depth=1,
verbose=True,
)
# Convert found_files to absolute paths for comparison
absolute_results = sorted(str(p.resolve()) for p in found_files)
absolute_test_files = sorted(str(p.resolve()) for p in setup_test_files)
assert absolute_results == absolute_test_files
def test_find_requirements_files_depth(tmp_path: Path) -> None:
# Create a nested directory structure
(tmp_path / "dir1").mkdir()
(tmp_path / "dir1/dir2").mkdir()
(tmp_path / "dir1/dir2/dir3").mkdir()
# Create test files
(tmp_path / "requirements.yaml").touch()
(tmp_path / "dir1/requirements.yaml").touch()
(tmp_path / "dir1/dir2/requirements.yaml").touch()
(tmp_path / "dir1/dir2/dir3/requirements.yaml").touch()
# Test depth=0
assert len(find_requirements_files(tmp_path, depth=0)) == 1
# Test depth=1
assert len(find_requirements_files(tmp_path, depth=1)) == 2
# Test depth=2
assert len(find_requirements_files(tmp_path, depth=2)) == 3
# Test depth=3
assert len(find_requirements_files(tmp_path, depth=3)) == 4
# Test depth=4 (or more)
assert len(find_requirements_files(tmp_path, depth=4)) == 4
@pytest.mark.parametrize("toml_or_yaml", ["toml", "yaml"])
def test_parse_requirements(
toml_or_yaml: Literal["toml", "yaml"],
tmp_path: Path,
) -> None:
p = tmp_path / "requirements.yaml"
p.write_text(
textwrap.dedent(
"""\
dependencies:
- foo >1 # [linux64]
- foo # [unix]
- bar >1
- bar
""",
),
)
p = maybe_as_toml(toml_or_yaml, p) | requirements = parse_requirements(p, verbose=False) | 4 | 2023-11-16 04:23:01+00:00 | 8k |
BAAI-DCAI/SegVol | train.py | [
{
"identifier": "SegVol",
"path": "network/model.py",
"snippet": "class SegVol(nn.Module):\n def __init__(self, \n image_encoder, \n mask_decoder,\n prompt_encoder,\n clip_ckpt,\n roi_size,\n patch_size,\n ... | import os
import torch
import argparse
import torch.multiprocessing as mp
import shutil
from datetime import datetime
from network.model import SegVol
from segment_anything_volumetric import sam_model_registry
from utils.lr_scheduler import LinearWarmupCosineAnnealingLR
from utils.loss import BCELoss, BinaryDiceLoss
from data_utils import get_loader
from tensorboardX import SummaryWriter
from tqdm import tqdm | 5,865 | parser.add_argument("--pretrain", type = str, default='')
parser.add_argument("--resume", type = str, default='')
parser.add_argument("--data_dir", type = str, default='')
parser.add_argument("--dataset_codes", type = list, default=['0010', '0011'])
# config
parser.add_argument("--test_mode", default=False, type=bool)
parser.add_argument("-infer_overlap", default=0.5, type=float, help="sliding window inference overlap")
parser.add_argument("-spatial_size", default=(32, 256, 256), type=tuple)
parser.add_argument("-patch_size", default=(4, 16, 16), type=tuple)
parser.add_argument('-work_dir', type=str, default='./work_dir')
parser.add_argument("--clip_ckpt", type = str, default = './config/clip')
parser.add_argument("--RandFlipd_prob", default=0.2, type=float, help="RandFlipd aug probability")
parser.add_argument("--RandScaleIntensityd_prob", default=0.1, type=float, help="RandScaleIntensityd aug probability")
parser.add_argument("--RandShiftIntensityd_prob", default=0.1, type=float, help="RandShiftIntensityd aug probability")
parser.add_argument('-num_workers', type=int, default=8)
# dist
parser.add_argument('--dist', dest='dist', type=bool, default=True,
help='distributed training or not')
parser.add_argument('--node_rank', type=int, default=0, help='Node rank')
parser.add_argument('--init_method', type = str, default = "env://")
parser.add_argument('--bucket_cap_mb', type = int, default = 25,
help='The amount of memory in Mb that DDP will accumulate before firing off gradient communication for the bucket (need to tune)')
# key params
parser.add_argument('-lr', type=float, default=1e-4)
parser.add_argument('-weight_decay', type=float, default=1e-5)
parser.add_argument('-warmup_epoch', type=int, default=10)
parser.add_argument('-num_epochs', type=int, default=500)
parser.add_argument('-batch_size', type=int, default=4)
parser.add_argument("--use_pseudo_label", default=True, type=bool)
args = parser.parse_args()
return args
def train_epoch(args, segvol_model, train_dataloader, optimizer, scheduler, epoch, rank, gpu, iter_num):
epoch_loss = 0
epoch_sl_loss = 0
epoch_ssl_loss = 0
epoch_iterator = tqdm(
train_dataloader, desc = f"[RANK {rank}: GPU {gpu}]", dynamic_ncols=True
)
if args.dist:
train_dataloader.sampler.set_epoch(epoch)
torch.distributed.barrier()
for batch in epoch_iterator:
image, gt3D = batch["image"].cuda(), batch["post_label"].cuda()
pseudo_seg_cleaned = batch['pseudo_seg_cleaned'].cuda()
organ_name_list = batch['organ_name_list']
loss_step_avg = 0
sl_loss_step_avg = 0
ssl_loss_step_avg = 0
for cls_idx in range(len(organ_name_list)):
optimizer.zero_grad()
organs_cls = organ_name_list[cls_idx]
labels_cls = gt3D[:, cls_idx]
if torch.sum(labels_cls) == 0:
print(f'[RANK {rank}: GPU {gpu}] ITER-{iter_num} --- No object, skip iter')
continue
sl_loss, ssl_loss = segvol_model(image, organs=None, boxes=None, points=None,
train_organs=organs_cls,
train_labels=labels_cls,
pseudo_seg_cleaned=pseudo_seg_cleaned)
if args.use_pseudo_label:
loss = sl_loss + 0.1 * ssl_loss
ssl_loss_step_avg += ssl_loss.item()
sl_loss_step_avg += sl_loss.item()
loss_step_avg += loss.item()
loss.backward()
optimizer.step()
print(f'[RANK {rank}: GPU {gpu}] ITER-{iter_num} --- loss {loss.item()}, sl_loss, {sl_loss.item()}, ssl_loss {ssl_loss.item()}')
iter_num += 1
loss_step_avg /= len(organ_name_list)
sl_loss_step_avg /= len(organ_name_list)
ssl_loss_step_avg /= len(organ_name_list)
print(f'[RANK {rank}: GPU {gpu}] AVG loss {loss_step_avg}, sl_loss, {sl_loss_step_avg}, ssl_loss {ssl_loss_step_avg}')
if rank == 0:
args.writer.add_scalar('train_iter/loss', loss_step_avg, iter_num)
args.writer.add_scalar('train_iter/sl_loss', sl_loss_step_avg, iter_num)
args.writer.add_scalar('train_iter/ssl_loss', ssl_loss_step_avg, iter_num)
epoch_loss += loss_step_avg
epoch_sl_loss += sl_loss_step_avg
if args.use_pseudo_label:
epoch_ssl_loss += ssl_loss_step_avg
scheduler.step()
epoch_loss /= len(train_dataloader) + 1e-12
epoch_ssl_loss /= len(train_dataloader) + 1e-12
epoch_sl_loss /= len(train_dataloader) + 1e-12
print(f'{args.model_save_path} ==> [RANK {rank}: GPU {gpu}] ', 'epoch_loss: {}, ssl_loss: {}'.format(epoch_loss, epoch_ssl_loss))
if rank == 0:
args.writer.add_scalar('train/loss', epoch_loss, epoch)
args.writer.add_scalar('train/sl_loss', epoch_sl_loss, epoch)
args.writer.add_scalar('train/ssl_loss', epoch_ssl_loss, epoch)
args.writer.add_scalar('train/lr', scheduler.get_lr(), epoch)
return epoch_loss, iter_num
def main_worker(gpu, ngpus_per_node, args):
node_rank = int(args.node_rank)
rank = node_rank * ngpus_per_node + gpu
world_size = ngpus_per_node #args.world_size
print(f"[Rank {rank}]: Use GPU: {gpu} for training")
is_main_host = rank == 0
if is_main_host:
os.makedirs(args.model_save_path, exist_ok=True)
shutil.copyfile(__file__, os.path.join(args.model_save_path, args.run_id + '_' + os.path.basename(__file__)))
torch.cuda.set_device(gpu)
torch.distributed.init_process_group(
backend = "nccl",
init_method = args.init_method,
rank = rank,
world_size = world_size,
)
print('init_process_group finished')
|
def set_parse():
parser = argparse.ArgumentParser()
# %% set up parser
parser.add_argument("--pretrain", type = str, default='')
parser.add_argument("--resume", type = str, default='')
parser.add_argument("--data_dir", type = str, default='')
parser.add_argument("--dataset_codes", type = list, default=['0010', '0011'])
# config
parser.add_argument("--test_mode", default=False, type=bool)
parser.add_argument("-infer_overlap", default=0.5, type=float, help="sliding window inference overlap")
parser.add_argument("-spatial_size", default=(32, 256, 256), type=tuple)
parser.add_argument("-patch_size", default=(4, 16, 16), type=tuple)
parser.add_argument('-work_dir', type=str, default='./work_dir')
parser.add_argument("--clip_ckpt", type = str, default = './config/clip')
parser.add_argument("--RandFlipd_prob", default=0.2, type=float, help="RandFlipd aug probability")
parser.add_argument("--RandScaleIntensityd_prob", default=0.1, type=float, help="RandScaleIntensityd aug probability")
parser.add_argument("--RandShiftIntensityd_prob", default=0.1, type=float, help="RandShiftIntensityd aug probability")
parser.add_argument('-num_workers', type=int, default=8)
# dist
parser.add_argument('--dist', dest='dist', type=bool, default=True,
help='distributed training or not')
parser.add_argument('--node_rank', type=int, default=0, help='Node rank')
parser.add_argument('--init_method', type = str, default = "env://")
parser.add_argument('--bucket_cap_mb', type = int, default = 25,
help='The amount of memory in Mb that DDP will accumulate before firing off gradient communication for the bucket (need to tune)')
# key params
parser.add_argument('-lr', type=float, default=1e-4)
parser.add_argument('-weight_decay', type=float, default=1e-5)
parser.add_argument('-warmup_epoch', type=int, default=10)
parser.add_argument('-num_epochs', type=int, default=500)
parser.add_argument('-batch_size', type=int, default=4)
parser.add_argument("--use_pseudo_label", default=True, type=bool)
args = parser.parse_args()
return args
def train_epoch(args, segvol_model, train_dataloader, optimizer, scheduler, epoch, rank, gpu, iter_num):
epoch_loss = 0
epoch_sl_loss = 0
epoch_ssl_loss = 0
epoch_iterator = tqdm(
train_dataloader, desc = f"[RANK {rank}: GPU {gpu}]", dynamic_ncols=True
)
if args.dist:
train_dataloader.sampler.set_epoch(epoch)
torch.distributed.barrier()
for batch in epoch_iterator:
image, gt3D = batch["image"].cuda(), batch["post_label"].cuda()
pseudo_seg_cleaned = batch['pseudo_seg_cleaned'].cuda()
organ_name_list = batch['organ_name_list']
loss_step_avg = 0
sl_loss_step_avg = 0
ssl_loss_step_avg = 0
for cls_idx in range(len(organ_name_list)):
optimizer.zero_grad()
organs_cls = organ_name_list[cls_idx]
labels_cls = gt3D[:, cls_idx]
if torch.sum(labels_cls) == 0:
print(f'[RANK {rank}: GPU {gpu}] ITER-{iter_num} --- No object, skip iter')
continue
sl_loss, ssl_loss = segvol_model(image, organs=None, boxes=None, points=None,
train_organs=organs_cls,
train_labels=labels_cls,
pseudo_seg_cleaned=pseudo_seg_cleaned)
if args.use_pseudo_label:
loss = sl_loss + 0.1 * ssl_loss
ssl_loss_step_avg += ssl_loss.item()
sl_loss_step_avg += sl_loss.item()
loss_step_avg += loss.item()
loss.backward()
optimizer.step()
print(f'[RANK {rank}: GPU {gpu}] ITER-{iter_num} --- loss {loss.item()}, sl_loss, {sl_loss.item()}, ssl_loss {ssl_loss.item()}')
iter_num += 1
loss_step_avg /= len(organ_name_list)
sl_loss_step_avg /= len(organ_name_list)
ssl_loss_step_avg /= len(organ_name_list)
print(f'[RANK {rank}: GPU {gpu}] AVG loss {loss_step_avg}, sl_loss, {sl_loss_step_avg}, ssl_loss {ssl_loss_step_avg}')
if rank == 0:
args.writer.add_scalar('train_iter/loss', loss_step_avg, iter_num)
args.writer.add_scalar('train_iter/sl_loss', sl_loss_step_avg, iter_num)
args.writer.add_scalar('train_iter/ssl_loss', ssl_loss_step_avg, iter_num)
epoch_loss += loss_step_avg
epoch_sl_loss += sl_loss_step_avg
if args.use_pseudo_label:
epoch_ssl_loss += ssl_loss_step_avg
scheduler.step()
epoch_loss /= len(train_dataloader) + 1e-12
epoch_ssl_loss /= len(train_dataloader) + 1e-12
epoch_sl_loss /= len(train_dataloader) + 1e-12
print(f'{args.model_save_path} ==> [RANK {rank}: GPU {gpu}] ', 'epoch_loss: {}, ssl_loss: {}'.format(epoch_loss, epoch_ssl_loss))
if rank == 0:
args.writer.add_scalar('train/loss', epoch_loss, epoch)
args.writer.add_scalar('train/sl_loss', epoch_sl_loss, epoch)
args.writer.add_scalar('train/ssl_loss', epoch_ssl_loss, epoch)
args.writer.add_scalar('train/lr', scheduler.get_lr(), epoch)
return epoch_loss, iter_num
def main_worker(gpu, ngpus_per_node, args):
node_rank = int(args.node_rank)
rank = node_rank * ngpus_per_node + gpu
world_size = ngpus_per_node #args.world_size
print(f"[Rank {rank}]: Use GPU: {gpu} for training")
is_main_host = rank == 0
if is_main_host:
os.makedirs(args.model_save_path, exist_ok=True)
shutil.copyfile(__file__, os.path.join(args.model_save_path, args.run_id + '_' + os.path.basename(__file__)))
torch.cuda.set_device(gpu)
torch.distributed.init_process_group(
backend = "nccl",
init_method = args.init_method,
rank = rank,
world_size = world_size,
)
print('init_process_group finished')
| sam_model = sam_model_registry['vit'](args=args, checkpoint=None) # checkpoint for pretrained vit | 1 | 2023-11-10 08:25:37+00:00 | 8k |
xk-huang/segment-caption-anything | scripts/apps/visualize_infer_app.py | [
{
"identifier": "global_setup",
"path": "src/arguments.py",
"snippet": "def global_setup(\n args: DictConfig,\n) -> Tuple[Arguments, SCASeq2SeqTrainingArguments, ModelArguments]:\n \"\"\"Global setup of arguments.\"\"\"\n if args.training.output_log_dir is not None:\n output_log_dir = ar... | import sys
import os
import os
import torch
import numpy as np
import pandas as pd
import pycocotools.mask
import json
import tqdm
import hashlib
import glob
import cv2
import numpy as np
import cv2
import numpy as np
import pandas as pd
import json
import io
import base64
import pycocotools.mask
import sqlite3
from src.arguments import global_setup, SAMCaptionerModelArguments, SCAModelBaseArguments
from src.models.sam_captioner import SAMCaptionerProcessor
from src.models.sca import ScaProcessor
from src.train import prepare_datasets, prepare_data_transform
from PIL import Image
from hydra import initialize, compose
from PIL import Image, ImageDraw, ImageFont
from PIL import Image, ImageDraw, ImageFont
from PIL import Image
from flask import Flask, render_template, request, send_file | 5,743 |
sys.path.append(".")
os.getcwd()
DATASET = "vg-densecap-local"
with initialize(version_base="1.3", config_path="../../src/conf"):
args = compose(
config_name="conf",
overrides=[
f"train_data=[{DATASET}]",
f"eval_data=[{DATASET}]",
"+model=base_sam_captioner",
"training.output_dir=tmp/visualization"
# "training.do_train=True",
# "training.do_eval=True",
],
)
args, training_args, model_args = global_setup(args)
os.makedirs(training_args.output_dir, exist_ok=True)
# Initialize our dataset and prepare it
with initialize(version_base="1.3", config_path="../../src/conf"):
train_dataset, eval_dataset = prepare_datasets(args)
if isinstance(model_args, SAMCaptionerModelArguments):
processor = SAMCaptionerProcessor.from_sam_captioner_pretrained(
model_args.sam_model_name_or_path,
model_args.captioner_model_name_or_path,
cache_dir=model_args.cache_dir,
model_max_length=model_args.model_max_length,
)
# FIXME: when load weights from existing sca model, we should use the same tokenizer as the existing sca model
# model.lm_head_model_name_or_path=$(grep lm_head_model_name_or_path $AMLT_MAP_INPUT_DIR/.hydra/config.yaml | tail -n1 | sed 's/ *//g' | cut -d ':' -f2)
# model.sam_model_name_or_path=$(grep sam_model_name_or_path $AMLT_MAP_INPUT_DIR/.hydra/config.yaml | tail -n1 | sed 's/ *//g' | cut -d ':' -f2)
elif isinstance(model_args, SCAModelBaseArguments):
|
sys.path.append(".")
os.getcwd()
DATASET = "vg-densecap-local"
with initialize(version_base="1.3", config_path="../../src/conf"):
args = compose(
config_name="conf",
overrides=[
f"train_data=[{DATASET}]",
f"eval_data=[{DATASET}]",
"+model=base_sam_captioner",
"training.output_dir=tmp/visualization"
# "training.do_train=True",
# "training.do_eval=True",
],
)
args, training_args, model_args = global_setup(args)
os.makedirs(training_args.output_dir, exist_ok=True)
# Initialize our dataset and prepare it
with initialize(version_base="1.3", config_path="../../src/conf"):
train_dataset, eval_dataset = prepare_datasets(args)
if isinstance(model_args, SAMCaptionerModelArguments):
processor = SAMCaptionerProcessor.from_sam_captioner_pretrained(
model_args.sam_model_name_or_path,
model_args.captioner_model_name_or_path,
cache_dir=model_args.cache_dir,
model_max_length=model_args.model_max_length,
)
# FIXME: when load weights from existing sca model, we should use the same tokenizer as the existing sca model
# model.lm_head_model_name_or_path=$(grep lm_head_model_name_or_path $AMLT_MAP_INPUT_DIR/.hydra/config.yaml | tail -n1 | sed 's/ *//g' | cut -d ':' -f2)
# model.sam_model_name_or_path=$(grep sam_model_name_or_path $AMLT_MAP_INPUT_DIR/.hydra/config.yaml | tail -n1 | sed 's/ *//g' | cut -d ':' -f2)
elif isinstance(model_args, SCAModelBaseArguments): | processor = ScaProcessor.from_sam_text_pretrained( | 4 | 2023-11-17 14:10:41+00:00 | 8k |
p0p4k/pflowtts_pytorch | pflow/models/components/speech_prompt_encoder.py | [
{
"identifier": "sequence_mask",
"path": "pflow/utils/model.py",
"snippet": "def sequence_mask(length, max_length=None):\n if max_length is None:\n max_length = length.max()\n x = torch.arange(max_length, dtype=length.dtype, device=length.device)\n return x.unsqueeze(0) < length.unsqueez... | import math
import torch
import torch.nn as nn
import pflow.utils as utils
from einops import rearrange
from pflow.utils.model import sequence_mask
from pflow.models.components import commons
from pflow.models.components.vits_posterior import PosteriorEncoder
from pflow.models.components.transformer import BasicTransformerBlock | 5,155 | MultiHeadAttention(
hidden_channels,
hidden_channels,
n_heads,
p_dropout=p_dropout
)
)
self.norm_layers_0.append(LayerNorm(hidden_channels))
self.encdec_attn_layers.append(
MultiHeadAttention(
hidden_channels,
hidden_channels,
n_heads,
p_dropout=p_dropout
)
)
self.norm_layers_1.append(LayerNorm(hidden_channels))
self.ffn_layers.append(
FFN(
hidden_channels,
hidden_channels,
filter_channels,
kernel_size,
p_dropout=p_dropout,
)
)
self.norm_layers_2.append(LayerNorm(hidden_channels))
def forward(self, x, x_mask, h, h_mask):
"""
x: decoder input
h: encoder output
"""
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
device=x.device, dtype=x.dtype
)
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
x = x * x_mask
for i in range(self.n_layers):
y = self.self_attn_layers[i](x, x, self_attn_mask)
y = self.drop(y)
x = self.norm_layers_0[i](x + y)
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
y = self.drop(y)
x = self.norm_layers_1[i](x + y)
y = self.ffn_layers[i](x, x_mask)
y = self.drop(y)
x = self.norm_layers_2[i](x + y)
x = x * x_mask
return x
class TextEncoder(nn.Module):
def __init__(
self,
encoder_type,
encoder_params,
duration_predictor_params,
n_vocab,
speech_in_channels,
):
super().__init__()
self.encoder_type = encoder_type
self.n_vocab = n_vocab
self.n_feats = encoder_params.n_feats
self.n_channels = encoder_params.n_channels
self.emb = torch.nn.Embedding(n_vocab, self.n_channels)
torch.nn.init.normal_(self.emb.weight, 0.0, self.n_channels**-0.5)
self.speech_in_channels = speech_in_channels
self.speech_out_channels = self.n_channels
self.speech_prompt_proj = torch.nn.Conv1d(self.speech_in_channels, self.speech_out_channels, 1)
# self.speech_prompt_proj = PosteriorEncoder(
# self.speech_in_channels,
# self.speech_out_channels,
# self.speech_out_channels,
# 1,
# 1,
# 1,
# gin_channels=0,
# )
self.prenet = ConvReluNorm(
self.n_channels,
self.n_channels,
self.n_channels,
kernel_size=5,
n_layers=3,
p_dropout=0,
)
self.speech_prompt_encoder = Encoder(
encoder_params.n_channels,
encoder_params.filter_channels,
encoder_params.n_heads,
encoder_params.n_layers,
encoder_params.kernel_size,
encoder_params.p_dropout,
)
self.text_base_encoder = Encoder(
encoder_params.n_channels,
encoder_params.filter_channels,
encoder_params.n_heads,
encoder_params.n_layers,
encoder_params.kernel_size,
encoder_params.p_dropout,
)
self.decoder = Decoder(
encoder_params.n_channels,
encoder_params.filter_channels,
encoder_params.n_heads,
encoder_params.n_layers,
encoder_params.kernel_size,
encoder_params.p_dropout,
)
| """ from https://github.com/jaywalnut310/glow-tts """
log = utils.get_pylogger(__name__)
class LayerNorm(nn.Module):
def __init__(self, channels, eps=1e-4):
super().__init__()
self.channels = channels
self.eps = eps
self.gamma = torch.nn.Parameter(torch.ones(channels))
self.beta = torch.nn.Parameter(torch.zeros(channels))
def forward(self, x):
n_dims = len(x.shape)
mean = torch.mean(x, 1, keepdim=True)
variance = torch.mean((x - mean) ** 2, 1, keepdim=True)
x = (x - mean) * torch.rsqrt(variance + self.eps)
shape = [1, -1] + [1] * (n_dims - 2)
x = x * self.gamma.view(*shape) + self.beta.view(*shape)
return x
class ConvReluNorm(nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, kernel_size, n_layers, p_dropout):
super().__init__()
self.in_channels = in_channels
self.hidden_channels = hidden_channels
self.out_channels = out_channels
self.kernel_size = kernel_size
self.n_layers = n_layers
self.p_dropout = p_dropout
self.conv_layers = torch.nn.ModuleList()
self.norm_layers = torch.nn.ModuleList()
self.conv_layers.append(torch.nn.Conv1d(in_channels, hidden_channels, kernel_size, padding=kernel_size // 2))
self.norm_layers.append(LayerNorm(hidden_channels))
self.relu_drop = torch.nn.Sequential(torch.nn.ReLU(), torch.nn.Dropout(p_dropout))
for _ in range(n_layers - 1):
self.conv_layers.append(
torch.nn.Conv1d(hidden_channels, hidden_channels, kernel_size, padding=kernel_size // 2)
)
self.norm_layers.append(LayerNorm(hidden_channels))
self.proj = torch.nn.Conv1d(hidden_channels, out_channels, 1)
self.proj.weight.data.zero_()
self.proj.bias.data.zero_()
def forward(self, x, x_mask):
x_org = x
for i in range(self.n_layers):
x = self.conv_layers[i](x * x_mask)
x = self.norm_layers[i](x)
x = self.relu_drop(x)
x = x_org + self.proj(x)
return x * x_mask
class DurationPredictor(nn.Module):
def __init__(self, in_channels, filter_channels, kernel_size, p_dropout):
super().__init__()
self.in_channels = in_channels
self.filter_channels = filter_channels
self.p_dropout = p_dropout
self.drop = torch.nn.Dropout(p_dropout)
self.conv_1 = torch.nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
self.norm_1 = LayerNorm(filter_channels)
self.conv_2 = torch.nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2)
self.norm_2 = LayerNorm(filter_channels)
self.proj = torch.nn.Conv1d(filter_channels, 1, 1)
def forward(self, x, x_mask):
x = self.conv_1(x * x_mask)
x = torch.relu(x)
x = self.norm_1(x)
x = self.drop(x)
x = self.conv_2(x * x_mask)
x = torch.relu(x)
x = self.norm_2(x)
x = self.drop(x)
x = self.proj(x * x_mask)
# x = torch.relu(x)
return x * x_mask
class DurationPredictorNS2(nn.Module):
def __init__(
self, in_channels, filter_channels, kernel_size, p_dropout=0.5
):
super().__init__()
self.in_channels = in_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.drop = nn.Dropout(p_dropout)
self.conv_1 = nn.Conv1d(
in_channels, filter_channels, kernel_size, padding=kernel_size // 2
)
self.norm_1 = LayerNorm(filter_channels)
self.module_list = nn.ModuleList()
self.module_list.append(self.conv_1)
self.module_list.append(nn.ReLU())
self.module_list.append(self.norm_1)
self.module_list.append(self.drop)
for i in range(12):
self.module_list.append(nn.Conv1d(filter_channels, filter_channels, kernel_size, padding=kernel_size // 2))
self.module_list.append(nn.ReLU())
self.module_list.append(LayerNorm(filter_channels))
self.module_list.append(nn.Dropout(p_dropout))
# attention layer every 3 layers
self.attn_list = nn.ModuleList()
for i in range(4):
self.attn_list.append(
Encoder(
filter_channels,
filter_channels,
8,
10,
3,
p_dropout=p_dropout,
)
)
for i in range(30):
if i+1 % 3 == 0:
self.module_list.append(self.attn_list[i//3])
self.proj = nn.Conv1d(filter_channels, 1, 1)
def forward(self, x, x_mask):
x = torch.detach(x)
for layer in self.module_list:
x = layer(x * x_mask)
x = self.proj(x * x_mask)
# x = torch.relu(x)
return x * x_mask
class RotaryPositionalEmbeddings(nn.Module):
"""
## RoPE module
Rotary encoding transforms pairs of features by rotating in the 2D plane.
That is, it organizes the $d$ features as $\frac{d}{2}$ pairs.
Each pair can be considered a coordinate in a 2D plane, and the encoding will rotate it
by an angle depending on the position of the token.
"""
def __init__(self, d: int, base: int = 10_000):
r"""
* `d` is the number of features $d$
* `base` is the constant used for calculating $\Theta$
"""
super().__init__()
self.base = base
self.d = int(d)
self.cos_cached = None
self.sin_cached = None
def _build_cache(self, x: torch.Tensor):
r"""
Cache $\cos$ and $\sin$ values
"""
# Return if cache is already built
if self.cos_cached is not None and x.shape[0] <= self.cos_cached.shape[0]:
return
# Get sequence length
seq_len = x.shape[0]
# $\Theta = {\theta_i = 10000^{-\frac{2(i-1)}{d}}, i \in [1, 2, ..., \frac{d}{2}]}$
theta = 1.0 / (self.base ** (torch.arange(0, self.d, 2).float() / self.d)).to(x.device)
# Create position indexes `[0, 1, ..., seq_len - 1]`
seq_idx = torch.arange(seq_len, device=x.device).float().to(x.device)
# Calculate the product of position index and $\theta_i$
idx_theta = torch.einsum("n,d->nd", seq_idx, theta)
# Concatenate so that for row $m$ we have
# $[m \theta_0, m \theta_1, ..., m \theta_{\frac{d}{2}}, m \theta_0, m \theta_1, ..., m \theta_{\frac{d}{2}}]$
idx_theta2 = torch.cat([idx_theta, idx_theta], dim=1)
# Cache them
self.cos_cached = idx_theta2.cos()[:, None, None, :]
self.sin_cached = idx_theta2.sin()[:, None, None, :]
def _neg_half(self, x: torch.Tensor):
# $\frac{d}{2}$
d_2 = self.d // 2
# Calculate $[-x^{(\frac{d}{2} + 1)}, -x^{(\frac{d}{2} + 2)}, ..., -x^{(d)}, x^{(1)}, x^{(2)}, ..., x^{(\frac{d}{2})}]$
return torch.cat([-x[:, :, :, d_2:], x[:, :, :, :d_2]], dim=-1)
def forward(self, x: torch.Tensor):
"""
* `x` is the Tensor at the head of a key or a query with shape `[seq_len, batch_size, n_heads, d]`
"""
# Cache $\cos$ and $\sin$ values
x = rearrange(x, "b h t d -> t b h d")
self._build_cache(x)
# Split the features, we can choose to apply rotary embeddings only to a partial set of features.
x_rope, x_pass = x[..., : self.d], x[..., self.d :]
# Calculate
# $[-x^{(\frac{d}{2} + 1)}, -x^{(\frac{d}{2} + 2)}, ..., -x^{(d)}, x^{(1)}, x^{(2)}, ..., x^{(\frac{d}{2})}]$
neg_half_x = self._neg_half(x_rope)
x_rope = (x_rope * self.cos_cached[: x.shape[0]]) + (neg_half_x * self.sin_cached[: x.shape[0]])
return rearrange(torch.cat((x_rope, x_pass), dim=-1), "t b h d -> b h t d")
class MultiHeadAttention(nn.Module):
def __init__(
self,
channels,
out_channels,
n_heads,
heads_share=True,
p_dropout=0.0,
proximal_bias=False,
proximal_init=False,
):
super().__init__()
assert channels % n_heads == 0
self.channels = channels
self.out_channels = out_channels
self.n_heads = n_heads
self.heads_share = heads_share
self.proximal_bias = proximal_bias
self.p_dropout = p_dropout
self.attn = None
self.k_channels = channels // n_heads
self.conv_q = torch.nn.Conv1d(channels, channels, 1)
self.conv_k = torch.nn.Conv1d(channels, channels, 1)
self.conv_v = torch.nn.Conv1d(channels, channels, 1)
# from https://nn.labml.ai/transformers/rope/index.html
self.query_rotary_pe = RotaryPositionalEmbeddings(self.k_channels * 0.5)
self.key_rotary_pe = RotaryPositionalEmbeddings(self.k_channels * 0.5)
self.conv_o = torch.nn.Conv1d(channels, out_channels, 1)
self.drop = torch.nn.Dropout(p_dropout)
torch.nn.init.xavier_uniform_(self.conv_q.weight)
torch.nn.init.xavier_uniform_(self.conv_k.weight)
if proximal_init:
self.conv_k.weight.data.copy_(self.conv_q.weight.data)
self.conv_k.bias.data.copy_(self.conv_q.bias.data)
torch.nn.init.xavier_uniform_(self.conv_v.weight)
def forward(self, x, c, attn_mask=None):
q = self.conv_q(x)
k = self.conv_k(c)
v = self.conv_v(c)
x, self.attn = self.attention(q, k, v, mask=attn_mask)
x = self.conv_o(x)
return x
def attention(self, query, key, value, mask=None):
b, d, t_s, t_t = (*key.size(), query.size(2))
query = rearrange(query, "b (h c) t-> b h t c", h=self.n_heads)
key = rearrange(key, "b (h c) t-> b h t c", h=self.n_heads)
value = rearrange(value, "b (h c) t-> b h t c", h=self.n_heads)
query = self.query_rotary_pe(query)
key = self.key_rotary_pe(key)
scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(self.k_channels)
if self.proximal_bias:
assert t_s == t_t, "Proximal bias is only available for self-attention."
scores = scores + self._attention_bias_proximal(t_s).to(device=scores.device, dtype=scores.dtype)
if mask is not None:
scores = scores.masked_fill(mask == 0, -1e4)
p_attn = torch.nn.functional.softmax(scores, dim=-1)
p_attn = self.drop(p_attn)
output = torch.matmul(p_attn, value)
output = output.transpose(2, 3).contiguous().view(b, d, t_t)
return output, p_attn
@staticmethod
def _attention_bias_proximal(length):
r = torch.arange(length, dtype=torch.float32)
diff = torch.unsqueeze(r, 0) - torch.unsqueeze(r, 1)
return torch.unsqueeze(torch.unsqueeze(-torch.log1p(torch.abs(diff)), 0), 0)
class FFN(nn.Module):
def __init__(self, in_channels, out_channels, filter_channels, kernel_size, p_dropout=0.0):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.filter_channels = filter_channels
self.kernel_size = kernel_size
self.p_dropout = p_dropout
self.conv_1 = torch.nn.Conv1d(in_channels, filter_channels, kernel_size, padding=kernel_size // 2)
self.conv_2 = torch.nn.Conv1d(filter_channels, out_channels, kernel_size, padding=kernel_size // 2)
self.drop = torch.nn.Dropout(p_dropout)
def forward(self, x, x_mask):
x = self.conv_1(x * x_mask)
x = torch.relu(x)
x = self.drop(x)
x = self.conv_2(x * x_mask)
return x * x_mask
class Encoder(nn.Module):
def __init__(
self,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size=1,
p_dropout=0.0,
**kwargs,
):
super().__init__()
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.drop = torch.nn.Dropout(p_dropout)
self.attn_layers = torch.nn.ModuleList()
self.norm_layers_1 = torch.nn.ModuleList()
self.ffn_layers = torch.nn.ModuleList()
self.norm_layers_2 = torch.nn.ModuleList()
for _ in range(self.n_layers):
self.attn_layers.append(MultiHeadAttention(hidden_channels, hidden_channels, n_heads, p_dropout=p_dropout))
self.norm_layers_1.append(LayerNorm(hidden_channels))
self.ffn_layers.append(
FFN(
hidden_channels,
hidden_channels,
filter_channels,
kernel_size,
p_dropout=p_dropout,
)
)
self.norm_layers_2.append(LayerNorm(hidden_channels))
def forward(self, x, x_mask):
attn_mask = x_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
for i in range(self.n_layers):
x = x * x_mask
y = self.attn_layers[i](x, x, attn_mask)
y = self.drop(y)
x = self.norm_layers_1[i](x + y)
y = self.ffn_layers[i](x, x_mask)
y = self.drop(y)
x = self.norm_layers_2[i](x + y)
x = x * x_mask
return x
class Decoder(nn.Module):
def __init__(
self,
hidden_channels,
filter_channels,
n_heads,
n_layers,
kernel_size=1,
p_dropout=0.0,
proximal_bias=False,
proximal_init=True,
**kwargs
):
super().__init__()
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.proximal_bias = proximal_bias
self.proximal_init = proximal_init
self.drop = nn.Dropout(p_dropout)
self.self_attn_layers = nn.ModuleList()
self.norm_layers_0 = nn.ModuleList()
self.encdec_attn_layers = nn.ModuleList()
self.norm_layers_1 = nn.ModuleList()
self.ffn_layers = nn.ModuleList()
self.norm_layers_2 = nn.ModuleList()
for i in range(self.n_layers):
self.self_attn_layers.append(
MultiHeadAttention(
hidden_channels,
hidden_channels,
n_heads,
p_dropout=p_dropout
)
)
self.norm_layers_0.append(LayerNorm(hidden_channels))
self.encdec_attn_layers.append(
MultiHeadAttention(
hidden_channels,
hidden_channels,
n_heads,
p_dropout=p_dropout
)
)
self.norm_layers_1.append(LayerNorm(hidden_channels))
self.ffn_layers.append(
FFN(
hidden_channels,
hidden_channels,
filter_channels,
kernel_size,
p_dropout=p_dropout,
)
)
self.norm_layers_2.append(LayerNorm(hidden_channels))
def forward(self, x, x_mask, h, h_mask):
"""
x: decoder input
h: encoder output
"""
self_attn_mask = commons.subsequent_mask(x_mask.size(2)).to(
device=x.device, dtype=x.dtype
)
encdec_attn_mask = h_mask.unsqueeze(2) * x_mask.unsqueeze(-1)
x = x * x_mask
for i in range(self.n_layers):
y = self.self_attn_layers[i](x, x, self_attn_mask)
y = self.drop(y)
x = self.norm_layers_0[i](x + y)
y = self.encdec_attn_layers[i](x, h, encdec_attn_mask)
y = self.drop(y)
x = self.norm_layers_1[i](x + y)
y = self.ffn_layers[i](x, x_mask)
y = self.drop(y)
x = self.norm_layers_2[i](x + y)
x = x * x_mask
return x
class TextEncoder(nn.Module):
def __init__(
self,
encoder_type,
encoder_params,
duration_predictor_params,
n_vocab,
speech_in_channels,
):
super().__init__()
self.encoder_type = encoder_type
self.n_vocab = n_vocab
self.n_feats = encoder_params.n_feats
self.n_channels = encoder_params.n_channels
self.emb = torch.nn.Embedding(n_vocab, self.n_channels)
torch.nn.init.normal_(self.emb.weight, 0.0, self.n_channels**-0.5)
self.speech_in_channels = speech_in_channels
self.speech_out_channels = self.n_channels
self.speech_prompt_proj = torch.nn.Conv1d(self.speech_in_channels, self.speech_out_channels, 1)
# self.speech_prompt_proj = PosteriorEncoder(
# self.speech_in_channels,
# self.speech_out_channels,
# self.speech_out_channels,
# 1,
# 1,
# 1,
# gin_channels=0,
# )
self.prenet = ConvReluNorm(
self.n_channels,
self.n_channels,
self.n_channels,
kernel_size=5,
n_layers=3,
p_dropout=0,
)
self.speech_prompt_encoder = Encoder(
encoder_params.n_channels,
encoder_params.filter_channels,
encoder_params.n_heads,
encoder_params.n_layers,
encoder_params.kernel_size,
encoder_params.p_dropout,
)
self.text_base_encoder = Encoder(
encoder_params.n_channels,
encoder_params.filter_channels,
encoder_params.n_heads,
encoder_params.n_layers,
encoder_params.kernel_size,
encoder_params.p_dropout,
)
self.decoder = Decoder(
encoder_params.n_channels,
encoder_params.filter_channels,
encoder_params.n_heads,
encoder_params.n_layers,
encoder_params.kernel_size,
encoder_params.p_dropout,
)
| self.transformerblock = BasicTransformerBlock( | 3 | 2023-11-11 16:08:17+00:00 | 8k |
ShipBit/wingman-ai | gui/root.py | [
{
"identifier": "NotificationBanner",
"path": "gui/components/notification_banner.py",
"snippet": "class NotificationBanner(ctk.CTkFrame):\n notification_level: dict[Printr.CHANNEL, Any] = {\n \"info\": {\"color\": (\"#113399\", \"#113399\"), \"font_color\": \"white\"},\n \"warning\": {... | from os import path
from sys import platform
from typing import Literal
from gui.components.notification_banner import NotificationBanner
from gui.sections.header import Header
from gui.views.context_view import ContextView
from gui.views.settings_view import SettingsView
from gui.views.about_view import AboutView
import tkinter as tk
import customtkinter as ctk | 3,673 |
class WingmanUI(ctk.CTk):
VIEWS = Literal["context", "settings", "about"]
_views: dict[VIEWS, ctk.CTkFrame | None] = dict(
context=None, settings=None, about=None
)
def __init__(self, core):
super().__init__()
self.core = core
self.about_window = None
ctk.set_appearance_mode(
self.core.config_manager.gui_config.get("appearance", "system")
)
# TODO: add themes
# ctk.set_default_color_theme(path.join(self.core.app_root_dir, "assets", "themes", "wingman-ai.json"))
self.title("Wingman AI")
self.geometry("1024x800+200+150")
self.minsize(400, 150)
# no way to set this on MacOS
self.iconbitmap(path.join(self.core.app_root_dir, "assets", "wingman-ai.ico"))
if platform == "darwin":
mac_dock_icon = tk.Image(
"photo",
file=path.join(
self.core.app_root_dir, "assets", "icons", "wingman-ai.png"
),
)
self.iconphoto(True, mac_dock_icon)
self.menubar = tk.Menu(self)
self.system_menu = tk.Menu(self.menubar, name="apple")
self.system_menu.add_command(label="Exit Wingman AI", command=self.quit)
self.menubar.add_cascade(label="System", menu=self.system_menu)
self.help_menu = tk.Menu(self.menubar, tearoff=0)
self.help_menu.add_command(
label="About Wingman AI", command=lambda: self.show_view("about")
)
self.menubar.add_cascade(label="Help", menu=self.help_menu)
self.config(menu=self.menubar)
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(1, weight=1)
self.header = Header(self, height=74, corner_radius=0)
self.header.grid(row=0, column=0, sticky="we")
view_grid = {"row": 1, "column": 0, "sticky": "nesw"}
self._views["about"] = AboutView(self, corner_radius=0, fg_color="transparent")
self._views["about"].grid(**view_grid)
|
class WingmanUI(ctk.CTk):
VIEWS = Literal["context", "settings", "about"]
_views: dict[VIEWS, ctk.CTkFrame | None] = dict(
context=None, settings=None, about=None
)
def __init__(self, core):
super().__init__()
self.core = core
self.about_window = None
ctk.set_appearance_mode(
self.core.config_manager.gui_config.get("appearance", "system")
)
# TODO: add themes
# ctk.set_default_color_theme(path.join(self.core.app_root_dir, "assets", "themes", "wingman-ai.json"))
self.title("Wingman AI")
self.geometry("1024x800+200+150")
self.minsize(400, 150)
# no way to set this on MacOS
self.iconbitmap(path.join(self.core.app_root_dir, "assets", "wingman-ai.ico"))
if platform == "darwin":
mac_dock_icon = tk.Image(
"photo",
file=path.join(
self.core.app_root_dir, "assets", "icons", "wingman-ai.png"
),
)
self.iconphoto(True, mac_dock_icon)
self.menubar = tk.Menu(self)
self.system_menu = tk.Menu(self.menubar, name="apple")
self.system_menu.add_command(label="Exit Wingman AI", command=self.quit)
self.menubar.add_cascade(label="System", menu=self.system_menu)
self.help_menu = tk.Menu(self.menubar, tearoff=0)
self.help_menu.add_command(
label="About Wingman AI", command=lambda: self.show_view("about")
)
self.menubar.add_cascade(label="Help", menu=self.help_menu)
self.config(menu=self.menubar)
self.grid_columnconfigure(0, weight=1)
self.grid_rowconfigure(1, weight=1)
self.header = Header(self, height=74, corner_radius=0)
self.header.grid(row=0, column=0, sticky="we")
view_grid = {"row": 1, "column": 0, "sticky": "nesw"}
self._views["about"] = AboutView(self, corner_radius=0, fg_color="transparent")
self._views["about"].grid(**view_grid)
| self._views["settings"] = SettingsView( | 3 | 2023-11-15 09:36:06+00:00 | 8k |
jeromeleong/mirrors-zhile-io-pandora | src/pandora/turbo/chat.py | [
{
"identifier": "Conversations",
"path": "src/pandora/turbo/base.py",
"snippet": "class Conversations:\n def __init__(self):\n self.__data = []\n\n def list(self, offset, limit):\n return len(self.__data), self.__data[offset: limit]\n\n def clear(self):\n self.__data = []\n... | import json
from datetime import datetime as dt
from os import getenv
from requests import Response
from .base import Conversations, UserPrompt, Prompt, SystemPrompt
from ..openai.api import ChatCompletion
from ..openai.token import gpt_num_tokens | 3,617 | if not conversation:
return self.__out_error('Conversation not found', 404)
if 'New chat' != conversation.title:
message = {
'message': 'Conversation {} already has title \'{}\''.format(conversation_id, conversation.title)
}
return self.__wrap_response(message)
messages = conversation.get_messages_directly(message_id)
messages.append({'role': 'user', 'content': self.TITLE_PROMPT})
status, header, generator = self.api.request(self.get_access_token(token), model, messages, False)
last_ok, last = self.__get_completion(status, next(generator))
if not last_ok:
return self.__out_error(last['detail'], status)
conversation.set_title(last.strip('"'))
result = {
'title': conversation.title
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('generate title failed: ' + resp.text)
return resp.json()['title']
def set_conversation_title(self, conversation_id, title, raw=False, token=None):
def __shadow():
try:
conversation = self.__get_conversations(token).guard_get(conversation_id)
except Exception as e:
return self.__out_error(str(e), 404)
conversation.set_title(title)
result = {
'success': True
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('update conversation failed: ' + resp.json()['detail'])
return resp.json()['success']
def talk(self, content, model, message_id, parent_message_id, conversation_id=None, stream=True, token=None):
system_prompt = None
if conversation_id:
conversation = self.__get_conversations(token).get(conversation_id)
if not conversation:
return self.__out_error_stream('Conversation not found', 404)
parent = conversation.get_prompt(parent_message_id)
else:
conversation = self.__get_conversations(token).new()
parent = conversation.add_prompt(Prompt(parent_message_id))
parent = system_prompt = conversation.add_prompt(SystemPrompt(self.system_prompt, parent))
conversation.add_prompt(UserPrompt(message_id, content, parent))
user_prompt, gpt_prompt, messages = conversation.get_messages(message_id, model)
try:
status, headers, generator = self.api.request(self.get_access_token(token), model,
self.__reduce_messages(messages, model, token), stream)
except Exception as e:
return self.__out_error_stream(str(e))
def __out_generator():
if 200 == status and system_prompt and stream:
yield self.__out_stream(conversation, system_prompt)
yield self.__out_stream(conversation, user_prompt)
for line in generator:
yield self.__map_conversation(status, conversation, gpt_prompt, line)
return status, headers, __out_generator()
def goon(self, model, parent_message_id, conversation_id, stream=True, token=None):
return self.regenerate_reply(None, model, conversation_id, parent_message_id, None, stream, token)
def regenerate_reply(self, prompt, model, conversation_id, message_id, parent_message_id, stream=True, token=None):
if not conversation_id:
return self.__out_error_stream('Miss conversation_id', 400)
conversation = self.__get_conversations(token).get(conversation_id)
if not conversation:
return self.__out_error_stream('Conversation not found', 404)
user_prompt, gpt_prompt, messages = conversation.get_messages(message_id, model)
try:
status, headers, generator = self.api.request(self.get_access_token(token), model,
self.__reduce_messages(messages, model, token), stream)
except Exception as e:
return self.__out_error_stream(str(e))
def __out_generator():
for line in generator:
yield self.__map_conversation(status, conversation, gpt_prompt, line)
return status, headers, __out_generator()
def __reduce_messages(self, messages, model, token=None):
max_tokens = self.FAKE_TOKENS[model] if self.__is_fake_api(token) else self.MAX_TOKENS[model]
| # -*- coding: utf-8 -*-
class TurboGPT:
DEFAULT_SYSTEM_PROMPT = 'You are ChatGPT, a large language model trained by OpenAI. ' \
'Answer as concisely as possible.\nKnowledge cutoff: 2021-09-01\n' \
'Current date: {}'.format(dt.now().strftime('%Y-%m-%d'))
TITLE_PROMPT = 'Generate a brief title for our conversation.'
MAX_TOKENS = {
'gpt-3.5-turbo': 4096,
'gpt-4': 8192,
'gpt-4-32k': 32768,
}
FAKE_TOKENS = {
'gpt-3.5-turbo': 8191,
'gpt-4': 4095,
'gpt-4-32k': 8195,
}
def __init__(self, api_keys: dict, proxy=None):
self.api_keys = api_keys
self.api_keys_key_list = list(api_keys)
self.default_api_keys_key = self.api_keys_key_list[0]
self.api = ChatCompletion(proxy)
self.conversations_map = {}
self.system_prompt = getenv('API_SYSTEM_PROMPT', self.DEFAULT_SYSTEM_PROMPT)
def __get_conversations(self, api_keys_key=None):
if api_keys_key is None:
api_keys_key = self.default_api_keys_key
if api_keys_key not in self.conversations_map:
self.conversations_map[api_keys_key] = Conversations()
return self.conversations_map[api_keys_key]
def __is_fake_api(self, token=None):
api_key = self.get_access_token(token)
return api_key.startswith('fk-') or api_key.startswith('pk-')
def get_access_token(self, token_key=None):
return self.api_keys[token_key or self.default_api_keys_key]
def list_token_keys(self):
return self.api_keys_key_list
def list_models(self, raw=False, token=None):
fake_api = self.__is_fake_api(token)
models = {
'models': [
{
'slug': 'gpt-3.5-turbo',
'max_tokens': self.FAKE_TOKENS['gpt-3.5-turbo'] if fake_api else self.MAX_TOKENS['gpt-3.5-turbo'],
'title': 'GPT-3.5',
'description': 'Turbo is the api model that powers ChatGPT',
'tags': []
},
{
'slug': 'gpt-4',
'max_tokens': self.FAKE_TOKENS['gpt-4'] if fake_api else self.MAX_TOKENS['gpt-4'],
'title': 'GPT-4',
'description': 'More capable than any GPT-3.5, able to do complex tasks, and optimized for chat',
'tags': []
},
{
'slug': 'gpt-4-32k',
'max_tokens': self.FAKE_TOKENS['gpt-4-32k'] if fake_api else self.MAX_TOKENS['gpt-4-32k'],
'title': 'GPT-4 32K',
'description': 'Same capabilities as the base gpt-4 mode but with 4x the context length',
'tags': []
}
]
}
if raw:
return self.__wrap_response(models)
return models['models']
def list_conversations(self, offset, limit, raw=False, token=None):
offset = int(offset)
limit = int(limit)
total, items = self.__get_conversations(token).list(offset, limit)
stripped = []
for item in items:
stripped.append({
'id': item.conversation_id,
'title': item.title,
'create_time': dt.utcfromtimestamp(item.create_time).isoformat(),
})
result = {'items': stripped, 'total': total, 'limit': limit, 'offset': offset}
if raw:
return self.__wrap_response(result)
return result
def get_conversation(self, conversation_id, raw=False, token=None):
def __shadow():
try:
conversation = self.__get_conversations(token).guard_get(conversation_id)
except Exception as e:
return self.__out_error(str(e), 404)
return self.__wrap_response(conversation.get_info())
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('get conversation failed: ' + resp.json()['detail'])
return resp.json()
def clear_conversations(self, raw=False, token=None):
def __shadow():
self.__get_conversations(token).clear()
result = {
'success': True
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
return resp.json()['success']
def del_conversation(self, conversation_id, raw=False, token=None):
def __shadow():
conversations = self.__get_conversations(token)
try:
conversation = conversations.guard_get(conversation_id)
except Exception as e:
return self.__out_error(str(e), 404)
conversations.delete(conversation)
result = {
'success': True
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('delete conversation failed: ' + resp.json()['detail'])
return resp.json()['success']
def gen_conversation_title(self, conversation_id, model, message_id, raw=False, token=None):
def __shadow():
conversation = self.__get_conversations(token).get(conversation_id)
if not conversation:
return self.__out_error('Conversation not found', 404)
if 'New chat' != conversation.title:
message = {
'message': 'Conversation {} already has title \'{}\''.format(conversation_id, conversation.title)
}
return self.__wrap_response(message)
messages = conversation.get_messages_directly(message_id)
messages.append({'role': 'user', 'content': self.TITLE_PROMPT})
status, header, generator = self.api.request(self.get_access_token(token), model, messages, False)
last_ok, last = self.__get_completion(status, next(generator))
if not last_ok:
return self.__out_error(last['detail'], status)
conversation.set_title(last.strip('"'))
result = {
'title': conversation.title
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('generate title failed: ' + resp.text)
return resp.json()['title']
def set_conversation_title(self, conversation_id, title, raw=False, token=None):
def __shadow():
try:
conversation = self.__get_conversations(token).guard_get(conversation_id)
except Exception as e:
return self.__out_error(str(e), 404)
conversation.set_title(title)
result = {
'success': True
}
return self.__wrap_response(result)
resp = __shadow()
if raw:
return resp
if resp.status_code != 200:
raise Exception('update conversation failed: ' + resp.json()['detail'])
return resp.json()['success']
def talk(self, content, model, message_id, parent_message_id, conversation_id=None, stream=True, token=None):
system_prompt = None
if conversation_id:
conversation = self.__get_conversations(token).get(conversation_id)
if not conversation:
return self.__out_error_stream('Conversation not found', 404)
parent = conversation.get_prompt(parent_message_id)
else:
conversation = self.__get_conversations(token).new()
parent = conversation.add_prompt(Prompt(parent_message_id))
parent = system_prompt = conversation.add_prompt(SystemPrompt(self.system_prompt, parent))
conversation.add_prompt(UserPrompt(message_id, content, parent))
user_prompt, gpt_prompt, messages = conversation.get_messages(message_id, model)
try:
status, headers, generator = self.api.request(self.get_access_token(token), model,
self.__reduce_messages(messages, model, token), stream)
except Exception as e:
return self.__out_error_stream(str(e))
def __out_generator():
if 200 == status and system_prompt and stream:
yield self.__out_stream(conversation, system_prompt)
yield self.__out_stream(conversation, user_prompt)
for line in generator:
yield self.__map_conversation(status, conversation, gpt_prompt, line)
return status, headers, __out_generator()
def goon(self, model, parent_message_id, conversation_id, stream=True, token=None):
return self.regenerate_reply(None, model, conversation_id, parent_message_id, None, stream, token)
def regenerate_reply(self, prompt, model, conversation_id, message_id, parent_message_id, stream=True, token=None):
if not conversation_id:
return self.__out_error_stream('Miss conversation_id', 400)
conversation = self.__get_conversations(token).get(conversation_id)
if not conversation:
return self.__out_error_stream('Conversation not found', 404)
user_prompt, gpt_prompt, messages = conversation.get_messages(message_id, model)
try:
status, headers, generator = self.api.request(self.get_access_token(token), model,
self.__reduce_messages(messages, model, token), stream)
except Exception as e:
return self.__out_error_stream(str(e))
def __out_generator():
for line in generator:
yield self.__map_conversation(status, conversation, gpt_prompt, line)
return status, headers, __out_generator()
def __reduce_messages(self, messages, model, token=None):
max_tokens = self.FAKE_TOKENS[model] if self.__is_fake_api(token) else self.MAX_TOKENS[model]
| while gpt_num_tokens(messages) > max_tokens - 200: | 5 | 2023-11-12 10:31:05+00:00 | 8k |
dubverse-ai/MahaTTS | maha_tts/inference.py | [
{
"identifier": "load_diff_model",
"path": "maha_tts/models/diff_model.py",
"snippet": "def load_diff_model(checkpoint,device,model_channels=512,ar_active=False,len_code_labels=10004):\n diff_model = DiffModel(input_channels=80,\n output_channels=160,\n model_channels=... | import torch,glob,os,requests
import numpy as np
import torch.nn.functional as F
from tqdm import tqdm
from librosa.filters import mel as librosa_mel_fn
from scipy.io.wavfile import write
from scipy.special import softmax
from maha_tts.models.diff_model import load_diff_model
from maha_tts.models.autoregressive import load_TS_model
from maha_tts.models.vocoder import load_vocoder_model,infer_wav
from maha_tts.utils.audio import denormalize_tacotron_mel,normalize_tacotron_mel,load_wav_to_torch,dynamic_range_compression
from maha_tts.utils.stft import STFT
from maha_tts.utils.diffusion import SpacedDiffusion,get_named_beta_schedule,space_timesteps
from maha_tts.text.symbols import labels,text_labels,text_labels_en,code_labels,text_enc,text_dec,code_enc,code_dec,text_enc_en,text_dec_en
from maha_tts.text.cleaners import english_cleaners
from maha_tts.config import config | 5,885 | download_file(model_dirs[name][0],checkpoint_voco)
download_file(model_dirs[name][1],voco_config_path)
else:
download_file(model_dirs[name][0],checkpoint_diff)
download_file(model_dirs[name][1],checkpoint_ts)
def load_models(name,device=torch.device('cpu')):
'''
Load pre-trained models for different components of a text-to-speech system.
Args:
device (str): The target device for model loading (e.g., 'cpu' or 'cuda').
checkpoint_diff (str): File path to the pre-trained model checkpoint for the diffusion model.
checkpoint_ts (str): File path to the pre-trained model checkpoint for the text-to-semantic model.
checkpoint_voco (str): File path to the pre-trained model checkpoint for the vocoder model.
voco_config_path (str): File path to the configuration file for the vocoder model.
Returns:
diff_model (object): Loaded diffusion model for semantic-to-acoustic tokens.
ts_model (object): Loaded text-to-semantic model for converting text-to-semantic tokens.
vocoder (object): Loaded vocoder model for generating waveform from acoustic tokens.
diffuser (object): Configured diffuser object for use in the diffusion model.
'''
assert name in model_dirs, "no model name "+name
checkpoint_diff = os.path.join(DEFAULT_MODELS_DIR,name,'s2a_latest.pt')
checkpoint_ts = os.path.join(DEFAULT_MODELS_DIR,name,'t2s_best.pt')
checkpoint_voco = os.path.join(DEFAULT_MODELS_DIR,'hifigan','g_02500000')
voco_config_path = os.path.join(DEFAULT_MODELS_DIR,'hifigan','config.json')
# for i in [checkpoint_diff,checkpoint_ts,checkpoint_voco,voco_config_path]:
if not os.path.exists(checkpoint_diff) or not os.path.exists(checkpoint_ts):
download_model(name)
if not os.path.exists(checkpoint_voco) or not os.path.exists(voco_config_path):
download_model('hifigan')
diff_model = load_diff_model(checkpoint_diff,device)
ts_model = load_TS_model(checkpoint_ts,device,name)
vocoder = load_vocoder_model(voco_config_path,checkpoint_voco,device)
diffuser = load_diffuser()
return diff_model,ts_model,vocoder,diffuser
def infer_mel(model,timeshape,code,ref_mel,diffuser,temperature=1.0):
device = next(model.parameters()).device
code = code.to(device)
ref_mel =ref_mel.to(device)
output_shape = (1,80,timeshape)
noise = torch.randn(output_shape, device=code.device) * temperature
mel = diffuser.p_sample_loop(model, output_shape, noise=noise,
model_kwargs={'code_emb': code,'ref_clips':ref_mel},
progress=True)
return denormalize_tacotron_mel(mel)
def generate_semantic_tokens(
text,
model,
ref_mels,
language=None,
temp = 0.7,
top_p= None,
top_k= 1,
n_tot_steps = 1000,
device = None
):
semb = []
with torch.no_grad():
for n in tqdm(range(n_tot_steps)):
x = get_inputs(text,semb,ref_mels,device,model.name)
_,result = model(**x,language=language)
relevant_logits = result[0,:,-1]
if top_p is not None:
# faster to convert to numpy
original_device = relevant_logits.device
relevant_logits = relevant_logits.detach().cpu().type(torch.float32).numpy()
sorted_indices = np.argsort(relevant_logits)[::-1]
sorted_logits = relevant_logits[sorted_indices]
cumulative_probs = np.cumsum(softmax(sorted_logits))
sorted_indices_to_remove = cumulative_probs > top_p
sorted_indices_to_remove[1:] = sorted_indices_to_remove[:-1].copy()
sorted_indices_to_remove[0] = False
relevant_logits[sorted_indices[sorted_indices_to_remove]] = -np.inf
relevant_logits = torch.from_numpy(relevant_logits)
relevant_logits = relevant_logits.to(original_device)
if top_k is not None:
v, _ = torch.topk(relevant_logits, min(top_k, relevant_logits.size(-1)))
relevant_logits[relevant_logits < v[-1]] = -float("Inf")
probs = F.softmax(relevant_logits / temp, dim=-1)
item_next = torch.multinomial(probs, num_samples=1).to(torch.int32)
semb.append(str(code_dec[item_next.item()]))
if semb[-1] == '<EST>' or semb[-1] == '<PAD>':
break
del relevant_logits, probs, item_next
semb = torch.tensor([int(i) for i in semb[:-1]])
return semb,result
def get_inputs(text,semb=[],ref_mels=[],device=torch.device('cpu'),name = 'Smolie-in'):
text = text.lower()
if name=='Smolie-en':
text_ids=[text_enc_en['<S>']]+[text_enc_en[i] for i in text.strip()]+[text_enc_en['<E>']]
else:
text_ids=[text_enc['<S>']]+[text_enc[i] for i in text.strip()]+[text_enc['<E>']]
semb_ids=[code_enc['<SST>']]+[code_enc[i] for i in semb]#+[tok_enc['<EST>']]
input_ids = text_ids+semb_ids
# pad_length = config.t2s_position-(len(text_ids)+len(semb_ids))
token_type_ids = [0]*len(text_ids)+[1]*len(semb_ids)#+[0]*pad_length
positional_ids = [i for i in range(len(text_ids))]+[i for i in range(len(semb_ids))]#+[0]*pad_length
# labels = [-100]*len(text_ids)+semb_ids+[-100]*pad_length
attention_mask = [1]*len(input_ids)#+[0]*pad_length
# input_ids += [tok_enc['<PAD>']]*pad_length
|
DEFAULT_MODELS_DIR = os.path.join(os.path.expanduser('~'), '.cache', 'maha_tts', 'models')
stft_fn = STFT(config.filter_length, config.hop_length, config.win_length)
mel_basis = librosa_mel_fn(
sr=config.sampling_rate, n_fft=config.filter_length, n_mels=config.n_mel_channels, fmin=config.mel_fmin, fmax=config.mel_fmax)
mel_basis = torch.from_numpy(mel_basis).float()
model_dirs= {
'Smolie-en':['https://huggingface.co/Dubverse/MahaTTS/resolve/main/maha_tts/pretrained_models/Smolie-en/s2a_latest.pt',
'https://huggingface.co/Dubverse/MahaTTS/resolve/main/maha_tts/pretrained_models/Smolie-en/t2s_best.pt'],
'Smolie-in':['https://huggingface.co/Dubverse/MahaTTS/resolve/main/maha_tts/pretrained_models/Smolie-in/s2a_latest.pt',
'https://huggingface.co/Dubverse/MahaTTS/resolve/main/maha_tts/pretrained_models/Smolie-in/t2s_best.pt'],
'hifigan':['https://huggingface.co/Dubverse/MahaTTS/resolve/main/maha_tts/pretrained_models/hifigan/g_02500000',
'https://huggingface.co/Dubverse/MahaTTS/resolve/main/maha_tts/pretrained_models/hifigan/config.json']
}
def download_file(url, filename):
response = requests.get(url, stream=True)
total_size = int(response.headers.get('content-length', 0))
# Check if the response was successful (status code 200)
response.raise_for_status()
with open(filename, 'wb') as file, tqdm(
desc=filename,
total=total_size,
unit='B',
unit_scale=True,
unit_divisor=1024,
) as bar:
for data in response.iter_content(chunk_size=1024):
# Write data to the file
file.write(data)
# Update the progress bar
bar.update(len(data))
print(f"Download complete: {filename}\n")
def download_model(name):
print('Downloading ',name," ....")
checkpoint_diff = os.path.join(DEFAULT_MODELS_DIR,name,'s2a_latest.pt')
checkpoint_ts = os.path.join(DEFAULT_MODELS_DIR,name,'t2s_best.pt')
checkpoint_voco = os.path.join(DEFAULT_MODELS_DIR,'hifigan','g_02500000')
voco_config_path = os.path.join(DEFAULT_MODELS_DIR,'hifigan','config.json')
os.makedirs(os.path.join(DEFAULT_MODELS_DIR,name),exist_ok=True)
if name == 'hifigan':
download_file(model_dirs[name][0],checkpoint_voco)
download_file(model_dirs[name][1],voco_config_path)
else:
download_file(model_dirs[name][0],checkpoint_diff)
download_file(model_dirs[name][1],checkpoint_ts)
def load_models(name,device=torch.device('cpu')):
'''
Load pre-trained models for different components of a text-to-speech system.
Args:
device (str): The target device for model loading (e.g., 'cpu' or 'cuda').
checkpoint_diff (str): File path to the pre-trained model checkpoint for the diffusion model.
checkpoint_ts (str): File path to the pre-trained model checkpoint for the text-to-semantic model.
checkpoint_voco (str): File path to the pre-trained model checkpoint for the vocoder model.
voco_config_path (str): File path to the configuration file for the vocoder model.
Returns:
diff_model (object): Loaded diffusion model for semantic-to-acoustic tokens.
ts_model (object): Loaded text-to-semantic model for converting text-to-semantic tokens.
vocoder (object): Loaded vocoder model for generating waveform from acoustic tokens.
diffuser (object): Configured diffuser object for use in the diffusion model.
'''
assert name in model_dirs, "no model name "+name
checkpoint_diff = os.path.join(DEFAULT_MODELS_DIR,name,'s2a_latest.pt')
checkpoint_ts = os.path.join(DEFAULT_MODELS_DIR,name,'t2s_best.pt')
checkpoint_voco = os.path.join(DEFAULT_MODELS_DIR,'hifigan','g_02500000')
voco_config_path = os.path.join(DEFAULT_MODELS_DIR,'hifigan','config.json')
# for i in [checkpoint_diff,checkpoint_ts,checkpoint_voco,voco_config_path]:
if not os.path.exists(checkpoint_diff) or not os.path.exists(checkpoint_ts):
download_model(name)
if not os.path.exists(checkpoint_voco) or not os.path.exists(voco_config_path):
download_model('hifigan')
diff_model = load_diff_model(checkpoint_diff,device)
ts_model = load_TS_model(checkpoint_ts,device,name)
vocoder = load_vocoder_model(voco_config_path,checkpoint_voco,device)
diffuser = load_diffuser()
return diff_model,ts_model,vocoder,diffuser
def infer_mel(model,timeshape,code,ref_mel,diffuser,temperature=1.0):
device = next(model.parameters()).device
code = code.to(device)
ref_mel =ref_mel.to(device)
output_shape = (1,80,timeshape)
noise = torch.randn(output_shape, device=code.device) * temperature
mel = diffuser.p_sample_loop(model, output_shape, noise=noise,
model_kwargs={'code_emb': code,'ref_clips':ref_mel},
progress=True)
return denormalize_tacotron_mel(mel)
def generate_semantic_tokens(
text,
model,
ref_mels,
language=None,
temp = 0.7,
top_p= None,
top_k= 1,
n_tot_steps = 1000,
device = None
):
semb = []
with torch.no_grad():
for n in tqdm(range(n_tot_steps)):
x = get_inputs(text,semb,ref_mels,device,model.name)
_,result = model(**x,language=language)
relevant_logits = result[0,:,-1]
if top_p is not None:
# faster to convert to numpy
original_device = relevant_logits.device
relevant_logits = relevant_logits.detach().cpu().type(torch.float32).numpy()
sorted_indices = np.argsort(relevant_logits)[::-1]
sorted_logits = relevant_logits[sorted_indices]
cumulative_probs = np.cumsum(softmax(sorted_logits))
sorted_indices_to_remove = cumulative_probs > top_p
sorted_indices_to_remove[1:] = sorted_indices_to_remove[:-1].copy()
sorted_indices_to_remove[0] = False
relevant_logits[sorted_indices[sorted_indices_to_remove]] = -np.inf
relevant_logits = torch.from_numpy(relevant_logits)
relevant_logits = relevant_logits.to(original_device)
if top_k is not None:
v, _ = torch.topk(relevant_logits, min(top_k, relevant_logits.size(-1)))
relevant_logits[relevant_logits < v[-1]] = -float("Inf")
probs = F.softmax(relevant_logits / temp, dim=-1)
item_next = torch.multinomial(probs, num_samples=1).to(torch.int32)
semb.append(str(code_dec[item_next.item()]))
if semb[-1] == '<EST>' or semb[-1] == '<PAD>':
break
del relevant_logits, probs, item_next
semb = torch.tensor([int(i) for i in semb[:-1]])
return semb,result
def get_inputs(text,semb=[],ref_mels=[],device=torch.device('cpu'),name = 'Smolie-in'):
text = text.lower()
if name=='Smolie-en':
text_ids=[text_enc_en['<S>']]+[text_enc_en[i] for i in text.strip()]+[text_enc_en['<E>']]
else:
text_ids=[text_enc['<S>']]+[text_enc[i] for i in text.strip()]+[text_enc['<E>']]
semb_ids=[code_enc['<SST>']]+[code_enc[i] for i in semb]#+[tok_enc['<EST>']]
input_ids = text_ids+semb_ids
# pad_length = config.t2s_position-(len(text_ids)+len(semb_ids))
token_type_ids = [0]*len(text_ids)+[1]*len(semb_ids)#+[0]*pad_length
positional_ids = [i for i in range(len(text_ids))]+[i for i in range(len(semb_ids))]#+[0]*pad_length
# labels = [-100]*len(text_ids)+semb_ids+[-100]*pad_length
attention_mask = [1]*len(input_ids)#+[0]*pad_length
# input_ids += [tok_enc['<PAD>']]*pad_length | return {'text_ids':torch.tensor(text_ids).unsqueeze(0).to(device),'codes_ids':torch.tensor(semb_ids).unsqueeze(0).to(device),'ref_clips':normalize_tacotron_mel(ref_mels).to(device)} | 5 | 2023-11-16 09:44:54+00:00 | 8k |
wjun0830/CGDETR | run_on_video/CLIP_ckpt/qvhighlights_onlyCLIP/model.py | [
{
"identifier": "generalized_temporal_iou",
"path": "cg_detr/span_utils.py",
"snippet": "def generalized_temporal_iou(spans1, spans2):\n \"\"\"\n Generalized IoU from https://giou.stanford.edu/\n Also reference to DETR implementation of generalized_box_iou\n https://github.com/facebookresear... | import torch
import torch.nn.functional as F
import numpy as np
import copy
from torch import nn
from cg_detr.span_utils import generalized_temporal_iou, span_cxw_to_xx
from cg_detr.matcher import build_matcher
from cg_detr.transformer import build_transformer, TransformerEncoderLayer, TransformerEncoder
from cg_detr.position_encoding import build_position_encoding
from cg_detr.misc import accuracy | 5,814 | return losses
def _get_src_permutation_idx(self, indices):
# permute predictions following indices
batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])
src_idx = torch.cat([src for (src, _) in indices])
return batch_idx, src_idx # two 1D tensors of the same length
def _get_tgt_permutation_idx(self, indices):
# permute targets following indices
batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])
tgt_idx = torch.cat([tgt for (_, tgt) in indices])
return batch_idx, tgt_idx
def get_loss(self, loss, outputs, targets, indices, **kwargs):
loss_map = {
"spans": self.loss_spans,
"labels": self.loss_labels,
"contrastive_align": self.loss_contrastive_align,
"saliency": self.loss_saliency,
"ms_align": self.loss_contrastive_moment_sentence,
"distill": self.loss_moment2txt_sim_distill,
"orthogonal_dummy":self.loss_orthogonal_dummy
}
assert loss in loss_map, f'do you really want to compute {loss} loss?'
return loss_map[loss](outputs, targets, indices, **kwargs)
def forward(self, outputs, targets):
""" This performs the loss computation.
Parameters:
outputs: dict of tensors, see the output specification of the model for the format
targets: list of dicts, such that len(targets) == batch_size.
The expected keys in each dict depends on the losses applied, see each loss' doc
"""
outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs'}
# Retrieve the matching between the outputs of the last layer and the targets
# list(tuples), each tuple is (pred_span_indices, tgt_span_indices)
# only for HL, do not use matcher
if self.use_matcher:
indices = self.matcher(outputs_without_aux, targets)
losses_target = self.losses
else:
indices = None
losses_target = ["saliency"]
# Compute all the requested losses
losses = {}
# for loss in self.losses:
for loss in losses_target:
losses.update(self.get_loss(loss, outputs, targets, indices))
# In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
if 'aux_outputs' in outputs:
for i, aux_outputs in enumerate(outputs['aux_outputs']):
# indices = self.matcher(aux_outputs, targets)
if self.use_matcher:
indices = self.matcher(aux_outputs, targets)
losses_target = self.losses
else:
indices = None
losses_target = ["saliency", "ms_align", "distill", "orthogonal_dummy"]
for loss in losses_target:
if "saliency" == loss: # skip as it is only in the top layer
continue
if "ms_align" == loss:
continue
if "distill" == loss:
continue
if "orthogonal_dummy" == loss:
continue
kwargs = {}
l_dict = self.get_loss(loss, aux_outputs, targets, indices, **kwargs)
l_dict = {k + f'_{i}': v for k, v in l_dict.items()}
losses.update(l_dict)
return losses
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
super().__init__()
self.num_layers = num_layers
h = [hidden_dim] * (num_layers - 1)
self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
def forward(self, x):
for i, layer in enumerate(self.layers):
x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
return x
class LinearLayer(nn.Module):
"""linear layer configurable with layer normalization, dropout, ReLU."""
def __init__(self, input_dim, output_dim, layer_norm=True, dropout=0.1, relu=True):
super(LinearLayer, self).__init__()
self.relu = relu
self.layer_norm = layer_norm
if layer_norm:
self.LayerNorm = nn.LayerNorm(input_dim)
layers = [
nn.Dropout(dropout),
nn.Linear(input_dim, output_dim)
]
self.net = nn.Sequential(*layers)
def forward(self, x):
"""(N, L, D)"""
if self.layer_norm:
x = self.LayerNorm(x)
x = self.net(x)
if self.relu:
x = F.relu(x, inplace=True)
return x # (N, L, D)
def build_model(args):
device = torch.device(args.device)
transformer = build_transformer(args)
| # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
CG-DETR model and criterion classes.
"""
def inverse_sigmoid(x, eps=1e-3):
x = x.clamp(min=0, max=1)
x1 = x.clamp(min=eps)
x2 = (1 - x).clamp(min=eps)
return torch.log(x1/x2)
def init_weights(module):
if isinstance(module, (nn.Linear, nn.Embedding)):
module.weight.data.normal_(mean=0.0, std=0.02)
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
if isinstance(module, nn.Linear) and module.bias is not None:
module.bias.data.zero_()
def find_nth(vid, underline, n):
max_len = len(vid)
start = vid.find(underline)
while start >= 0 and n > 1:
start = vid.find(underline, start+len(underline))
n -= 1
if start == -1:
start = max_len
return start
def element_wise_list_equal(listA, listB):
res = []
for a, b in zip(listA, listB):
if a==b:
res.append(True)
else:
res.append(False)
return res
class CGDETR(nn.Module):
""" CG DETR. """
def __init__(self, transformer, position_embed, txt_position_embed, txt_dim, vid_dim,
num_queries, input_dropout, aux_loss=False,
contrastive_align_loss=False, contrastive_hdim=64,
max_v_l=75, span_loss_type="l1", use_txt_pos=False, n_input_proj=2, aud_dim=0, args=None):
""" Initializes the model.
Parameters:
transformer: torch module of the transformer architecture. See transformer.py
position_embed: torch module of the position_embedding, See position_encoding.py
txt_position_embed: position_embedding for text
txt_dim: int, text query input dimension
vid_dim: int, video feature input dimension
num_queries: number of object queries, ie detection slot. This is the maximal number of objects
CG-DETR can detect in a single video.
aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
contrastive_align_loss: If true, perform span - tokens contrastive learning
contrastive_hdim: dimension used for projecting the embeddings before computing contrastive loss
max_v_l: int, maximum #clips in videos
span_loss_type: str, one of [l1, ce]
l1: (center-x, width) regression.
ce: (st_idx, ed_idx) classification.
# foreground_thd: float, intersection over prediction >= foreground_thd: labeled as foreground
# background_thd: float, intersection over prediction <= background_thd: labeled background
"""
super().__init__()
self.args=args
self.num_queries = num_queries
self.transformer = transformer
self.position_embed = position_embed
self.txt_position_embed = txt_position_embed
hidden_dim = transformer.d_model
self.span_loss_type = span_loss_type
self.max_v_l = max_v_l
span_pred_dim = 2 if span_loss_type == "l1" else max_v_l * 2
self.span_embed = MLP(hidden_dim, hidden_dim, span_pred_dim, 3)
self.class_embed = nn.Linear(hidden_dim, 2) # 0: background, 1: foreground
self.token_type_embeddings = nn.Embedding(2, hidden_dim)
self.token_type_embeddings.apply(init_weights)
self.use_txt_pos = use_txt_pos
self.n_input_proj = n_input_proj
self.query_embed = nn.Embedding(num_queries, 2)
relu_args = [True] * 3
relu_args[n_input_proj-1] = False
self.input_txt_proj = nn.Sequential(*[
LinearLayer(txt_dim, hidden_dim, layer_norm=True, dropout=input_dropout, relu=relu_args[0]),
LinearLayer(hidden_dim, hidden_dim, layer_norm=True, dropout=input_dropout, relu=relu_args[1]),
LinearLayer(hidden_dim, hidden_dim, layer_norm=True, dropout=input_dropout, relu=relu_args[2])
][:n_input_proj])
self.input_vid_proj = nn.Sequential(*[
LinearLayer(vid_dim + aud_dim, hidden_dim, layer_norm=True, dropout=input_dropout, relu=relu_args[0]),
LinearLayer(hidden_dim, hidden_dim, layer_norm=True, dropout=input_dropout, relu=relu_args[1]),
LinearLayer(hidden_dim, hidden_dim, layer_norm=True, dropout=input_dropout, relu=relu_args[2])
][:n_input_proj])
self.contrastive_align_loss = contrastive_align_loss
if contrastive_align_loss:
self.contrastive_align_projection_query = nn.Linear(hidden_dim, contrastive_hdim)
self.contrastive_align_projection_txt = nn.Linear(hidden_dim, contrastive_hdim)
self.contrastive_align_projection_vid = nn.Linear(hidden_dim, contrastive_hdim)
self.saliency_proj1 = nn.Linear(hidden_dim, hidden_dim)
self.saliency_proj2 = nn.Linear(hidden_dim, hidden_dim)
self.aux_loss = aux_loss
self.hidden_dim = hidden_dim
self.global_rep_token = torch.nn.Parameter(torch.randn(args.total_prompts, hidden_dim))
self.global_rep_pos = torch.nn.Parameter(torch.randn(1, hidden_dim))
self.moment_rep_token = torch.nn.Parameter(torch.randn(hidden_dim))
self.moment_rep_pos = torch.nn.Parameter(torch.randn(hidden_dim))
self.dummy_rep_token = torch.nn.Parameter(torch.randn(args.num_dummies, hidden_dim))
self.dummy_rep_pos = torch.nn.Parameter(torch.randn(args.num_dummies, hidden_dim))
normalize_before = False
self.sent_rep_token = torch.nn.Parameter(torch.randn(hidden_dim))
self.sent_rep_pos = torch.nn.Parameter(torch.randn(hidden_dim))
self.txt_proj_linear = LinearLayer(txt_dim, hidden_dim, layer_norm=True)
input_txt_sa_proj = TransformerEncoderLayer(hidden_dim, 8, self.args.dim_feedforward, 0.1, "prelu", normalize_before)
txtproj_encoder_norm = nn.LayerNorm(hidden_dim) if normalize_before else None
self.txtproj_encoder = TransformerEncoder(input_txt_sa_proj, args.dummy_layers, txtproj_encoder_norm)
scls_encoder_layer = TransformerEncoderLayer(hidden_dim, 8, self.args.dim_feedforward, 0.1, "prelu", normalize_before)
scls_encoder_norm = nn.LayerNorm(hidden_dim) if normalize_before else None
self.scls_encoder = TransformerEncoder(scls_encoder_layer, args.sent_layers, scls_encoder_norm)
def forward(self, src_txt, src_txt_mask, src_vid, src_vid_mask, vid, qid, src_aud=None, src_aud_mask=None, targets=None):
"""The forward expects two tensors:
- src_txt: [batch_size, L_txt, D_txt]
- src_txt_mask: [batch_size, L_txt], containing 0 on padded pixels,
will convert to 1 as padding later for transformer
- src_vid: [batch_size, L_vid, D_vid]
- src_vid_mask: [batch_size, L_vid], containing 0 on padded pixels,
will convert to 1 as padding later for transformer
It returns a dict with the following elements:
- "pred_spans": The normalized boxes coordinates for all queries, represented as
(center_x, width). These values are normalized in [0, 1],
relative to the size of each individual image (disregarding possible padding).
See PostProcess for information on how to retrieve the unnormalized bounding box.
- "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of
dictionnaries containing the two above keys for each decoder layer.
"""
_count = [v.count('_') for v in vid]
if self.args.dset_name == 'hl':
_position_to_cut = [find_nth(v, '_', _count[i]-1) for i, v in enumerate(vid)]
ori_vid = [v[:_position_to_cut[i]] for i, v in enumerate(vid)]
else:
ori_vid = [v for v in vid]
if src_aud is not None:
src_vid = torch.cat([src_vid, src_aud], dim=2)
src_vid = self.input_vid_proj(src_vid)
src_txt = self.input_txt_proj(src_txt)
src_vid = src_vid + self.token_type_embeddings(torch.full_like(src_vid_mask.long(), 1))
src_txt = src_txt + self.token_type_embeddings(torch.zeros_like(src_txt_mask.long()))
pos_vid = self.position_embed(src_vid, src_vid_mask) # (bsz, L_vid, d)
pos_txt = self.txt_position_embed(src_txt) if self.use_txt_pos else torch.zeros_like(src_txt) # (bsz, L_txt, d)
### insert dummy token in front of txt
txt_dummy = self.dummy_rep_token.reshape([1, self.args.num_dummies, self.hidden_dim]).repeat(src_txt.shape[0], 1, 1)
src_txt_dummy = torch.cat([txt_dummy, src_txt], dim=1)
mask_txt = torch.tensor([[True] * self.args.num_dummies]).to(src_txt_mask.device).repeat(src_txt_mask.shape[0], 1)
src_txt_mask_dummy = torch.cat([mask_txt, src_txt_mask], dim=1)
pos_dummy = self.dummy_rep_pos.reshape([1, self.args.num_dummies, self.hidden_dim]).repeat(pos_txt.shape[0], 1, 1)
pos_txt_dummy = torch.cat([pos_dummy, pos_txt], dim=1)
src_txt_dummy = src_txt_dummy.permute(1, 0, 2) # (L, batch_size, d)
pos_txt_dummy = pos_txt_dummy.permute(1, 0, 2) # (L, batch_size, d)
memory = self.txtproj_encoder(src_txt_dummy, src_key_padding_mask=~(src_txt_mask_dummy.bool()), pos=pos_txt_dummy) # (L, batch_size, d)
dummy_token = memory[:self.args.num_dummies].permute(1, 0, 2)
pos_txt_dummy = pos_txt_dummy.permute(1, 0, 2) # (L, batch_size, d)
src_txt_dummy = torch.cat([dummy_token, src_txt], dim=1)
mask_txt_dummy = torch.tensor([[True]*self.args.num_dummies]).to(src_txt_mask.device).repeat(src_txt_mask.shape[0], 1)
src_txt_mask_dummy = torch.cat([mask_txt_dummy, src_txt_mask], dim=1)
# Input : Concat video, dummy, txt
src = torch.cat([src_vid, src_txt_dummy], dim=1) # (bsz, L_vid+L_txt, d)
mask = torch.cat([src_vid_mask, src_txt_mask_dummy], dim=1).bool() # (bsz, L_vid+L_txt)
pos = torch.cat([pos_vid, pos_txt_dummy], dim=1)
#### for moment token ####
moment2txt_similarity = None
nmoment2txt_similarity = None
moment_mask_ = None
### sentence token
smask_ = torch.tensor([[True]]).to(mask.device).repeat(src_txt_mask.shape[0], 1)
smask = torch.cat([smask_, src_txt_mask.bool()], dim=1)
ssrc_ = self.sent_rep_token.reshape([1, 1, self.hidden_dim]).repeat(src_txt.shape[0], 1, 1)
ssrc = torch.cat([ssrc_, src_txt], dim=1)
spos_ = self.sent_rep_pos.reshape([1, 1, self.hidden_dim]).repeat(pos_txt.shape[0], 1, 1)
spos = torch.cat([spos_, pos_txt], dim=1)
### dummy sentence token
smaskd = torch.cat([smask_, mask_txt_dummy.bool()], dim=1)
ssrcd = torch.cat([ssrc_, dummy_token], dim=1)
sposd = torch.cat([spos_, pos_dummy], dim=1)
if targets is not None: # train
mmask_ = torch.tensor([[True]]).to(mask.device).repeat(src_vid_mask.shape[0], 1)
mmask = torch.cat([mmask_, src_vid_mask.bool()], dim=1)
moment_mask_ = torch.clamp(targets["relevant_clips"], 0, 1).bool()
moment_mask = torch.cat([mmask_, moment_mask_], dim=1)
mmask = mmask * moment_mask
msrc_ = self.moment_rep_token.reshape([1, 1, self.hidden_dim]).repeat(src_vid.shape[0], 1, 1)
msrc = torch.cat([msrc_, src_vid], dim=1)
mpos_ = self.moment_rep_pos.reshape([1, 1, self.hidden_dim]).repeat(pos_vid.shape[0], 1, 1)
mpos = torch.cat([mpos_, pos_vid], dim=1)
### for Not moment token ####
nmmask_ = torch.tensor([[True]]).to(mask.device).repeat(src_vid_mask.shape[0], 1)
nmmask = torch.cat([nmmask_, src_vid_mask.bool()], dim=1)
nmoment_mask_ = ~(torch.clamp(targets["relevant_clips"], 0, 1).bool())
nmoment_mask = torch.cat([nmmask_, nmoment_mask_], dim=1)
nmmask = nmmask * nmoment_mask
nmsrc_ = self.moment_rep_token.reshape([1, 1, self.hidden_dim]).repeat(src_vid.shape[0], 1, 1)
nmsrc = torch.cat([nmsrc_, src_vid], dim=1)
nmpos_ = self.moment_rep_pos.reshape([1, 1, self.hidden_dim]).repeat(pos_vid.shape[0], 1, 1)
nmpos = torch.cat([nmpos_, pos_vid], dim=1)
###########
# for t2vidavg sal token
vidsrc_ = torch.zeros((len(src_vid), 1, self.hidden_dim)).cuda()
for i in range(len(src_vid)):
vidsrc_[i] = src_vid[i][:src_vid_mask.sum(1)[i].long()].mean(0).clone().detach()
video_length = src_vid.shape[1]
if targets is not None: ## train
ssrc = ssrc.permute(1, 0, 2) # (L, batch_size, d)
spos = spos.permute(1, 0, 2) # (L, batch_size, d)
smemory = self.scls_encoder(ssrc, src_key_padding_mask=~smask, pos=spos) # (L, batch_size, d)
# print(smemory[0].shape, smemory[:self.args.num_dummies].shape) # 32 256, 3 32 256
sentence_txt, smemory_words = smemory[0], smemory[1:]
ssrcd = ssrcd.permute(1, 0, 2) # (L, batch_size, d)
sposd = sposd.permute(1, 0, 2) # (L, batch_size, d)
smemoryd = self.scls_encoder(ssrcd, src_key_padding_mask=~smaskd, pos=sposd) # (L, batch_size, d)
sentence_dummy, smemory_words_dummy = smemoryd[0], smemoryd[1:]
txt_dummy_proj = torch.cat([smemory_words_dummy, smemory_words], dim=0)
hs, reference, memory, memory_global, attn_weights, memory_moment, nmmemory_moment, mmemory_frames, nmmemory_frames = self.transformer(src, ~mask, self.query_embed.weight, pos, video_length=video_length, moment_idx=targets["relevant_clips"], msrc=msrc, mpos=mpos, mmask=~mmask, nmsrc=nmsrc, nmpos=nmpos, nmmask=~nmmask,
ctxtoken=vidsrc_, gtoken=self.global_rep_token, gpos=self.global_rep_pos, vlen=src_vid_mask.sum(1).long())
moment2txt_similarity = torch.matmul(mmemory_frames.permute(1, 0, 2), txt_dummy_proj.permute(1, 2, 0))
nmoment2txt_similarity = torch.matmul(nmmemory_frames.permute(1, 0, 2), txt_dummy_proj.permute(1, 2, 0))
else: ## inference
sentence_dummy, sentence_txt = None, None
hs, reference, memory, memory_global, attn_weights, memory_moment, nmmemory_moment, mmemory_frames, nmmemory_frames = self.transformer(src, ~mask, self.query_embed.weight, pos, video_length=video_length,
ctxtoken=vidsrc_, gtoken=self.global_rep_token, gpos=self.global_rep_pos, vlen=src_vid_mask.sum(1).long())
outputs_class = self.class_embed(hs) # (#layers, batch_size, #queries, #classes)
reference_before_sigmoid = inverse_sigmoid(reference)
tmp = self.span_embed(hs)
outputs_coord = tmp + reference_before_sigmoid
if self.span_loss_type == "l1":
outputs_coord = outputs_coord.sigmoid()
out = {'pred_logits': outputs_class[-1], 'pred_spans': outputs_coord[-1]}
txt_mem = memory[:, src_vid.shape[1]:] # (bsz, L_txt, d)
vid_mem = memory[:, :src_vid.shape[1]] # (bsz, L_vid, d)
if self.contrastive_align_loss:
proj_queries = F.normalize(self.contrastive_align_projection_query(hs), p=2, dim=-1)
proj_txt_mem = F.normalize(self.contrastive_align_projection_txt(txt_mem), p=2, dim=-1)
proj_vid_mem = F.normalize(self.contrastive_align_projection_vid(vid_mem), p=2, dim=-1)
out.update(dict(
proj_queries=proj_queries[-1],
proj_txt_mem=proj_txt_mem,
proj_vid_mem=proj_vid_mem
))
### Neg Pairs ###
neg_vid = ori_vid[1:] + ori_vid[:1]
real_neg_mask = torch.Tensor(element_wise_list_equal(ori_vid, neg_vid)).to(src_txt_dummy.device)
real_neg_mask = real_neg_mask == False
if real_neg_mask.sum() != 0:
src_txt_dummy_neg = torch.cat([src_txt_dummy[1:], src_txt_dummy[0:1]], dim=0)
src_txt_mask_dummy_neg = torch.cat([src_txt_mask_dummy[1:], src_txt_mask_dummy[0:1]], dim=0)
src_dummy_neg = torch.cat([src_vid, src_txt_dummy_neg], dim=1)
mask_dummy_neg = torch.cat([src_vid_mask, src_txt_mask_dummy_neg], dim=1).bool()
pos_neg = pos.clone() # since it does not use actual content
mask_dummy_neg = mask_dummy_neg[real_neg_mask]
src_dummy_neg = src_dummy_neg[real_neg_mask]
pos_neg = pos_neg[real_neg_mask]
src_txt_mask_dummy_neg = src_txt_mask_dummy_neg[real_neg_mask]
_, _, memory_neg, memory_global_neg, attn_weights_neg, _, _, _, _ = self.transformer(src_dummy_neg, ~mask_dummy_neg, self.query_embed.weight, pos_neg, video_length=video_length,
ctxtoken=vidsrc_[real_neg_mask], gtoken=self.global_rep_token, gpos=self.global_rep_pos, vlen=src_vid_mask[real_neg_mask].sum(1).long())
vid_mem_neg = memory_neg[:, :src_vid.shape[1]]
out["saliency_scores_neg"] = (torch.sum(self.saliency_proj1(vid_mem_neg) * self.saliency_proj2(memory_global_neg).unsqueeze(1), dim=-1) / np.sqrt(self.hidden_dim))
out["src_txt_mask_neg"] = src_txt_mask_dummy_neg
out["t2vattnvalues_neg"] = (attn_weights_neg[:, :, self.args.num_dummies:] * (src_txt_mask_dummy_neg[:, self.args.num_dummies:].unsqueeze(1).repeat(1, video_length, 1))).sum(2)
out["t2vattnvalues_neg"] = torch.clamp(out["t2vattnvalues_neg"], 0, 1)
else:
out["saliency_scores_neg"] = None
out["t2vattnvalues_neg"] = None
out["saliency_scores"] = (torch.sum(self.saliency_proj1(vid_mem) * self.saliency_proj2(memory_global).unsqueeze(1), dim=-1) / np.sqrt(self.hidden_dim))
out["memory_moment"] = memory_moment
out["nmmemory_moment"] = nmmemory_moment
## sentence token embeeded with text / dummy
out["sentence_txt"] = sentence_txt
out["sentence_dummy"] = sentence_dummy
out["moment2txt_similarity"] = moment2txt_similarity
out["nmoment2txt_similarity"] = nmoment2txt_similarity
out["cate_attn_weights"] = attn_weights
out["moment_mask"] = moment_mask_
out["txt_mask"] = src_txt_mask_dummy
out["real_neg_mask"] = real_neg_mask
out["t2vattnvalues"] = (attn_weights[:,:,self.args.num_dummies:] * (src_txt_mask.unsqueeze(1).repeat(1, video_length, 1))).sum(2) # 32 75 (24) / 32 (24)
out["t2vattnvalues"] = torch.clamp(out["t2vattnvalues"], 0, 1)
out["dummy_tokens"] = dummy_token
out["global_rep_tokens"] = self.global_rep_token
if targets is not None:
out["src_vid"] = mmemory_frames.permute(1, 0, 2) * moment_mask_.unsqueeze(2) + nmmemory_frames.permute(1, 0, 2) * (~(moment_mask_.unsqueeze(2).bool())).float()
else:
out["src_vid"] = None
out["video_mask"] = src_vid_mask
if self.aux_loss:
# assert proj_queries and proj_txt_mem
out['aux_outputs'] = [
{'pred_logits': a, 'pred_spans': b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
if self.contrastive_align_loss:
assert proj_queries is not None
for idx, d in enumerate(proj_queries[:-1]):
out['aux_outputs'][idx].update(dict(proj_queries=d, proj_txt_mem=proj_txt_mem))
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, matcher, weight_dict, eos_coef, losses, temperature, span_loss_type, max_v_l,
saliency_margin=1, use_matcher=True, args=None):
""" Create the criterion.
Parameters:
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.
eos_coef: relative classification weight applied to the no-object category
losses: list of all the losses to be applied. See get_loss for list of available losses.
temperature: float, temperature for NCE loss
span_loss_type: str, [l1, ce]
max_v_l: int,
saliency_margin: float
"""
super().__init__()
self.args=args
self.matcher = matcher
self.weight_dict = weight_dict
self.losses = losses
self.temperature = temperature
self.span_loss_type = span_loss_type
self.max_v_l = max_v_l
self.saliency_margin = saliency_margin
# foreground and background classification
self.foreground_label = 0
self.background_label = 1
self.eos_coef = eos_coef
empty_weight = torch.ones(2)
empty_weight[-1] = self.eos_coef # lower weight for background (index 1, foreground index 0)
self.register_buffer('empty_weight', empty_weight)
# for tvsum,
self.use_matcher = use_matcher
# moment sentence contrastive
self.criterion = torch.nn.CrossEntropyLoss().to(self.args.device)
self.l2_criterion = torch.nn.MSELoss().to(self.args.device)
self.kld_criterion = torch.nn.KLDivLoss(reduction='none').to(self.args.device)
self.bce_criterion = nn.BCELoss(reduction='none')
def loss_spans(self, outputs, targets, indices):
"""Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss
targets dicts must contain the key "spans" containing a tensor of dim [nb_tgt_spans, 2]
The target spans are expected in format (center_x, w), normalized by the image size.
"""
assert 'pred_spans' in outputs
targets = targets["span_labels"]
idx = self._get_src_permutation_idx(indices)
src_spans = outputs['pred_spans'][idx] # (#spans, max_v_l * 2)
tgt_spans = torch.cat([t['spans'][i] for t, (_, i) in zip(targets, indices)], dim=0) # (#spans, 2)
if self.span_loss_type == "l1":
loss_span = F.l1_loss(src_spans, tgt_spans, reduction='none')
loss_giou = 1 - torch.diag(generalized_temporal_iou(span_cxw_to_xx(src_spans), span_cxw_to_xx(tgt_spans)))
else: # ce
n_spans = src_spans.shape[0]
src_spans = src_spans.view(n_spans, 2, self.max_v_l).transpose(1, 2)
loss_span = F.cross_entropy(src_spans, tgt_spans, reduction='none')
loss_giou = loss_span.new_zeros([1])
losses = {}
losses['loss_span'] = loss_span.mean()
losses['loss_giou'] = loss_giou.mean()
return losses
def loss_labels(self, outputs, targets, indices, log=True):
"""Classification loss (NLL)
targets dicts must contain the key "labels" containing a tensor of dim [nb_target_boxes]
"""
# TODO add foreground and background classifier. use all non-matched as background.
assert 'pred_logits' in outputs
src_logits = outputs['pred_logits'] # (batch_size, #queries, #classes=2)
# idx is a tuple of two 1D tensors (batch_idx, src_idx), of the same length == #objects in batch
idx = self._get_src_permutation_idx(indices)
target_classes = torch.full(src_logits.shape[:2], self.background_label,
dtype=torch.int64, device=src_logits.device) # (batch_size, #queries)
target_classes[idx] = self.foreground_label
loss_ce = F.cross_entropy(src_logits.transpose(1, 2), target_classes, self.empty_weight, reduction="none")
losses = {'loss_label': loss_ce.mean()}
if log:
# TODO this should probably be a separate loss, not hacked in this one here
losses['class_error'] = 100 - accuracy(src_logits[idx], self.foreground_label)[0]
return losses
def loss_saliency(self, outputs, targets, indices, log=True):
"""higher scores for positive clips"""
if "saliency_pos_labels" not in targets:
return {"loss_saliency": 0}
# Neg pair loss
if outputs["saliency_scores_neg"] is not None:
vid_token_mask = outputs["video_mask"]
real_neg_mask = outputs["real_neg_mask"]
saliency_scores_neg = outputs["saliency_scores_neg"].clone() # (N, L)
loss_neg_pair = (- torch.log(1. - torch.sigmoid(saliency_scores_neg)) * (vid_token_mask[real_neg_mask])).sum(dim=1).mean()
saliency_scores = outputs["saliency_scores"].clone() # (N, L)
saliency_contrast_label = targets["saliency_all_labels"]
# real neg / false neg 나눠서 contrastive 진
realneg_saliency_scores = torch.cat([saliency_scores[real_neg_mask], saliency_scores_neg], dim=1)
realneg_saliency_contrast_label = torch.cat([saliency_contrast_label[real_neg_mask], torch.zeros_like(saliency_contrast_label)[real_neg_mask]], dim=1)
realneg_vid_token_mask = vid_token_mask[real_neg_mask].repeat([1, 2])
realneg_saliency_scores = realneg_vid_token_mask * realneg_saliency_scores + (1. - realneg_vid_token_mask) * -1e+3
tau = 0.5
loss_rank_contrastive = 0.
for rand_idx in range(1, 12):
drop_mask = ~(realneg_saliency_contrast_label > 100) # no drop
pos_mask = (realneg_saliency_contrast_label >= rand_idx) # positive when equal or higher than rand_idx
if torch.sum(pos_mask) == 0: # no positive sample
continue
else:
batch_drop_mask = torch.sum(pos_mask, dim=1) > 0 # negative sample indicator
# drop higher ranks
cur_saliency_scores = realneg_saliency_scores * drop_mask / tau + ~drop_mask * -1e+3
# numerical stability
logits = cur_saliency_scores - torch.max(cur_saliency_scores, dim=1, keepdim=True)[0]
# softmax
exp_logits = torch.exp(logits)
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True) + 1e-6)
mean_log_prob_pos = (pos_mask * log_prob * realneg_vid_token_mask).sum(1) / (pos_mask.sum(1) + 1e-6)
loss = - mean_log_prob_pos * batch_drop_mask
loss_rank_contrastive = loss_rank_contrastive + loss.mean()
loss_rank_contrastive = loss_rank_contrastive / 12
false_neg_mask = ~(real_neg_mask)
if false_neg_mask.sum() != 0:
if false_neg_mask.sum() == 1:
falseneg_saliency_scores = saliency_scores[false_neg_mask].unsqueeze(0)
falseneg_saliency_contrast_label = saliency_contrast_label[false_neg_mask].unsqueeze(0)
falseneg_vid_token_mask = vid_token_mask[false_neg_mask].unsqueeze(0)
falseneg_saliency_scores = falseneg_vid_token_mask * falseneg_saliency_scores + (1. - falseneg_vid_token_mask) * -1e+3
else:
falseneg_saliency_scores = saliency_scores[false_neg_mask]
falseneg_saliency_contrast_label = saliency_contrast_label[false_neg_mask]
falseneg_vid_token_mask = vid_token_mask[false_neg_mask]
falseneg_saliency_scores = falseneg_vid_token_mask * falseneg_saliency_scores + (1. - falseneg_vid_token_mask) * -1e+3
tau = 0.5
falseneg_loss_rank_contrastive = 0.
for rand_idx in range(1, 12):
drop_mask = ~(falseneg_saliency_contrast_label > 100) # no drop
pos_mask = (falseneg_saliency_contrast_label >= rand_idx) # positive when equal or higher than rand_idx
if torch.sum(pos_mask) == 0: # no positive sample
continue
else:
batch_drop_mask = torch.sum(pos_mask, dim=1) > 0 # negative sample indicator
# drop higher ranks
cur_saliency_scores = falseneg_saliency_scores * drop_mask / tau + ~drop_mask * -1e+3
# numerical stability
logits = cur_saliency_scores - torch.max(cur_saliency_scores, dim=1, keepdim=True)[0]
# softmax
exp_logits = torch.exp(logits)
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True) + 1e-6)
mean_log_prob_pos = (pos_mask * log_prob * falseneg_vid_token_mask).sum(1) / (pos_mask.sum(1) + 1e-6)
loss = - mean_log_prob_pos * batch_drop_mask
falseneg_loss_rank_contrastive = falseneg_loss_rank_contrastive + loss.mean()
falseneg_loss_rank_contrastive = falseneg_loss_rank_contrastive / 12
loss_rank_contrastive += falseneg_loss_rank_contrastive
saliency_scores = outputs["saliency_scores"] # (N, L)
pos_indices = targets["saliency_pos_labels"] # (N, #pairs)
neg_indices = targets["saliency_neg_labels"] # (N, #pairs)
num_pairs = pos_indices.shape[1] # typically 2 or 4
batch_indices = torch.arange(len(saliency_scores)).to(saliency_scores.device)
pos_scores = torch.stack(
[saliency_scores[batch_indices, pos_indices[:, col_idx]] for col_idx in range(num_pairs)], dim=1)
neg_scores = torch.stack(
[saliency_scores[batch_indices, neg_indices[:, col_idx]] for col_idx in range(num_pairs)], dim=1)
loss_saliency = torch.clamp(self.saliency_margin + neg_scores - pos_scores, min=0).sum() \
/ (len(pos_scores) * num_pairs) * 2 # * 2 to keep the loss the same scale
if self.args.dset_name in ['youtube_uni']:
loss_saliency = loss_saliency + loss_rank_contrastive + loss_neg_pair * 0.
else:
loss_saliency = loss_saliency + loss_rank_contrastive + loss_neg_pair
########### Saliency loss to t2v attn weights ##############
"""higher scores for positive clips"""
vid_token_mask = outputs["video_mask"]
# Neg pair loss
if outputs["t2vattnvalues_neg"] is not None:
saliency_scores_neg = outputs["t2vattnvalues_neg"].clone() # (N, L)
loss_neg_pair_attn = (- torch.log(1. - saliency_scores_neg) * (vid_token_mask[real_neg_mask])).sum(dim=1).mean()
saliency_scores = outputs["t2vattnvalues"].clone() # (N, L)
saliency_contrast_label = targets["saliency_all_labels"]
# real neg / false neg 나눠서 contrastive 진
realneg_saliency_scores = torch.cat([saliency_scores[real_neg_mask], saliency_scores_neg], dim=1)
realneg_saliency_contrast_label = torch.cat(
[saliency_contrast_label[real_neg_mask], torch.zeros_like(saliency_contrast_label)[real_neg_mask]], dim=1)
realneg_vid_token_mask = vid_token_mask[real_neg_mask].repeat([1, 2])
realneg_saliency_scores = realneg_vid_token_mask * realneg_saliency_scores + (
1. - realneg_vid_token_mask) * -1e+3
tau = 0.5
loss_rank_contrastive_attn = 0.
for rand_idx in range(1, 12):
drop_mask = ~(realneg_saliency_contrast_label > 100) # no drop
pos_mask = (realneg_saliency_contrast_label >= rand_idx) # positive when equal or higher than rand_idx
if torch.sum(pos_mask) == 0: # no positive sample
continue
else:
batch_drop_mask = torch.sum(pos_mask, dim=1) > 0 # negative sample indicator
# drop higher ranks
cur_saliency_scores = realneg_saliency_scores * drop_mask / tau + ~drop_mask * -1e+3
# numerical stability
logits = cur_saliency_scores - torch.max(cur_saliency_scores, dim=1, keepdim=True)[0]
# softmax
exp_logits = torch.exp(logits)
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True) + 1e-6)
mean_log_prob_pos = (pos_mask * log_prob * realneg_vid_token_mask).sum(1) / (pos_mask.sum(1) + 1e-6)
loss = - mean_log_prob_pos * batch_drop_mask
loss_rank_contrastive_attn = loss_rank_contrastive_attn + loss.mean()
loss_rank_contrastive_attn = loss_rank_contrastive_attn / 12
false_neg_mask = ~(real_neg_mask)
if false_neg_mask.sum() != 0:
if false_neg_mask.sum() == 1:
falseneg_saliency_scores = saliency_scores[false_neg_mask].unsqueeze(0)
falseneg_saliency_contrast_label = saliency_contrast_label[false_neg_mask].unsqueeze(0)
falseneg_vid_token_mask = vid_token_mask[false_neg_mask].unsqueeze(0)
falseneg_saliency_scores = falseneg_vid_token_mask * falseneg_saliency_scores + (1. - falseneg_vid_token_mask) * -1e+3
else:
falseneg_saliency_scores = saliency_scores[false_neg_mask]
falseneg_saliency_contrast_label = saliency_contrast_label[false_neg_mask]
falseneg_vid_token_mask = vid_token_mask[false_neg_mask]
falseneg_saliency_scores = falseneg_vid_token_mask * falseneg_saliency_scores + (1. - falseneg_vid_token_mask) * -1e+3
tau = 0.5
falseneg_loss_rank_contrastive = 0.
for rand_idx in range(1, 12):
drop_mask = ~(falseneg_saliency_contrast_label > 100) # no drop
pos_mask = (falseneg_saliency_contrast_label >= rand_idx) # positive when equal or higher than rand_idx
if torch.sum(pos_mask) == 0: # no positive sample
continue
else:
batch_drop_mask = torch.sum(pos_mask, dim=1) > 0 # negative sample indicator
# drop higher ranks
cur_saliency_scores = falseneg_saliency_scores * drop_mask / tau + ~drop_mask * -1e+3
# numerical stability
logits = cur_saliency_scores - torch.max(cur_saliency_scores, dim=1, keepdim=True)[0]
# softmax
exp_logits = torch.exp(logits)
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True) + 1e-6)
mean_log_prob_pos = (pos_mask * log_prob * falseneg_vid_token_mask).sum(1) / (pos_mask.sum(1) + 1e-6)
loss = - mean_log_prob_pos * batch_drop_mask
falseneg_loss_rank_contrastive = falseneg_loss_rank_contrastive + loss.mean()
falseneg_loss_rank_contrastive = falseneg_loss_rank_contrastive / 12
loss_rank_contrastive += falseneg_loss_rank_contrastive
saliency_scores = outputs["t2vattnvalues"] # (N, L)
pos_indices = targets["saliency_pos_labels"] # (N, #pairs)
neg_indices = targets["saliency_neg_labels"] # (N, #pairs)
num_pairs = pos_indices.shape[1] # typically 2 or 4
batch_indices = torch.arange(len(saliency_scores)).to(saliency_scores.device)
pos_scores = torch.stack(
[saliency_scores[batch_indices, pos_indices[:, col_idx]] for col_idx in range(num_pairs)], dim=1)
neg_scores = torch.stack(
[saliency_scores[batch_indices, neg_indices[:, col_idx]] for col_idx in range(num_pairs)], dim=1)
loss_saliency_attn = torch.clamp(self.saliency_margin + neg_scores - pos_scores, min=0).sum() \
/ (len(pos_scores) * num_pairs) * 2 # * 2 to keep the loss the same scale
saliency_binary_label = torch.clamp(targets["saliency_all_labels"], 0, 1)
# print(saliency_scores.shape, saliency_binary_label.shape)
logits = saliency_scores.reshape(-1)
labels_x = saliency_binary_label.reshape(-1)
BCEcriterion = nn.BCELoss()
bceloss = BCEcriterion(logits, labels_x)
if self.args.dset_name in ['youtube_uni']:
loss_saliency_attn = loss_rank_contrastive_attn + bceloss + loss_neg_pair_attn * 0 + loss_saliency_attn
else:
loss_saliency_attn = loss_rank_contrastive_attn + bceloss + loss_neg_pair_attn + loss_saliency_attn
loss_saliency += (loss_saliency_attn * self.args.lw_wattn)
else: ## when batch size == 1
vid_token_mask = outputs["video_mask"]
saliency_scores = outputs["saliency_scores"].clone() # (N, L)
saliency_contrast_label = targets["saliency_all_labels"]
saliency_scores = vid_token_mask * saliency_scores + (1. - vid_token_mask) * -1e+3
tau = 0.5
loss_rank_contrastive = 0.
for rand_idx in range(1, 12):
drop_mask = ~(saliency_contrast_label > 100) # no drop
pos_mask = (saliency_contrast_label >= rand_idx) # positive when equal or higher than rand_idx
if torch.sum(pos_mask) == 0: # no positive sample
continue
else:
batch_drop_mask = torch.sum(pos_mask, dim=1) > 0 # negative sample indicator
# drop higher ranks
cur_saliency_scores = saliency_scores * drop_mask / tau + ~drop_mask * -1e+3
# numerical stability
logits = cur_saliency_scores - torch.max(cur_saliency_scores, dim=1, keepdim=True)[0]
# softmax
exp_logits = torch.exp(logits)
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True) + 1e-6)
mean_log_prob_pos = (pos_mask * log_prob * vid_token_mask).sum(1) / (pos_mask.sum(1) + 1e-6)
loss = - mean_log_prob_pos * batch_drop_mask
loss_rank_contrastive = loss_rank_contrastive + loss.mean()
loss_rank_contrastive = loss_rank_contrastive / 12
saliency_scores = outputs["saliency_scores"] # (N, L)
pos_indices = targets["saliency_pos_labels"] # (N, #pairs)
neg_indices = targets["saliency_neg_labels"] # (N, #pairs)
num_pairs = pos_indices.shape[1] # typically 2 or 4
batch_indices = torch.arange(len(saliency_scores)).to(saliency_scores.device)
pos_scores = torch.stack(
[saliency_scores[batch_indices, pos_indices[:, col_idx]] for col_idx in range(num_pairs)], dim=1)
neg_scores = torch.stack(
[saliency_scores[batch_indices, neg_indices[:, col_idx]] for col_idx in range(num_pairs)], dim=1)
loss_saliency = torch.clamp(self.saliency_margin + neg_scores - pos_scores, min=0).sum() \
/ (len(pos_scores) * num_pairs) * 2 # * 2 to keep the loss the same scale
loss_saliency = loss_saliency + loss_rank_contrastive
########### Saliency loss to t2v attn weights ##############
"""higher scores for positive clips"""
vid_token_mask = outputs["video_mask"]
saliency_scores = outputs["t2vattnvalues"].clone() # (N, L)
saliency_contrast_label = targets["saliency_all_labels"]
saliency_scores = vid_token_mask * saliency_scores + (1. - vid_token_mask) * -1e+3
tau = 0.5
loss_rank_contrastive = 0.
for rand_idx in range(1, 12):
drop_mask = ~(saliency_contrast_label > 100) # no drop
pos_mask = (saliency_contrast_label >= rand_idx) # positive when equal or higher than rand_idx
if torch.sum(pos_mask) == 0: # no positive sample
continue
else:
batch_drop_mask = torch.sum(pos_mask, dim=1) > 0 # negative sample indicator
# drop higher ranks
cur_saliency_scores = saliency_scores * drop_mask / tau + ~drop_mask * -1e+3
# numerical stability
logits = cur_saliency_scores - torch.max(cur_saliency_scores, dim=1, keepdim=True)[0]
# softmax
exp_logits = torch.exp(logits)
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True) + 1e-6)
mean_log_prob_pos = (pos_mask * log_prob * vid_token_mask).sum(1) / (pos_mask.sum(1) + 1e-6)
loss = - mean_log_prob_pos * batch_drop_mask
loss_rank_contrastive = loss_rank_contrastive + loss.mean()
loss_rank_contrastive_attn = loss_rank_contrastive / 12
saliency_scores = outputs["t2vattnvalues"] # (N, L)
pos_indices = targets["saliency_pos_labels"] # (N, #pairs)
neg_indices = targets["saliency_neg_labels"] # (N, #pairs)
num_pairs = pos_indices.shape[1] # typically 2 or 4
batch_indices = torch.arange(len(saliency_scores)).to(saliency_scores.device)
pos_scores = torch.stack(
[saliency_scores[batch_indices, pos_indices[:, col_idx]] for col_idx in range(num_pairs)], dim=1)
neg_scores = torch.stack(
[saliency_scores[batch_indices, neg_indices[:, col_idx]] for col_idx in range(num_pairs)], dim=1)
loss_saliency_attn = torch.clamp(self.saliency_margin + neg_scores - pos_scores, min=0).sum() \
/ (len(pos_scores) * num_pairs) * 2 # * 2 to keep the loss the same scale
saliency_binary_label = torch.clamp(targets["saliency_all_labels"], 0, 1)
logits = saliency_scores.reshape(-1)
labels_x = saliency_binary_label.reshape(-1)
BCEcriterion = nn.BCELoss()
bceloss = BCEcriterion(logits, labels_x)
loss_saliency_attn = loss_rank_contrastive_attn + bceloss + loss_saliency_attn
loss_saliency += (loss_saliency_attn * self.args.lw_wattn)
return {"loss_saliency": loss_saliency}
def loss_contrastive_moment_sentence(self, outputs, targets, indices, log=True):
if outputs["memory_moment"] is not None:
moment_token = outputs["memory_moment"]
nmmemory_moment = outputs["nmmemory_moment"]
sentence_token = outputs["sentence_txt"].squeeze(1)
sentence_dummy = outputs["sentence_dummy"].squeeze(1) # b, 1, d
moment_logits = F.normalize(moment_token, dim=1)
nmoment_logits = F.normalize(nmmemory_moment, dim=1)
sentence_logits = F.normalize(sentence_token, dim=1)
dummy_logits = F.normalize(sentence_dummy, dim=1)
similarity_matrix = torch.matmul(moment_logits, sentence_logits.T) # B B
nsimilarity_matrix = torch.matmul(nmoment_logits, sentence_logits.T) # B B
similarity_matrix = torch.cat([similarity_matrix, nsimilarity_matrix], dim=1)
labels = torch.eye(similarity_matrix.shape[0]).to(self.args.device)
nlabels = torch.zeros_like(nsimilarity_matrix).to(self.args.device)
labels = torch.cat([labels, nlabels], dim=1).max(dim=1)[1]
loss_ms_align = self.criterion(similarity_matrix, labels)
dummy_similarity_matrix = torch.matmul(moment_logits, dummy_logits.T)
dummy_nsimilarity_matrix = torch.matmul(nmoment_logits, dummy_logits.T)
dummy_similarity_matrix = torch.cat([dummy_similarity_matrix, dummy_nsimilarity_matrix], dim=1)
dummy_labels = (~(torch.eye(similarity_matrix.shape[0]).to(self.args.device).bool())).float()
dummy_nlabels = torch.ones_like(nsimilarity_matrix).to(self.args.device)
dummy_labels = torch.cat([dummy_labels, dummy_nlabels], dim=1).max(dim=1)[1]
dummy_loss_ms_align = self.criterion(dummy_similarity_matrix, dummy_labels)
loss_ms_align += dummy_loss_ms_align
video_mask = outputs['video_mask']
src_vid = outputs['src_vid'] # [batch_size, L_vid, D_vid]
moment_mask_ = torch.clamp(targets["relevant_clips"], 0, 1)
momtokcls_pred = torch.matmul(moment_token.unsqueeze(1), src_vid.permute(0, 2, 1)) # b 1 L_vid
momtokcls_label = moment_mask_
momtokcls_logit = torch.sigmoid(momtokcls_pred)
loss_ms_align += (self.bce_criterion(momtokcls_logit.reshape(-1), momtokcls_label.reshape(-1)) * video_mask.reshape(-1)).mean()
else:
loss_ms_align = 0.
return {"loss_ms_align": loss_ms_align}
#
def loss_moment2txt_sim_distill(self, outputs, targets, indices, log=True):
if outputs["moment2txt_similarity"] is not None:
moment2txt_similarity = outputs["moment2txt_similarity"] # 32 75 22
moment_mask = outputs["moment_mask"].int() # 32 75 1
txt_mask = outputs["txt_mask"].unsqueeze(1).repeat(1, outputs["cate_attn_weights"].size(1), 1) # b l_t
attn_weights = outputs["cate_attn_weights"] # 32 75 22
b, L_vid, L_txt = attn_weights.size()
loss_distill = self.kld_criterion(
torch.log(attn_weights + 1e-6).reshape(b * L_vid, -1),
torch.softmax(moment2txt_similarity, dim=-1).clone().detach().reshape(b * L_vid, -1)).mean(1) * moment_mask.reshape(-1)
loss_distill = loss_distill.sum() / moment_mask.sum()
else:
loss_distill = 0.
return {"loss_distill": loss_distill}
def loss_orthogonal_dummy(self, outputs, targets, indices, log=True):
dummy_tokens = outputs["dummy_tokens"] # (n_dum, dim)
if dummy_tokens.size(1) != 1:
dummy_tokens_norm = dummy_tokens / dummy_tokens.norm(dim=2)[:, :, None]
dummy_tokens_sim = torch.matmul(dummy_tokens_norm, dummy_tokens_norm.permute(0, 2, 1).detach())
for i in range(len(dummy_tokens_sim)):
dummy_tokens_sim[i].fill_diagonal_(0)
loss_dummy_ortho = dummy_tokens_sim.abs().mean()
else:
loss_dummy_ortho=0.
global_tokens = outputs["global_rep_tokens"]
global_tokens_norm = global_tokens / global_tokens.norm(dim=1)[:, None]
global_tokens_sim = torch.matmul(global_tokens_norm, global_tokens_norm.permute(1, 0).detach())
for i in range(len(global_tokens_sim)):
global_tokens_sim.fill_diagonal_(0)
loss_dummy_ortho += global_tokens_sim.abs().mean()
return {"loss_orthogonal_dummy": loss_dummy_ortho}
def loss_contrastive_align(self, outputs, targets, indices, log=True):
"""encourage higher scores between matched query span and input text"""
normalized_text_embed = outputs["proj_txt_mem"] # (bsz, #tokens, d) text tokens
normalized_img_embed = outputs["proj_queries"] # (bsz, #queries, d)
logits = torch.einsum(
"bmd,bnd->bmn", normalized_img_embed, normalized_text_embed) # (bsz, #queries, #tokens)
logits = logits.sum(2) / self.temperature # (bsz, #queries)
idx = self._get_src_permutation_idx(indices)
positive_map = torch.zeros_like(logits, dtype=torch.bool)
positive_map[idx] = True
positive_logits = logits.masked_fill(~positive_map, 0)
pos_term = positive_logits.sum(1) # (bsz, )
num_pos = positive_map.sum(1) # (bsz, )
neg_term = logits.logsumexp(1) # (bsz, )
loss_nce = - pos_term / num_pos + neg_term # (bsz, )
losses = {"loss_contrastive_align": loss_nce.mean()}
return losses
def loss_contrastive_align_vid_txt(self, outputs, targets, indices, log=True):
"""encourage higher scores between matched query span and input text"""
# TODO (1) align vid_mem and txt_mem;
# TODO (2) change L1 loss as CE loss on 75 labels, similar to soft token prediction in MDETR
normalized_text_embed = outputs["proj_txt_mem"] # (bsz, #tokens, d) text tokens
normalized_img_embed = outputs["proj_queries"] # (bsz, #queries, d)
logits = torch.einsum(
"bmd,bnd->bmn", normalized_img_embed, normalized_text_embed) # (bsz, #queries, #tokens)
logits = logits.sum(2) / self.temperature # (bsz, #queries)
idx = self._get_src_permutation_idx(indices)
positive_map = torch.zeros_like(logits, dtype=torch.bool)
positive_map[idx] = True
positive_logits = logits.masked_fill(~positive_map, 0)
pos_term = positive_logits.sum(1) # (bsz, )
num_pos = positive_map.sum(1) # (bsz, )
neg_term = logits.logsumexp(1) # (bsz, )
loss_nce = - pos_term / num_pos + neg_term # (bsz, )
losses = {"loss_contrastive_align": loss_nce.mean()}
return losses
def _get_src_permutation_idx(self, indices):
# permute predictions following indices
batch_idx = torch.cat([torch.full_like(src, i) for i, (src, _) in enumerate(indices)])
src_idx = torch.cat([src for (src, _) in indices])
return batch_idx, src_idx # two 1D tensors of the same length
def _get_tgt_permutation_idx(self, indices):
# permute targets following indices
batch_idx = torch.cat([torch.full_like(tgt, i) for i, (_, tgt) in enumerate(indices)])
tgt_idx = torch.cat([tgt for (_, tgt) in indices])
return batch_idx, tgt_idx
def get_loss(self, loss, outputs, targets, indices, **kwargs):
loss_map = {
"spans": self.loss_spans,
"labels": self.loss_labels,
"contrastive_align": self.loss_contrastive_align,
"saliency": self.loss_saliency,
"ms_align": self.loss_contrastive_moment_sentence,
"distill": self.loss_moment2txt_sim_distill,
"orthogonal_dummy":self.loss_orthogonal_dummy
}
assert loss in loss_map, f'do you really want to compute {loss} loss?'
return loss_map[loss](outputs, targets, indices, **kwargs)
def forward(self, outputs, targets):
""" This performs the loss computation.
Parameters:
outputs: dict of tensors, see the output specification of the model for the format
targets: list of dicts, such that len(targets) == batch_size.
The expected keys in each dict depends on the losses applied, see each loss' doc
"""
outputs_without_aux = {k: v for k, v in outputs.items() if k != 'aux_outputs'}
# Retrieve the matching between the outputs of the last layer and the targets
# list(tuples), each tuple is (pred_span_indices, tgt_span_indices)
# only for HL, do not use matcher
if self.use_matcher:
indices = self.matcher(outputs_without_aux, targets)
losses_target = self.losses
else:
indices = None
losses_target = ["saliency"]
# Compute all the requested losses
losses = {}
# for loss in self.losses:
for loss in losses_target:
losses.update(self.get_loss(loss, outputs, targets, indices))
# In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
if 'aux_outputs' in outputs:
for i, aux_outputs in enumerate(outputs['aux_outputs']):
# indices = self.matcher(aux_outputs, targets)
if self.use_matcher:
indices = self.matcher(aux_outputs, targets)
losses_target = self.losses
else:
indices = None
losses_target = ["saliency", "ms_align", "distill", "orthogonal_dummy"]
for loss in losses_target:
if "saliency" == loss: # skip as it is only in the top layer
continue
if "ms_align" == loss:
continue
if "distill" == loss:
continue
if "orthogonal_dummy" == loss:
continue
kwargs = {}
l_dict = self.get_loss(loss, aux_outputs, targets, indices, **kwargs)
l_dict = {k + f'_{i}': v for k, v in l_dict.items()}
losses.update(l_dict)
return losses
class MLP(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
super().__init__()
self.num_layers = num_layers
h = [hidden_dim] * (num_layers - 1)
self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
def forward(self, x):
for i, layer in enumerate(self.layers):
x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
return x
class LinearLayer(nn.Module):
"""linear layer configurable with layer normalization, dropout, ReLU."""
def __init__(self, input_dim, output_dim, layer_norm=True, dropout=0.1, relu=True):
super(LinearLayer, self).__init__()
self.relu = relu
self.layer_norm = layer_norm
if layer_norm:
self.LayerNorm = nn.LayerNorm(input_dim)
layers = [
nn.Dropout(dropout),
nn.Linear(input_dim, output_dim)
]
self.net = nn.Sequential(*layers)
def forward(self, x):
"""(N, L, D)"""
if self.layer_norm:
x = self.LayerNorm(x)
x = self.net(x)
if self.relu:
x = F.relu(x, inplace=True)
return x # (N, L, D)
def build_model(args):
device = torch.device(args.device)
transformer = build_transformer(args) | position_embedding, txt_position_embedding = build_position_encoding(args) | 6 | 2023-11-10 12:45:25+00:00 | 8k |
kudelskisecurity/fuzzomatic | fuzzomatic/main.py | [
{
"identifier": "utils",
"path": "fuzzomatic/tools/utils.py",
"snippet": "def get_codebase_name(codebase_dir):\ndef autofix_unwrap_calls(target_path):\ndef load_fuzz_target(target_path):\ndef autofix_fuzz_target(target_path):\ndef rustfmt_target(target_path):\ndef build_target(codebase_dir, target_name)... | import argparse
import datetime
import json
import os.path
import subprocess
import sys
import fuzzomatic.tools.utils
from fuzzomatic.tools import utils
from fuzzomatic import discovery
from fuzzomatic.approaches import (
try_functions_approach,
try_examples_approach,
try_readme_approach,
try_benches_approach,
try_unit_tests_approach,
try_unit_tests_with_function_approach,
)
from fuzzomatic.tools.constants import (
DEFAULT_TARGET_NAME,
FUZZOMATIC_RESULTS_FILENAME,
EXIT_NOT_A_CARGO_PROJECT,
EXIT_PROJECT_ALREADY_FUZZED,
EXIT_PROJECT_DOES_NOT_BUILD,
EXIT_OPENAI_API_KEY_ERROR,
)
from fuzzomatic.tools.llm import ask_llm, reset_ask_llm_counts, load_openai_api_key
from fuzzomatic.tools.runtime import evaluate_target, cleanup_corpus
from fuzzomatic.tools.utils import (
get_codebase_name,
git_clone,
init_cargo_fuzz,
check_virtual_manifest,
check_has_workspace_members,
detect_git_url,
) | 6,128 | nargs="+",
dest="functions_denylist",
default=None,
help="List of words that should not appear in target function names. "
"Such functions will be skipped.",
)
return parser
def save_results(
args,
git_url,
generated_fuzz_targets,
start_time,
end_time,
duration,
outcome_reason,
):
name = get_codebase_name(args.codebase_dir)
# runtime
duration_seconds = duration.total_seconds()
# create results
results_path = os.path.join(args.codebase_dir, FUZZOMATIC_RESULTS_FILENAME)
results = {
"codebase_dir": args.codebase_dir,
"name": name,
"git_url": git_url,
"generated_fuzz_targets": generated_fuzz_targets,
"start_time": start_time.isoformat(),
"end_time": end_time.isoformat(),
"duration_seconds": duration_seconds,
"outcome_reason": outcome_reason,
}
# save results to file
with open(results_path, "w+") as fout:
fout.write(json.dumps(results))
print(f"Saved fuzzomatic results to: {results_path}")
def get_approaches(requested_approaches):
approaches = []
if requested_approaches is not None:
for name, func in ENABLED_APPROACHES:
if name in requested_approaches:
approaches.append((name, func))
else:
approaches = ENABLED_APPROACHES
return approaches
def generate_building_fuzz_targets(
args, codebase_dir, git_url, approaches, force=False
):
codebase_name = get_codebase_name(codebase_dir)
if not force:
print(f"Checking if {codebase_name} is not already in oss-fuzz")
if discovery.is_project_to_be_skipped(codebase_dir, git_url):
yield "message", EXIT_PROJECT_ALREADY_FUZZED
autofuzz_generator = autofuzz_codebase(args, codebase_dir, approaches=approaches)
for result in autofuzz_generator:
yield result
def ensure_dependencies_available():
required_external_commands = [
("semgrep", ["semgrep"]),
("cargo fuzz", ["cargo", "fuzz", "help"]),
]
print("Checking external dependencies...")
for cmd_name, cmd in required_external_commands:
try:
subprocess.check_call(
cmd, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL
)
print(f"[SUCCESS] {cmd_name}")
except (subprocess.CalledProcessError, FileNotFoundError):
print(
f"[FAILURE] {cmd_name} is a required dependency. "
f"Fuzzomatic won't run without it."
)
print(
"Make sure that the dependency is installed "
"as explained in the README instructions"
)
print("Aborting...")
sys.exit(-1)
def main(args=None):
# reset LLM counter
ask_llm.counter = 0
if args is None:
parser = get_parser()
args = parser.parse_args()
# load openai api key
load_openai_api_key()
# check required dependencies are available
ensure_dependencies_available()
very_start = datetime.datetime.utcnow()
# if git URL, clone the repository
git_url = None
if args.codebase_dir.startswith("https://"):
git_url = args.codebase_dir
path = os.path.abspath(os.path.join(".", "git"))
print("Code base appears to be a git URL. Trying to git clone...")
codebase_dir = git_clone(args.codebase_dir, path)
args.codebase_dir = codebase_dir
else:
| #!/usr/bin/env python3
def get_parser():
prog_name = "fuzzomatic"
parser = argparse.ArgumentParser(
prog=prog_name,
description="Automatically generate Rust fuzz targets from scratch",
)
parser.add_argument(
"codebase_dir", help="Path to the codebase to generate a fuzz target for"
)
parser = add_parser_shared_arguments(parser)
return parser
def add_parser_shared_arguments(parser):
parser.add_argument(
"--force",
action="store_true",
dest="force",
help="Run Fuzzomatic anyway. Even if project is already covered by oss-fuzz",
)
parser.add_argument(
"--stop-on",
dest="stop_on",
default="bug",
help="Stop on can be one of `building`, `useful` or `bug`. "
"`building` means stop when a building fuzz target was generated."
"`useful` means stop when a useful fuzz target was generated."
"`bug` means stop when a bug is found. ",
)
parser.add_argument(
"--max-fuzz-targets",
dest="max_fuzz_targets",
type=int,
default=1,
help="Stop if `max_fuzz_targets` fuzz targets match the "
"`stop_on` condition for this code base."
"For example, if max_fuzz_targets is 2 and stop_on is bug, "
"we will stop as soon as 2 bugs are found.",
)
parser.add_argument(
"--approaches",
nargs="+",
dest="approaches",
default=None,
help="List of approaches to use",
)
parser.add_argument(
"--functions-denylist",
nargs="+",
dest="functions_denylist",
default=None,
help="List of words that should not appear in target function names. "
"Such functions will be skipped.",
)
return parser
def save_results(
args,
git_url,
generated_fuzz_targets,
start_time,
end_time,
duration,
outcome_reason,
):
name = get_codebase_name(args.codebase_dir)
# runtime
duration_seconds = duration.total_seconds()
# create results
results_path = os.path.join(args.codebase_dir, FUZZOMATIC_RESULTS_FILENAME)
results = {
"codebase_dir": args.codebase_dir,
"name": name,
"git_url": git_url,
"generated_fuzz_targets": generated_fuzz_targets,
"start_time": start_time.isoformat(),
"end_time": end_time.isoformat(),
"duration_seconds": duration_seconds,
"outcome_reason": outcome_reason,
}
# save results to file
with open(results_path, "w+") as fout:
fout.write(json.dumps(results))
print(f"Saved fuzzomatic results to: {results_path}")
def get_approaches(requested_approaches):
approaches = []
if requested_approaches is not None:
for name, func in ENABLED_APPROACHES:
if name in requested_approaches:
approaches.append((name, func))
else:
approaches = ENABLED_APPROACHES
return approaches
def generate_building_fuzz_targets(
args, codebase_dir, git_url, approaches, force=False
):
codebase_name = get_codebase_name(codebase_dir)
if not force:
print(f"Checking if {codebase_name} is not already in oss-fuzz")
if discovery.is_project_to_be_skipped(codebase_dir, git_url):
yield "message", EXIT_PROJECT_ALREADY_FUZZED
autofuzz_generator = autofuzz_codebase(args, codebase_dir, approaches=approaches)
for result in autofuzz_generator:
yield result
def ensure_dependencies_available():
required_external_commands = [
("semgrep", ["semgrep"]),
("cargo fuzz", ["cargo", "fuzz", "help"]),
]
print("Checking external dependencies...")
for cmd_name, cmd in required_external_commands:
try:
subprocess.check_call(
cmd, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL
)
print(f"[SUCCESS] {cmd_name}")
except (subprocess.CalledProcessError, FileNotFoundError):
print(
f"[FAILURE] {cmd_name} is a required dependency. "
f"Fuzzomatic won't run without it."
)
print(
"Make sure that the dependency is installed "
"as explained in the README instructions"
)
print("Aborting...")
sys.exit(-1)
def main(args=None):
# reset LLM counter
ask_llm.counter = 0
if args is None:
parser = get_parser()
args = parser.parse_args()
# load openai api key
load_openai_api_key()
# check required dependencies are available
ensure_dependencies_available()
very_start = datetime.datetime.utcnow()
# if git URL, clone the repository
git_url = None
if args.codebase_dir.startswith("https://"):
git_url = args.codebase_dir
path = os.path.abspath(os.path.join(".", "git"))
print("Code base appears to be a git URL. Trying to git clone...")
codebase_dir = git_clone(args.codebase_dir, path)
args.codebase_dir = codebase_dir
else: | git_url = detect_git_url(args.codebase_dir) | 24 | 2023-11-14 09:52:59+00:00 | 8k |
AdmTal/music-graphs | src/graph_stuff.py | [
{
"identifier": "Theme",
"path": "src/theme_stuff.py",
"snippet": "class Theme:\n def __init__(\n self,\n theme_file,\n defaults_file,\n ):\n with open(theme_file, \"r\") as stream:\n self._theme = AttributeDict(**yaml.safe_load(stream))\n\n with open(... | import re
import math
from collections import defaultdict, namedtuple
from PIL import Image, ImageDraw, ImageFilter, ImageFont
from src.theme_stuff import Theme
from src.cache_stuff import get_cache_dir | 4,297 | (point_center[0] + i, point_center[1] + i),
],
fill=theme.ball_color(track),
outline=hex_to_rgb(theme.ball_stroke_color(track)),
width=theme.ball_stroke_width(track),
)
blur_max = theme.ball_g_blur_max(track)
if blur_max:
blur_radius = min(
animation_length_in_frames - frame_number,
theme.ball_g_blur_max(track) / (frame_number + 1),
)
overlay_image = overlay_image.filter(
ImageFilter.GaussianBlur(radius=blur_radius)
)
# Composite the transparent overlay onto the base image
return Image.alpha_composite(
base_image.convert("RGBA"),
overlay_image,
)
def animate_ellipsis_blur(
base_image,
points,
frame_number,
offsets,
theme,
track,
animation_len,
velocity,
):
image = base_image.copy()
draw = ImageDraw.Draw(image)
x_offset, y_offset = offsets
x0, y0, w, h = points
x0 += x_offset
y0 += y_offset
# Calculate the increase in size
w_increase = w * theme.note_increase_size(track) * (velocity / 127)
h_increase = h * theme.note_increase_size(track) * (velocity / 127)
# Define the bounding box with the increased size
bounding_box = [
x0 - w - w_increase / 2,
y0 - h - h_increase / 2,
x0 + w + w_increase / 2,
y0 + h + h_increase / 2,
]
# Draw the initial ellipse
draw.ellipse(
bounding_box,
outline=hex_to_rgb(theme.note_color(track)),
width=theme.note_stroke_width(track),
)
# Determine the blur radius for this frame
blur_strength = (frame_number / animation_len) * velocity
blur_radius = max(1, blur_strength)
# Create a mask for the ellipse to constrain the blur effect
mask = Image.new("L", image.size, 0)
mask_draw = ImageDraw.Draw(mask)
mask_draw.ellipse(bounding_box, fill=255)
# Apply the blur effect on the mask
mask_blurred = mask.filter(ImageFilter.GaussianBlur(blur_radius))
# Create a solid image for the blur color
ellipse = Image.new("RGBA", image.size, hex_to_rgb(theme.note_color(track)))
# Composite the blurred mask with the ellipse onto the base image
image.paste(ellipse, mask=mask_blurred)
return image
def draw_centered_text(
offsets,
image,
text,
x,
y,
font_path,
font_size,
color,
outline_color,
stroke_width,
):
font = ImageFont.truetype(font_path, font_size)
draw = ImageDraw.Draw(image)
x += offsets[0]
y += offsets[1]
draw.text(
(x, y),
text,
font=font,
fill=hex_to_rgb(color),
stroke_width=stroke_width,
stroke_fill=hex_to_rgb(outline_color),
)
return image
def paste_center(host_image, image):
host_width, host_height = host_image.size
width, height = image.size
x = (host_width - width) // 2
y = (host_height - height) // 2
host_image.paste(image, (x, y), image)
def get_node_positions(graph):
"""Draw a graph to a file, load it, then parse it's `node[pos] values, and return them"""
|
LINE_WIDTH = 3
Draw = namedtuple(
"Draw",
"pen_color fill_color p_points b_points e_points",
)
LDraw = namedtuple(
"LDraw",
"font font_size pen_color text_x text_y text_w text_j text",
)
def points_to_pixels(points, dpi):
pixels = points * (dpi / 72) # 72 points per inch
return pixels
class Graph:
def __init__(self, pen_color, fill_color, polygon_points):
self._pen_color = pen_color
self._fill_color = fill_color
self._polygon_points = polygon_points
def split_attributes(attr_string):
attributes_dict = {}
attr_lines = re.split(r",(?!\d)", attr_string)
for attr_line in attr_lines:
attrs = attr_line.replace('"', "")
key, value = attrs.split("=")
attributes_dict[key] = value
return attributes_dict
def compact_dot_format(file_content):
file_content = file_content.replace("\n\t", "")
file_content = file_content.replace("{", "{\n")
file_content = file_content.replace(";", ";\n")
file_content = file_content.replace(" ", "")
file_content = file_content.replace("\n\n", "")
file_content = file_content.replace("\\\n", "")
file_content = file_content.replace("}", "")
return file_content
def split_numbers(sequence, n):
# Create a regex pattern for n numbers
pattern = r"((?:\b\d+\b\s*){" + str(n) + r"})(.*)"
match = re.match(pattern, sequence)
return match.groups() if match else (sequence, "")
def array_chunk(lst, chunk_size):
return [lst[i : i + chunk_size] for i in range(0, len(lst), chunk_size)]
def parse_draw(draw_string, dpi):
rest = draw_string.strip()
pen_color = None
fill_color = None
p_points = None
b_points = None
e_points = None
while rest.strip():
command, rest = rest[0], rest[2:]
if command == "c":
num, rest = int(rest[0]), rest[3:]
pen_color, rest = rest[:num], rest[num + 1 :]
continue
if command == "C":
num, rest = int(rest[0]), rest[3:]
fill_color, rest = rest[:num], rest[num + 1 :]
continue
if command == "P":
num, rest = int(rest[0]), rest[2:]
p_points, rest = split_numbers(rest, num * 2)
p_points = array_chunk([float(i) for i in p_points.split()], 2)
continue
if command == "e":
e_points, rest = split_numbers(rest, 4)
e_points = [float(i) for i in e_points.split()]
continue
if command == "B":
num, rest = int(rest[0]), rest[2:]
b_points, rest = split_numbers(rest, num)
b_points = [float(i) for i in b_points.split()]
continue
raise Exception(rest)
return Draw(
fill_color=fill_color,
pen_color=pen_color,
p_points=[
[points_to_pixels(i[0], dpi), points_to_pixels(i[1], dpi)] for i in p_points
]
if p_points
else None,
b_points=[points_to_pixels(i, dpi) for i in b_points] if b_points else None,
e_points=[points_to_pixels(i, dpi) for i in e_points] if e_points else None,
)
def parse_ldraw(ldraw_string, dpi):
rest = ldraw_string.strip()
font = None
font_size = None
pen_color = None
text_x = None
text_y = None
text_w = None
text_j = None
text = None
while rest.strip():
command, rest = rest[0], rest[2:]
if command == "F":
first_space = rest.find(" ")
font_size, rest = int(rest[:first_space]), rest[first_space + 1 :]
first_space = rest.find(" ")
num, rest = int(rest[:first_space]), rest[first_space:]
font, rest = (
rest[first_space : first_space + num],
rest[first_space + num + 1 :],
)
continue
if command == "c":
num, rest = int(rest[0]), rest[3:]
pen_color, rest = rest[:num], rest[num + 1 :]
continue
if command == "T":
nums, text = rest.split("-")
text_x, text_y, text_j, text_w, text_len = [float(i) for i in nums.split()]
rest = ""
continue
raise Exception(f"command = {command}; rest = {rest}")
return LDraw(
font=font,
font_size=font_size,
pen_color=pen_color,
text_x=points_to_pixels(text_x, dpi),
text_y=points_to_pixels(text_y, dpi),
text_w=points_to_pixels(text_w, dpi),
text_j=text_j,
text=text,
)
def get_dimensions(points):
x_values = [point[0] for point in points]
y_values = [point[1] for point in points]
width = max(x_values) - min(x_values)
height = max(y_values) - min(y_values)
return int(width), int(height)
def hex_to_rgb(hex_color):
if not hex_color:
return None
if not isinstance(hex_color, str):
return hex_color
hex_color = hex_color.lstrip("#")
return tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
def draw_ellipse(
offsets,
image,
e_points,
node_outline_color=None,
node_fill_color=None,
node_shadow_color=None,
node_shadow_size=None,
line_width=None,
):
x0, y0, w, h = e_points
x0 += offsets[0]
y0 += offsets[1]
bounding_box = [
x0 - w,
y0 - h,
x0 + w,
y0 + h,
]
# Draw shadow if bg_fade and bg_fade_size are provided
if node_shadow_color and node_shadow_size:
# Calculate the size increase based on the percentage
increase_w = w * node_shadow_size
increase_h = h * node_shadow_size
shadow_size = [
x0 - w - increase_w,
y0 - h - increase_h,
x0 + w + increase_w,
y0 + h + increase_h,
]
# Create a temporary image for the shadow
temp_image = Image.new("RGBA", image.size, (0, 0, 0, 0))
temp_draw = ImageDraw.Draw(temp_image)
# Draw and blur the shadow ellipse
temp_draw.ellipse(shadow_size, fill=node_shadow_color)
blur_radius = int(max(increase_w, increase_h)) / 2 # Gaussian blur radius
temp_image = temp_image.filter(ImageFilter.GaussianBlur(radius=blur_radius))
# Merge shadow with the main image
image.paste(temp_image, (0, 0), temp_image)
draw = ImageDraw.Draw(image)
# Draw the main ellipse
draw.ellipse(
bounding_box,
outline=hex_to_rgb(node_outline_color) if node_outline_color else None,
fill=hex_to_rgb(node_fill_color) if node_fill_color else None,
width=line_width,
)
def bezier_point(t, points):
while len(points) > 1:
points = [
tuple((1 - t) * p0 + t * p1 for p0, p1 in zip(points[i], points[i + 1]))
for i in range(len(points) - 1)
]
return points[0]
def draw_bezier_curve(offsets, image, points, pen_color, line_width, blur_radius):
# Create a transparent image to draw the curve
curve_image = Image.new("RGBA", image.size, (0, 0, 0, 0))
draw = ImageDraw.Draw(curve_image)
# Adjust points with offsets
points = [points[i : i + 2] for i in range(0, len(points), 2)]
points = [(c[0] + offsets[0], c[1] + offsets[1]) for c in points]
# Define the bezier curve function
def bezier_point(t, points):
n = len(points) - 1
return tuple(
sum(
c * (t**i) * ((1 - t) ** (n - i)) * math.comb(n, i)
for i, c in enumerate(coords)
)
for coords in zip(*points)
)
# Split the curve into segments and draw
segments = 500
curve = [bezier_point(t / segments, points) for t in range(segments + 1)]
for i in range(segments):
draw.line((curve[i], curve[i + 1]), fill=pen_color, width=line_width)
# Apply a blur filter to the curve image
curve_image = curve_image.filter(ImageFilter.GaussianBlur(blur_radius))
# Composite the blurred curve onto the original image
image.paste(curve_image, (0, 0), curve_image)
return image
def hex_to_rgba(color, alpha):
return (
*int(color[1:], 16).to_bytes(3, "big"),
alpha,
)
def calculate_alpha(frame_number, total_frames):
fade_in_end = total_frames * 0.1
fade_out_start = total_frames * 0.5
if frame_number < fade_in_end:
# Fade in phase
return int(255 * (frame_number / fade_in_end))
elif frame_number <= fade_out_start:
# Full opacity phase
return 255
else:
# Fade out phase
return int(
255 * ((total_frames - frame_number) / (total_frames - fade_out_start))
)
def draw_fading_bezier_curve(
base_image,
offsets,
theme,
points,
frame_number,
track,
animation_len,
):
# Create a new transparent image to draw the Bézier curve
overlay_image = Image.new("RGBA", base_image.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(overlay_image)
# Calculate alpha value for current frame
alpha = calculate_alpha(frame_number, animation_len)
# Split the points into pairs and apply offsets
points = [points[i : i + 2] for i in range(0, len(points), 2)]
points = [(c[0] + offsets[0], c[1] + offsets[1]) for c in points]
# Split the curve into segments
segments = 300 * len(points)
curve = [bezier_point(t / segments, points) for t in range(segments + 1)]
# Draw the border/shadow
border_width = theme.chord_line_width(track) * 2
border_rgba_color = hex_to_rgba(theme.chord_line_border_color(track), alpha)
for i in range(segments):
draw.line(
(
curve[i],
curve[i + 1],
),
fill=border_rgba_color,
width=border_width,
)
overlay_image = overlay_image.filter(ImageFilter.GaussianBlur(radius=5))
draw = ImageDraw.Draw(overlay_image)
# Convert hex color to RGBA with alpha for main line
rgba_color = hex_to_rgba(theme.chord_line_color(track), alpha)
# Draw the main line with fading effect
for i in range(segments):
draw.line(
(
curve[i],
curve[i + 1],
),
fill=rgba_color,
width=theme.chord_line_width(track),
)
# Composite the transparent overlay onto the base image
return Image.alpha_composite(
base_image.convert("RGBA"),
overlay_image,
)
def animate_bezier_point(
base_image,
offsets,
theme,
track,
points,
frame_number,
animation_length_in_frames,
):
overlay_image = Image.new(
"RGBA",
base_image.size,
color=None,
)
draw = ImageDraw.Draw(overlay_image)
x_offset, y_offset = offsets
t = frame_number / animation_length_in_frames
point = bezier_point(t, [points[i : i + 2] for i in range(0, len(points), 2)])
point_center = (x_offset + point[0], y_offset + point[1])
# Draw the 3D-looking circle
for i in range(theme.ball_radius(track) // 2):
# Calculate the color gradient based on the specified ball color
draw.ellipse(
[
(point_center[0] - i, point_center[1] - i),
(point_center[0] + i, point_center[1] + i),
],
fill=theme.ball_color(track),
outline=hex_to_rgb(theme.ball_stroke_color(track)),
width=theme.ball_stroke_width(track),
)
blur_max = theme.ball_g_blur_max(track)
if blur_max:
blur_radius = min(
animation_length_in_frames - frame_number,
theme.ball_g_blur_max(track) / (frame_number + 1),
)
overlay_image = overlay_image.filter(
ImageFilter.GaussianBlur(radius=blur_radius)
)
# Composite the transparent overlay onto the base image
return Image.alpha_composite(
base_image.convert("RGBA"),
overlay_image,
)
def animate_ellipsis_blur(
base_image,
points,
frame_number,
offsets,
theme,
track,
animation_len,
velocity,
):
image = base_image.copy()
draw = ImageDraw.Draw(image)
x_offset, y_offset = offsets
x0, y0, w, h = points
x0 += x_offset
y0 += y_offset
# Calculate the increase in size
w_increase = w * theme.note_increase_size(track) * (velocity / 127)
h_increase = h * theme.note_increase_size(track) * (velocity / 127)
# Define the bounding box with the increased size
bounding_box = [
x0 - w - w_increase / 2,
y0 - h - h_increase / 2,
x0 + w + w_increase / 2,
y0 + h + h_increase / 2,
]
# Draw the initial ellipse
draw.ellipse(
bounding_box,
outline=hex_to_rgb(theme.note_color(track)),
width=theme.note_stroke_width(track),
)
# Determine the blur radius for this frame
blur_strength = (frame_number / animation_len) * velocity
blur_radius = max(1, blur_strength)
# Create a mask for the ellipse to constrain the blur effect
mask = Image.new("L", image.size, 0)
mask_draw = ImageDraw.Draw(mask)
mask_draw.ellipse(bounding_box, fill=255)
# Apply the blur effect on the mask
mask_blurred = mask.filter(ImageFilter.GaussianBlur(blur_radius))
# Create a solid image for the blur color
ellipse = Image.new("RGBA", image.size, hex_to_rgb(theme.note_color(track)))
# Composite the blurred mask with the ellipse onto the base image
image.paste(ellipse, mask=mask_blurred)
return image
def draw_centered_text(
offsets,
image,
text,
x,
y,
font_path,
font_size,
color,
outline_color,
stroke_width,
):
font = ImageFont.truetype(font_path, font_size)
draw = ImageDraw.Draw(image)
x += offsets[0]
y += offsets[1]
draw.text(
(x, y),
text,
font=font,
fill=hex_to_rgb(color),
stroke_width=stroke_width,
stroke_fill=hex_to_rgb(outline_color),
)
return image
def paste_center(host_image, image):
host_width, host_height = host_image.size
width, height = image.size
x = (host_width - width) // 2
y = (host_height - height) // 2
host_image.paste(image, (x, y), image)
def get_node_positions(graph):
"""Draw a graph to a file, load it, then parse it's `node[pos] values, and return them""" | temp_filename = f"{get_cache_dir()}/graph_order" | 1 | 2023-11-17 17:56:04+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.