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 |
|---|---|---|---|---|---|---|---|---|---|---|
YaoFANGUK/video-subtitle-remover | backend/inpaint/video/raft/corr.py | [
{
"identifier": "bilinear_sampler",
"path": "backend/inpaint/video/raft/utils/utils.py",
"snippet": "def bilinear_sampler(img, coords, mode='bilinear', mask=False):\n \"\"\" Wrapper for grid_sample, uses pixel coordinates \"\"\"\n H, W = img.shape[-2:]\n xgrid, ygrid = coords.split([1,1], dim=-... | import torch
import torch.nn.functional as F
import alt_cuda_corr
from .utils.utils import bilinear_sampler, coords_grid | 673 |
try:
except:
# alt_cuda_corr is not compiled
pass
class CorrBlock:
def __init__(self, fmap1, fmap2, num_levels=4, radius=4):
self.num_levels = num_levels
self.radius = radius
self.corr_pyramid = []
# all pairs correlation
corr = CorrBlock.corr(fmap1, fmap2)
batch, h1, w1, dim, h2, w2 = corr.shape
corr = corr.reshape(batch*h1*w1, dim, h2, w2)
self.corr_pyramid.append(corr)
for i in range(self.num_levels-1):
corr = F.avg_pool2d(corr, 2, stride=2)
self.corr_pyramid.append(corr)
def __call__(self, coords):
r = self.radius
coords = coords.permute(0, 2, 3, 1)
batch, h1, w1, _ = coords.shape
out_pyramid = []
for i in range(self.num_levels):
corr = self.corr_pyramid[i]
dx = torch.linspace(-r, r, 2*r+1)
dy = torch.linspace(-r, r, 2*r+1)
delta = torch.stack(torch.meshgrid(dy, dx), axis=-1).to(coords.device)
centroid_lvl = coords.reshape(batch*h1*w1, 1, 1, 2) / 2**i
delta_lvl = delta.view(1, 2*r+1, 2*r+1, 2)
coords_lvl = centroid_lvl + delta_lvl
|
try:
except:
# alt_cuda_corr is not compiled
pass
class CorrBlock:
def __init__(self, fmap1, fmap2, num_levels=4, radius=4):
self.num_levels = num_levels
self.radius = radius
self.corr_pyramid = []
# all pairs correlation
corr = CorrBlock.corr(fmap1, fmap2)
batch, h1, w1, dim, h2, w2 = corr.shape
corr = corr.reshape(batch*h1*w1, dim, h2, w2)
self.corr_pyramid.append(corr)
for i in range(self.num_levels-1):
corr = F.avg_pool2d(corr, 2, stride=2)
self.corr_pyramid.append(corr)
def __call__(self, coords):
r = self.radius
coords = coords.permute(0, 2, 3, 1)
batch, h1, w1, _ = coords.shape
out_pyramid = []
for i in range(self.num_levels):
corr = self.corr_pyramid[i]
dx = torch.linspace(-r, r, 2*r+1)
dy = torch.linspace(-r, r, 2*r+1)
delta = torch.stack(torch.meshgrid(dy, dx), axis=-1).to(coords.device)
centroid_lvl = coords.reshape(batch*h1*w1, 1, 1, 2) / 2**i
delta_lvl = delta.view(1, 2*r+1, 2*r+1, 2)
coords_lvl = centroid_lvl + delta_lvl
| corr = bilinear_sampler(corr, coords_lvl) | 0 | 2023-10-25 02:50:01+00:00 | 2k |
Genesis-Embodied-AI/RoboGen | objaverse_utils/find_uid_utils.py | [
{
"identifier": "text_to_uid_dict",
"path": "objaverse_utils/utils.py",
"snippet": ""
},
{
"identifier": "check_text_similarity",
"path": "gpt_4/verification.py",
"snippet": "def check_text_similarity(text, check_list=None, check_embeddings=None):\n global sentence_bert_model\n if ... | import pandas as pd
import torch
import numpy as np
import json
from objaverse_utils.utils import text_to_uid_dict
from gpt_4.verification import check_text_similarity
from gpt_4.bard_verify import verify_objaverse_object | 1,182 |
objaverse_csv = pd.read_csv('objaverse_utils/Cap3D_automated_Objaverse.csv')
objaverse_csv = objaverse_csv.dropna()
objaverse_csv_uids = list(objaverse_csv.iloc[:, 0].values)
objaverse_csv_annotations = list(objaverse_csv.iloc[:, 1].values)
objaverse_csv_annotations_embeddings = torch.load("objaverse_utils/data/cap3d_sentence_bert_embeddings.pt")
tag_uids = []
tag_embeddings = []
tag_descriptions = []
num_chunks = 31
for idx in range(num_chunks):
uids = torch.load("objaverse_utils/data/default_tag_uids_{}.pt".format(idx))
embeddings = torch.load("objaverse_utils/data/default_tag_embeddings_{}.pt".format(idx))
descriptions = torch.load("objaverse_utils/data/default_tag_names_{}.pt".format(idx))
tag_uids = tag_uids + uids
tag_descriptions = tag_descriptions + descriptions
tag_embeddings.append(embeddings)
def find_uid(obj_descrption, candidate_num=10, debug=False, task_name=None, task_description=None):
|
objaverse_csv = pd.read_csv('objaverse_utils/Cap3D_automated_Objaverse.csv')
objaverse_csv = objaverse_csv.dropna()
objaverse_csv_uids = list(objaverse_csv.iloc[:, 0].values)
objaverse_csv_annotations = list(objaverse_csv.iloc[:, 1].values)
objaverse_csv_annotations_embeddings = torch.load("objaverse_utils/data/cap3d_sentence_bert_embeddings.pt")
tag_uids = []
tag_embeddings = []
tag_descriptions = []
num_chunks = 31
for idx in range(num_chunks):
uids = torch.load("objaverse_utils/data/default_tag_uids_{}.pt".format(idx))
embeddings = torch.load("objaverse_utils/data/default_tag_embeddings_{}.pt".format(idx))
descriptions = torch.load("objaverse_utils/data/default_tag_names_{}.pt".format(idx))
tag_uids = tag_uids + uids
tag_descriptions = tag_descriptions + descriptions
tag_embeddings.append(embeddings)
def find_uid(obj_descrption, candidate_num=10, debug=False, task_name=None, task_description=None): | uids = text_to_uid_dict.get(obj_descrption, None) | 0 | 2023-10-31 19:44:09+00:00 | 2k |
junhoyeo/BetterOCR | betterocr/detect.py | [
{
"identifier": "extract_json",
"path": "betterocr/parsers.py",
"snippet": "def extract_json(input_string):\n # Find the JSON in the string\n matches = re.findall(r'{\\s*\"data\"\\s*:\\s*\"(.*?)\"\\s*}', input_string, re.DOTALL)\n if matches:\n # Correctly escape special characters\n ... | from threading import Thread
from queue import Queue
from openai import OpenAI
from .parsers import extract_json, extract_list, rectangle_corners
from .wrappers import (
job_easy_ocr,
job_easy_ocr_boxes,
job_tesseract,
job_tesseract_boxes,
)
from .wrappers.easy_pororo_ocr import job_easy_pororo_ocr
from .wrappers.easy_pororo_ocr import job_easy_pororo_ocr_boxes
import json
import os | 1,298 |
def wrapper(func, args, queue):
queue.put(func(args))
# custom error
class NoTextDetectedError(Exception):
pass
def detect():
"""Unimplemented"""
raise NotImplementedError
def detect_async():
"""Unimplemented"""
raise NotImplementedError
def get_jobs(languages: list[str], boxes=False):
jobs = [
|
def wrapper(func, args, queue):
queue.put(func(args))
# custom error
class NoTextDetectedError(Exception):
pass
def detect():
"""Unimplemented"""
raise NotImplementedError
def detect_async():
"""Unimplemented"""
raise NotImplementedError
def get_jobs(languages: list[str], boxes=False):
jobs = [ | job_easy_ocr if not boxes else job_easy_ocr_boxes, | 3 | 2023-10-26 11:26:25+00:00 | 2k |
KoeAI/LLVC | infer.py | [
{
"identifier": "Net",
"path": "model.py",
"snippet": "class Net(nn.Module):\n def __init__(self, label_len, L=8,\n enc_dim=512, num_enc_layers=10,\n dec_dim=256, dec_buf_len=100, num_dec_layers=2,\n dec_chunk_size=72, out_buf_len=2,\n u... | from model import Net
from utils import glob_audio_files
from tqdm import tqdm
import torch
import torchaudio
import time
import numpy as np
import argparse
import json
import os | 1,507 |
def load_model(checkpoint_path, config_path):
with open(config_path) as f:
config = json.load(f)
|
def load_model(checkpoint_path, config_path):
with open(config_path) as f:
config = json.load(f) | model = Net(**config['model_params']) | 0 | 2023-10-28 01:58:49+00:00 | 2k |
aurelio-labs/semantic-router | semantic_router/llms/llamacpp.py | [
{
"identifier": "BaseLLM",
"path": "semantic_router/llms/base.py",
"snippet": "class BaseLLM(BaseModel):\n name: str\n\n class Config:\n arbitrary_types_allowed = True\n\n def __init__(self, name: str, **kwargs):\n super().__init__(name=name, **kwargs)\n\n def __call__(self, me... | from contextlib import contextmanager
from pathlib import Path
from typing import Any, Optional
from llama_cpp import Llama, LlamaGrammar
from semantic_router.llms.base import BaseLLM
from semantic_router.schema import Message
from semantic_router.utils.logger import logger | 1,212 |
class LlamaCppLLM(BaseLLM):
llm: Llama
temperature: float
max_tokens: Optional[int] = 200
grammar: Optional[LlamaGrammar] = None
def __init__(
self,
llm: Llama,
name: str = "llama.cpp",
temperature: float = 0.2,
max_tokens: Optional[int] = 200,
grammar: Optional[LlamaGrammar] = None,
):
super().__init__(
name=name,
llm=llm,
temperature=temperature,
max_tokens=max_tokens,
grammar=grammar,
)
self.llm = llm
self.temperature = temperature
self.max_tokens = max_tokens
self.grammar = grammar
def __call__(
self,
messages: list[Message],
) -> str:
try:
completion = self.llm.create_chat_completion(
messages=[m.to_llamacpp() for m in messages],
temperature=self.temperature,
max_tokens=self.max_tokens,
grammar=self.grammar,
stream=False,
)
assert isinstance(completion, dict) # keep mypy happy
output = completion["choices"][0]["message"]["content"]
if not output:
raise Exception("No output generated")
return output
except Exception as e:
|
class LlamaCppLLM(BaseLLM):
llm: Llama
temperature: float
max_tokens: Optional[int] = 200
grammar: Optional[LlamaGrammar] = None
def __init__(
self,
llm: Llama,
name: str = "llama.cpp",
temperature: float = 0.2,
max_tokens: Optional[int] = 200,
grammar: Optional[LlamaGrammar] = None,
):
super().__init__(
name=name,
llm=llm,
temperature=temperature,
max_tokens=max_tokens,
grammar=grammar,
)
self.llm = llm
self.temperature = temperature
self.max_tokens = max_tokens
self.grammar = grammar
def __call__(
self,
messages: list[Message],
) -> str:
try:
completion = self.llm.create_chat_completion(
messages=[m.to_llamacpp() for m in messages],
temperature=self.temperature,
max_tokens=self.max_tokens,
grammar=self.grammar,
stream=False,
)
assert isinstance(completion, dict) # keep mypy happy
output = completion["choices"][0]["message"]["content"]
if not output:
raise Exception("No output generated")
return output
except Exception as e: | logger.error(f"LLM error: {e}") | 2 | 2023-10-30 12:12:45+00:00 | 2k |
baaivision/JudgeLM | judgelm/llm_judge/gen_model_judgement_mmvet.py | [
{
"identifier": "load_questions",
"path": "judgelm/llm_judge/common.py",
"snippet": "def parse_score(review):\ndef translate_score_to_win_list(score_list, T=0.0):\ndef generate_question_template(domain, question1, question2):\ndef reorg_answer_file(answer_file):\n def __init__(self, keywords, tokeniz... | import argparse
import json
import os
import time
import shortuuid
import torch
import sys
import random
import ray
from tqdm import tqdm
from pathlib import Path # if you haven't already done so
from judgelm.llm_judge.common import load_questions, reorg_answer_file, conv_judge_vqa_single_answer, KeywordsStoppingCriteria
from judgelm.model import load_model | 937 | """Generate answers with local models.
"""
file = Path(__file__).resolve()
root = file.parents[2]
sys.path.append(str(root))
print(sys.path)
def run_eval(
model_path,
model_id,
question_file,
question_begin,
question_end,
answer_file,
max_new_token,
num_gpus_per_model,
num_gpus_total,
max_gpu_memory,
temperature,
if_fast_eval
):
questions = load_questions(question_file, question_begin, question_end)
# Split the question file into `num_gpus` files
assert num_gpus_total % num_gpus_per_model == 0
use_ray = num_gpus_total // num_gpus_per_model > 1
if use_ray:
get_answers_func = ray.remote(num_gpus=num_gpus_per_model)(
get_model_answers
).remote
else:
get_answers_func = get_model_answers
chunk_size = len(questions) // (num_gpus_total // num_gpus_per_model) # // 2
ans_handles = []
for i in range(0, len(questions), chunk_size):
ans_handles.append(
get_answers_func(
model_path,
model_id,
questions[i : i + chunk_size],
answer_file,
max_new_token,
num_gpus_per_model,
max_gpu_memory,
temperature,
if_fast_eval,
)
)
if use_ray:
ray.get(ans_handles)
@torch.inference_mode()
def get_model_answers(
model_path,
model_id,
questions,
answer_file,
max_new_token,
num_gpus_per_model,
max_gpu_memory,
temperature,
if_fast_eval,
):
| """Generate answers with local models.
"""
file = Path(__file__).resolve()
root = file.parents[2]
sys.path.append(str(root))
print(sys.path)
def run_eval(
model_path,
model_id,
question_file,
question_begin,
question_end,
answer_file,
max_new_token,
num_gpus_per_model,
num_gpus_total,
max_gpu_memory,
temperature,
if_fast_eval
):
questions = load_questions(question_file, question_begin, question_end)
# Split the question file into `num_gpus` files
assert num_gpus_total % num_gpus_per_model == 0
use_ray = num_gpus_total // num_gpus_per_model > 1
if use_ray:
get_answers_func = ray.remote(num_gpus=num_gpus_per_model)(
get_model_answers
).remote
else:
get_answers_func = get_model_answers
chunk_size = len(questions) // (num_gpus_total // num_gpus_per_model) # // 2
ans_handles = []
for i in range(0, len(questions), chunk_size):
ans_handles.append(
get_answers_func(
model_path,
model_id,
questions[i : i + chunk_size],
answer_file,
max_new_token,
num_gpus_per_model,
max_gpu_memory,
temperature,
if_fast_eval,
)
)
if use_ray:
ray.get(ans_handles)
@torch.inference_mode()
def get_model_answers(
model_path,
model_id,
questions,
answer_file,
max_new_token,
num_gpus_per_model,
max_gpu_memory,
temperature,
if_fast_eval,
): | model, tokenizer = load_model( | 1 | 2023-10-26 19:41:07+00:00 | 2k |
EulerSearch/embedding_studio | embedding_studio/api/api_v1/endpoints/fine_tuning.py | [
{
"identifier": "FineTuningTaskCreate",
"path": "embedding_studio/api/api_v1/schemas/fine_tuning.py",
"snippet": "class FineTuningTaskCreate(BaseModel):\n fine_tuning_method: str\n batch_id: Optional[str] = None\n metadata: Optional[Dict] = None\n idempotency_key: Optional[uuid.UUID] = None"... | import logging
from typing import Any, List
from dramatiq_abort import abort as dramatiq_abort
from fastapi import APIRouter, HTTPException, status
from embedding_studio.api.api_v1.schemas.fine_tuning import (
FineTuningTaskCreate,
FineTuningTaskResponse,
)
from embedding_studio.context.app_context import context
from embedding_studio.models.fine_tuning import FineTuningStatus
from embedding_studio.workers.fine_tuning.worker import fine_tuning_worker | 1,238 |
logger = logging.getLogger(__name__)
router = APIRouter()
@router.post(
"/task",
response_model=FineTuningTaskResponse,
response_model_by_alias=False,
response_model_exclude_none=True,
)
def create_fine_tuning_task(
|
logger = logging.getLogger(__name__)
router = APIRouter()
@router.post(
"/task",
response_model=FineTuningTaskResponse,
response_model_by_alias=False,
response_model_exclude_none=True,
)
def create_fine_tuning_task( | body: FineTuningTaskCreate, | 0 | 2023-10-31 00:33:13+00:00 | 2k |
reworkd/bananalyzer | tests/test_examples.py | [
{
"identifier": "download_examples",
"path": "bananalyzer/data/examples.py",
"snippet": "def are_examples_available(path: Path) -> bool:\ndef get_examples_path() -> Path:\ndef convert_to_crlf(file_path: Path) -> None:\ndef download_examples() -> None:\ndef load_examples_at_path(path: Path, examples_json... | import json
import os
import shutil
import pytest
from pathlib import Path
from typing import List
from unittest.mock import mock_open
from pytest_mock import MockFixture
from bananalyzer.data.examples import (
download_examples,
downloaded_examples_path,
get_all_examples,
get_example_by_url,
get_examples_path,
get_test_examples,
get_training_examples,
load_examples_at_path,
local_examples_path,
)
from bananalyzer.data.schemas import Example | 932 |
def test_load_examples_at_path_success(mocker: MockFixture) -> None:
data: List[Example] = []
mocker.patch("builtins.open", mock_open(read_data=json.dumps(data)))
loaded_examples = load_examples_at_path(Path("/fake/path"), "fake.json")
assert len(loaded_examples) == len(data)
assert all(isinstance(example, Example) for example in loaded_examples)
def test_load_examples_at_path_json_error(mocker: MockFixture) -> None:
mocker.patch("builtins.open", mock_open(read_data="invalid json"))
with pytest.raises(json.JSONDecodeError):
load_examples_at_path(Path("/fake/path"), "fake.json")
def test_load_examples_at_path_file_not_found(mocker: MockFixture) -> None:
mocker.patch("builtins.open", side_effect=FileNotFoundError)
with pytest.raises(FileNotFoundError):
load_examples_at_path(Path("/fake/path"), "fake.json")
def test_get_local_examples_path() -> None:
# Running test in repo will default to local path
|
def test_load_examples_at_path_success(mocker: MockFixture) -> None:
data: List[Example] = []
mocker.patch("builtins.open", mock_open(read_data=json.dumps(data)))
loaded_examples = load_examples_at_path(Path("/fake/path"), "fake.json")
assert len(loaded_examples) == len(data)
assert all(isinstance(example, Example) for example in loaded_examples)
def test_load_examples_at_path_json_error(mocker: MockFixture) -> None:
mocker.patch("builtins.open", mock_open(read_data="invalid json"))
with pytest.raises(json.JSONDecodeError):
load_examples_at_path(Path("/fake/path"), "fake.json")
def test_load_examples_at_path_file_not_found(mocker: MockFixture) -> None:
mocker.patch("builtins.open", side_effect=FileNotFoundError)
with pytest.raises(FileNotFoundError):
load_examples_at_path(Path("/fake/path"), "fake.json")
def test_get_local_examples_path() -> None:
# Running test in repo will default to local path | assert get_examples_path() == local_examples_path | 0 | 2023-10-30 16:40:57+00:00 | 2k |
OpenMask3D/openmask3d | openmask3d/mask_features_computation/features_extractor.py | [
{
"identifier": "Camera",
"path": "openmask3d/data/load.py",
"snippet": "class Camera:\n def __init__(self, \n intrinsic_path, \n intrinsic_resolution, \n poses_path, \n depths_path, \n extension_depth, \n ... | import clip
import numpy as np
import imageio
import torch
import os
from tqdm import tqdm
from openmask3d.data.load import Camera, InstanceMasks3D, Images, PointCloud, get_number_of_images
from openmask3d.mask_features_computation.utils import initialize_sam_model, mask2box_multi_level, run_sam | 1,519 |
class PointProjector:
def __init__(self, camera: Camera,
point_cloud: PointCloud,
|
class PointProjector:
def __init__(self, camera: Camera,
point_cloud: PointCloud, | masks: InstanceMasks3D, | 1 | 2023-10-31 14:58:50+00:00 | 2k |
nv-tlabs/vid2player3d | embodied_pose/models/im_network_builder.py | [
{
"identifier": "RunningNorm",
"path": "embodied_pose/models/running_norm.py",
"snippet": "class RunningNorm(nn.Module):\n \"\"\"\n y = (x-mean)/std\n using running estimates of mean,std\n \"\"\"\n\n def __init__(self, dim, demean=True, destd=True, clip=5.0):\n super().__init__()\n... | from rl_games.algos_torch import network_builder
from rl_games.algos_torch.running_mean_std import RunningMeanStd
from isaacgym.torch_utils import *
from .running_norm import RunningNorm
from utils import torch_utils
from utils.torch_transform import heading_to_vec, rotation_matrix_to_angle_axis, rotation_matrix_to_quaternion, rot6d_to_rotmat
from utils.hybrik import batch_inverse_kinematics_transform_naive, batch_inverse_kinematics_transform
from uhc.smpllib.smpl_parser import SMPL_BONE_ORDER_NAMES as smpl_joint_names
import torch
import torch.nn as nn
import numpy as np | 1,231 |
DISC_LOGIT_INIT_SCALE = 1.0
mujoco_joint_names = [
'Pelvis', 'L_Hip', 'L_Knee', 'L_Ankle', 'L_Toe', 'R_Hip', 'R_Knee',
'R_Ankle', 'R_Toe', 'Torso', 'Spine', 'Chest', 'Neck', 'Head', 'L_Thorax',
'L_Shoulder', 'L_Elbow', 'L_Wrist', 'L_Hand', 'R_Thorax', 'R_Shoulder',
'R_Elbow', 'R_Wrist', 'R_Hand'
]
smpl_2_mujoco = [smpl_joint_names.index(q) for q in mujoco_joint_names]
mujoco_2_smpl = [mujoco_joint_names.index(q) for q in smpl_joint_names]
class ImitatorBuilder(network_builder.A2CBuilder):
def __init__(self, **kwargs):
super().__init__(**kwargs)
return
class Network(network_builder.A2CBuilder.Network):
def __init__(self, params, **kwargs):
self.context_padding = params.get('context_padding', 8)
self.humanoid_obs_dim = params.get('humanoid_obs_dim', 734)
self.residual_action = params.get('residual_action', True)
self.use_running_obs = params.get('use_running_obs', False)
self.running_obs_type = params.get('running_obs_type', 'rl_game')
self.use_ik = params.get('use_ik', False)
self.ik_type = params.get('ik_type', 'optimized')
self.ik_ignore_outlier = params.get('ik_ignore_outlier', False)
self.kinematic_pretrained = params.get('kinematic_pretrained', False)
self.smpl_rest_joints = kwargs['smpl_rest_joints']
self.smpl_parents = kwargs['smpl_parents']
self.smpl_children = kwargs['smpl_children']
kwargs['input_shape'] = (self.humanoid_obs_dim,)
super().__init__(params, **kwargs)
if self.use_running_obs:
if self.running_obs_type == 'rl_game':
self.running_obs = RunningMeanStd((self.humanoid_obs_dim,))
else:
|
DISC_LOGIT_INIT_SCALE = 1.0
mujoco_joint_names = [
'Pelvis', 'L_Hip', 'L_Knee', 'L_Ankle', 'L_Toe', 'R_Hip', 'R_Knee',
'R_Ankle', 'R_Toe', 'Torso', 'Spine', 'Chest', 'Neck', 'Head', 'L_Thorax',
'L_Shoulder', 'L_Elbow', 'L_Wrist', 'L_Hand', 'R_Thorax', 'R_Shoulder',
'R_Elbow', 'R_Wrist', 'R_Hand'
]
smpl_2_mujoco = [smpl_joint_names.index(q) for q in mujoco_joint_names]
mujoco_2_smpl = [mujoco_joint_names.index(q) for q in smpl_joint_names]
class ImitatorBuilder(network_builder.A2CBuilder):
def __init__(self, **kwargs):
super().__init__(**kwargs)
return
class Network(network_builder.A2CBuilder.Network):
def __init__(self, params, **kwargs):
self.context_padding = params.get('context_padding', 8)
self.humanoid_obs_dim = params.get('humanoid_obs_dim', 734)
self.residual_action = params.get('residual_action', True)
self.use_running_obs = params.get('use_running_obs', False)
self.running_obs_type = params.get('running_obs_type', 'rl_game')
self.use_ik = params.get('use_ik', False)
self.ik_type = params.get('ik_type', 'optimized')
self.ik_ignore_outlier = params.get('ik_ignore_outlier', False)
self.kinematic_pretrained = params.get('kinematic_pretrained', False)
self.smpl_rest_joints = kwargs['smpl_rest_joints']
self.smpl_parents = kwargs['smpl_parents']
self.smpl_children = kwargs['smpl_children']
kwargs['input_shape'] = (self.humanoid_obs_dim,)
super().__init__(params, **kwargs)
if self.use_running_obs:
if self.running_obs_type == 'rl_game':
self.running_obs = RunningMeanStd((self.humanoid_obs_dim,))
else: | self.running_obs = RunningNorm(self.humanoid_obs_dim) | 0 | 2023-10-30 20:43:43+00:00 | 2k |
vLAR-group/RayDF | net_multiview/network.py | [
{
"identifier": "DualVisClassifier",
"path": "net_classifier/network.py",
"snippet": "class DualVisClassifier(nn.Module):\n def __init__(self, D=8, W=512, ext_layer=1, input_ch=11, w0_init=30.):\n super(DualVisClassifier, self).__init__()\n\n self.layer_ray = nn.ModuleList(\n ... | import os
import torch
import torch.nn as nn
import sys
from net_classifier.network import DualVisClassifier
from utils.layer import Siren
from utils.ray import get_rayparam_func | 1,173 | sys.path.append('../')
EPS = 1e-8
class RaySurfDNet(nn.Module):
def __init__(self, D=8, W=256, input_ch=4, rgb_layer=0, w0_init=30.):
super(RaySurfDNet, self).__init__()
self.predict_rgb = True if rgb_layer > 0 else False
n_ext = max(rgb_layer, 1)
self.lf_encoder = nn.ModuleList([Siren(input_ch, W, w0=w0_init, is_first=True)] +
[Siren(W, W) for i in range(1, D-n_ext)])
self.dist_dense = nn.ModuleList([Siren(W, W) for i in range(n_ext-1)] +
[Siren(W, 1, activation=nn.Identity())])
if self.predict_rgb:
self.color_dense = nn.ModuleList([Siren(W, W) for i in range(rgb_layer-1)] +
[Siren(W, 3, activation=nn.Identity())])
@staticmethod
def get_features(layers, x):
h = x
for i, l in enumerate(layers):
h = layers[i](h)
return h
def forward(self, x):
outputs = {}
feats = self.get_features(self.lf_encoder, x)
outputs['dist'] = self.get_features(self.dist_dense, feats)
if self.predict_rgb:
outputs['rgb'] = self.get_features(self.color_dense, feats)
return outputs
def create_net(args, scene_info, device):
| sys.path.append('../')
EPS = 1e-8
class RaySurfDNet(nn.Module):
def __init__(self, D=8, W=256, input_ch=4, rgb_layer=0, w0_init=30.):
super(RaySurfDNet, self).__init__()
self.predict_rgb = True if rgb_layer > 0 else False
n_ext = max(rgb_layer, 1)
self.lf_encoder = nn.ModuleList([Siren(input_ch, W, w0=w0_init, is_first=True)] +
[Siren(W, W) for i in range(1, D-n_ext)])
self.dist_dense = nn.ModuleList([Siren(W, W) for i in range(n_ext-1)] +
[Siren(W, 1, activation=nn.Identity())])
if self.predict_rgb:
self.color_dense = nn.ModuleList([Siren(W, W) for i in range(rgb_layer-1)] +
[Siren(W, 3, activation=nn.Identity())])
@staticmethod
def get_features(layers, x):
h = x
for i, l in enumerate(layers):
h = layers[i](h)
return h
def forward(self, x):
outputs = {}
feats = self.get_features(self.lf_encoder, x)
outputs['dist'] = self.get_features(self.dist_dense, feats)
if self.predict_rgb:
outputs['rgb'] = self.get_features(self.color_dense, feats)
return outputs
def create_net(args, scene_info, device): | ray_fn, input_ch = get_rayparam_func(scene_info) | 2 | 2023-10-30 14:05:51+00:00 | 2k |
francescofugazzi/3dgsconverter | gsconverter/utils/utility.py | [
{
"identifier": "debug_print",
"path": "gsconverter/utils/utility_functions.py",
"snippet": "def debug_print(message):\n if config.DEBUG:\n print(message)"
},
{
"identifier": "init_worker",
"path": "gsconverter/utils/utility_functions.py",
"snippet": "def init_worker():\n si... | import numpy as np
import multiprocessing
from multiprocessing import Pool, cpu_count
from .utility_functions import debug_print, init_worker | 913 | """
3D Gaussian Splatting Converter
Copyright (c) 2023 Francesco Fugazzi
This software is released under the MIT License.
For more information about the license, please see the LICENSE file.
"""
class Utility:
@staticmethod
def text_based_detect_format(file_path):
debug_print("[DEBUG] Executing 'text_based_detect_format' function...")
"""Detect if the given file is in '3dgs' or 'cc' format."""
with open(file_path, 'rb') as file:
header_bytes = file.read(2048) # Read the beginning to detect the format
header = header_bytes.decode('utf-8', errors='ignore')
if "property float f_dc_0" in header:
debug_print("[DEBUG] Detected format: 3dgs")
return "3dgs"
elif "property float scal_f_dc_0" in header or "property float scalar_scal_f_dc_0" in header or "property float scalar_f_dc_0" in header:
debug_print("[DEBUG] Detected format: cc")
return "cc"
else:
return None
@staticmethod
def copy_data_with_prefix_check(source, target, possible_prefixes):
debug_print("[DEBUG] Executing 'copy_data_with_prefix_check' function...")
"""
Given two structured numpy arrays (source and target), copy the data from source to target.
If a field exists in source but not in target, this function will attempt to find the field
in target by adding any of the possible prefixes to the field name.
"""
for name in source.dtype.names:
if name in target.dtype.names:
target[name] = source[name]
else:
copied = False
for prefix in possible_prefixes:
# If the field starts with the prefix, try the field name without the prefix
if name.startswith(prefix):
stripped_name = name[len(prefix):]
if stripped_name in target.dtype.names:
target[stripped_name] = source[name]
copied = True
break
# If the field doesn't start with any prefix, try adding the prefix
else:
prefixed_name = prefix + name
if prefixed_name in target.dtype.names:
debug_print(f"[DEBUG] Copying data from '{name}' to '{prefixed_name}'")
target[prefixed_name] = source[name]
copied = True
break
##if not copied:
## print(f"Warning: Field {name} not found in target.")
@staticmethod
def compute_rgb_from_vertex(vertices):
debug_print("[DEBUG] Executing 'compute_rgb_from_vertex' function...")
# Depending on the available field names, choose the appropriate ones
if 'f_dc_0' in vertices.dtype.names:
f_dc = np.column_stack((vertices['f_dc_0'], vertices['f_dc_1'], vertices['f_dc_2']))
else:
f_dc = np.column_stack((vertices['scalar_scal_f_dc_0'], vertices['scalar_scal_f_dc_1'], vertices['scalar_scal_f_dc_2']))
colors = (f_dc + 1) * 127.5
colors = np.clip(colors, 0, 255).astype(np.uint8)
debug_print("[DEBUG] RGB colors computed.")
return colors
@staticmethod
def parallel_voxel_counting(vertices, voxel_size=1.0):
debug_print("[DEBUG] Executing 'parallel_voxel_counting' function...")
"""Counts the number of points in each voxel in a parallelized manner."""
num_processes = cpu_count()
chunk_size = len(vertices) // num_processes
chunks = [vertices[i:i + chunk_size] for i in range(0, len(vertices), chunk_size)]
num_cores = max(1, multiprocessing.cpu_count() - 1)
| """
3D Gaussian Splatting Converter
Copyright (c) 2023 Francesco Fugazzi
This software is released under the MIT License.
For more information about the license, please see the LICENSE file.
"""
class Utility:
@staticmethod
def text_based_detect_format(file_path):
debug_print("[DEBUG] Executing 'text_based_detect_format' function...")
"""Detect if the given file is in '3dgs' or 'cc' format."""
with open(file_path, 'rb') as file:
header_bytes = file.read(2048) # Read the beginning to detect the format
header = header_bytes.decode('utf-8', errors='ignore')
if "property float f_dc_0" in header:
debug_print("[DEBUG] Detected format: 3dgs")
return "3dgs"
elif "property float scal_f_dc_0" in header or "property float scalar_scal_f_dc_0" in header or "property float scalar_f_dc_0" in header:
debug_print("[DEBUG] Detected format: cc")
return "cc"
else:
return None
@staticmethod
def copy_data_with_prefix_check(source, target, possible_prefixes):
debug_print("[DEBUG] Executing 'copy_data_with_prefix_check' function...")
"""
Given two structured numpy arrays (source and target), copy the data from source to target.
If a field exists in source but not in target, this function will attempt to find the field
in target by adding any of the possible prefixes to the field name.
"""
for name in source.dtype.names:
if name in target.dtype.names:
target[name] = source[name]
else:
copied = False
for prefix in possible_prefixes:
# If the field starts with the prefix, try the field name without the prefix
if name.startswith(prefix):
stripped_name = name[len(prefix):]
if stripped_name in target.dtype.names:
target[stripped_name] = source[name]
copied = True
break
# If the field doesn't start with any prefix, try adding the prefix
else:
prefixed_name = prefix + name
if prefixed_name in target.dtype.names:
debug_print(f"[DEBUG] Copying data from '{name}' to '{prefixed_name}'")
target[prefixed_name] = source[name]
copied = True
break
##if not copied:
## print(f"Warning: Field {name} not found in target.")
@staticmethod
def compute_rgb_from_vertex(vertices):
debug_print("[DEBUG] Executing 'compute_rgb_from_vertex' function...")
# Depending on the available field names, choose the appropriate ones
if 'f_dc_0' in vertices.dtype.names:
f_dc = np.column_stack((vertices['f_dc_0'], vertices['f_dc_1'], vertices['f_dc_2']))
else:
f_dc = np.column_stack((vertices['scalar_scal_f_dc_0'], vertices['scalar_scal_f_dc_1'], vertices['scalar_scal_f_dc_2']))
colors = (f_dc + 1) * 127.5
colors = np.clip(colors, 0, 255).astype(np.uint8)
debug_print("[DEBUG] RGB colors computed.")
return colors
@staticmethod
def parallel_voxel_counting(vertices, voxel_size=1.0):
debug_print("[DEBUG] Executing 'parallel_voxel_counting' function...")
"""Counts the number of points in each voxel in a parallelized manner."""
num_processes = cpu_count()
chunk_size = len(vertices) // num_processes
chunks = [vertices[i:i + chunk_size] for i in range(0, len(vertices), chunk_size)]
num_cores = max(1, multiprocessing.cpu_count() - 1) | with Pool(processes=num_cores, initializer=init_worker) as pool: | 1 | 2023-10-28 15:09:50+00:00 | 2k |
solangii/MICS | models/network/resnet20.py | [
{
"identifier": "to_one_hot",
"path": "utils/mixup_utils.py",
"snippet": "def to_one_hot(inp, num_classes):\n y_onehot = torch.FloatTensor(inp.size(0), num_classes)\n y_onehot.zero_()\n\n y_onehot.scatter_(1, inp.unsqueeze(1).data.cpu(), 1)\n\n return Variable(y_onehot.cuda(), requires_grad=... | import torch
import torch.nn as nn
import numpy as np
import random
from utils.mixup_utils import to_one_hot, middle_mixup_process, get_lambda
from torch.autograd import Variable | 1,436 |
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, last=False):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
self.last = last
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=10):
self.inplanes = 16
self.num_classes = num_classes
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1,
bias=False)
self.bn1 = nn.BatchNorm2d(16)
self.relu = nn.ReLU(inplace=True)
self.layer1 = self._make_layer(block, 16, layers[0])
self.layer2 = self._make_layer(block, 32, layers[1], stride=2)
self.layer3 = self._make_layer(block, 64, layers[2], stride=2, last_phase=True)
# self.avgpool = nn.AvgPool2d(8, stride=1)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block, planes, blocks, stride=1, last_phase=False):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
if last_phase:
for i in range(1, blocks - 1):
layers.append(block(self.inplanes, planes))
layers.append(block(self.inplanes, planes, last=True))
else:
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x, target=None, mix_type="vanilla", mixup_alpha=None, num_base_classes=-1,
use_hard_positive_aug=False, add_noise_level=0., mult_noise_level=0., minimum_lambda=0.5,
hpa_type="none", label_sharpening=True, label_mix="vanilla", label_mix_threshold=0.2,
exp_coef=1., cutmix_prob=1., num_similar_class=3, classifiers=None,
gaussian_h1=0.2, piecewise_linear_h1=0.5, piecewise_linear_h2=0., use_softlabel=True):
if "mixup_hidden" in mix_type:
layer_mix = random.randint(0, 2)
else:
layer_mix = None
out = x
if mixup_alpha is not None:
lam = get_lambda(mixup_alpha)
# https://github.com/YU1ut/MixMatch-pytorch/blob/master/train.py#L243
if use_hard_positive_aug:
lam = max(lam, 1 - lam)
lam = max(lam, minimum_lambda)
lam = torch.from_numpy(np.array([lam]).astype('float32')).cuda()
lam = Variable(lam)
if target is not None:
target_reweighted = to_one_hot(target, self.num_classes)
if layer_mix == 0:
|
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, last=False):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
self.last = last
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=10):
self.inplanes = 16
self.num_classes = num_classes
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1,
bias=False)
self.bn1 = nn.BatchNorm2d(16)
self.relu = nn.ReLU(inplace=True)
self.layer1 = self._make_layer(block, 16, layers[0])
self.layer2 = self._make_layer(block, 32, layers[1], stride=2)
self.layer3 = self._make_layer(block, 64, layers[2], stride=2, last_phase=True)
# self.avgpool = nn.AvgPool2d(8, stride=1)
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block, planes, blocks, stride=1, last_phase=False):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
if last_phase:
for i in range(1, blocks - 1):
layers.append(block(self.inplanes, planes))
layers.append(block(self.inplanes, planes, last=True))
else:
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x, target=None, mix_type="vanilla", mixup_alpha=None, num_base_classes=-1,
use_hard_positive_aug=False, add_noise_level=0., mult_noise_level=0., minimum_lambda=0.5,
hpa_type="none", label_sharpening=True, label_mix="vanilla", label_mix_threshold=0.2,
exp_coef=1., cutmix_prob=1., num_similar_class=3, classifiers=None,
gaussian_h1=0.2, piecewise_linear_h1=0.5, piecewise_linear_h2=0., use_softlabel=True):
if "mixup_hidden" in mix_type:
layer_mix = random.randint(0, 2)
else:
layer_mix = None
out = x
if mixup_alpha is not None:
lam = get_lambda(mixup_alpha)
# https://github.com/YU1ut/MixMatch-pytorch/blob/master/train.py#L243
if use_hard_positive_aug:
lam = max(lam, 1 - lam)
lam = max(lam, minimum_lambda)
lam = torch.from_numpy(np.array([lam]).astype('float32')).cuda()
lam = Variable(lam)
if target is not None:
target_reweighted = to_one_hot(target, self.num_classes)
if layer_mix == 0: | out, target_reweighted, mix_label_mask = middle_mixup_process(out, target_reweighted, num_base_classes, | 1 | 2023-10-25 16:50:51+00:00 | 2k |
megvii-research/WACV2024-SAFA | model/flownet.py | [
{
"identifier": "warp",
"path": "model/warplayer.py",
"snippet": "def warp(tenInput, tenFlow, mode='bilinear'):\n k = (str(tenFlow.device), str(tenFlow.size()))\n if k not in backwarp_tenGrid:\n tenHorizontal = torch.linspace(-1.0, 1.0, tenFlow.shape[3]).view(1, 1, 1, tenFlow.shape[3]).expa... | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
from model.warplayer import warp
from model.head import Head | 1,255 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1, groups=1):
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
padding=padding, dilation=dilation, bias=True, groups=groups),
nn.PReLU(out_planes)
)
def conv_bn(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
padding=padding, dilation=dilation, bias=False),
nn.BatchNorm2d(out_planes),
nn.PReLU(out_planes)
)
class Resblock(nn.Module):
def __init__(self, c, dilation=1):
super(Resblock, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1),
nn.PReLU(c),
nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1),
)
self.beta = nn.Parameter(torch.zeros((1, c, 1, 1)), requires_grad=True)
self.prelu = nn.PReLU(c)
def forward(self, x):
y = self.conv(x)
return self.prelu(y * self.beta + x)
class RoundSTE(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
y = torch.bernoulli(x)
return y
@staticmethod
def backward(ctx, grad):
return grad, None
class RecurrentBlock(nn.Module):
def __init__(self, c, dilation=1, depth=6):
super(RecurrentBlock, self).__init__()
self.conv_stem = conv(3*c+6+1, c, 3, 1, 1, groups=1)
self.conv_backbone = torch.nn.ModuleList([])
self.depth = depth
for i in range(depth):
self.conv_backbone.append(Resblock(c, dilation))
def forward(self, x, i0, i1, flow, timestep, convflow, getscale):
flow_down = F.interpolate(flow, scale_factor=0.5, mode="bilinear")
|
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1, groups=1):
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
padding=padding, dilation=dilation, bias=True, groups=groups),
nn.PReLU(out_planes)
)
def conv_bn(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride,
padding=padding, dilation=dilation, bias=False),
nn.BatchNorm2d(out_planes),
nn.PReLU(out_planes)
)
class Resblock(nn.Module):
def __init__(self, c, dilation=1):
super(Resblock, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1),
nn.PReLU(c),
nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1),
)
self.beta = nn.Parameter(torch.zeros((1, c, 1, 1)), requires_grad=True)
self.prelu = nn.PReLU(c)
def forward(self, x):
y = self.conv(x)
return self.prelu(y * self.beta + x)
class RoundSTE(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
y = torch.bernoulli(x)
return y
@staticmethod
def backward(ctx, grad):
return grad, None
class RecurrentBlock(nn.Module):
def __init__(self, c, dilation=1, depth=6):
super(RecurrentBlock, self).__init__()
self.conv_stem = conv(3*c+6+1, c, 3, 1, 1, groups=1)
self.conv_backbone = torch.nn.ModuleList([])
self.depth = depth
for i in range(depth):
self.conv_backbone.append(Resblock(c, dilation))
def forward(self, x, i0, i1, flow, timestep, convflow, getscale):
flow_down = F.interpolate(flow, scale_factor=0.5, mode="bilinear") | i0 = warp(i0, flow_down[:, :2] * 0.5) | 0 | 2023-10-26 09:24:29+00:00 | 2k |
Z4kSec/IoctlHunter | ioctl_hunter/ui/keys_reader.py | [
{
"identifier": "State",
"path": "ioctl_hunter/lib/state.py",
"snippet": "class State:\n results = Results()\n\n script = None\n cur_proc = None\n\n quiet = False\n running = True\n hook_enabled = False\n debug_enabled = False\n hex_out_enabled = False\n\n included_drivers = [... | import sys
import threading
import time
import logging
import msvcrt
from colorama import init, Fore, Style
from ..lib.state import State
from ..ui.display import (
print_enable_debugger,
print_disable_debugger,
print_dynamic_helper,
) | 1,022 |
logger = logging.getLogger("ioctl-hunter")
class KeysListenner(threading.Thread):
is_debugger_enabled = False
def __init__(self):
super(KeysListenner, self).__init__(daemon=True)
init(convert=True)
self.start()
def run(self):
while not msvcrt.kbhit():
time.sleep(0.1)
try:
while True:
result = None
if not msvcrt.kbhit():
time.sleep(0.1)
continue
result = msvcrt.getch().decode("utf-8")
if result and result in ["\n", "\r"] and not self.is_debugger_enabled:
|
logger = logging.getLogger("ioctl-hunter")
class KeysListenner(threading.Thread):
is_debugger_enabled = False
def __init__(self):
super(KeysListenner, self).__init__(daemon=True)
init(convert=True)
self.start()
def run(self):
while not msvcrt.kbhit():
time.sleep(0.1)
try:
while True:
result = None
if not msvcrt.kbhit():
time.sleep(0.1)
continue
result = msvcrt.getch().decode("utf-8")
if result and result in ["\n", "\r"] and not self.is_debugger_enabled: | print_enable_debugger() | 1 | 2023-10-31 22:38:36+00:00 | 2k |
masked-spacetime-hashing/msth | nerfstudio/process_data/process_data_utils.py | [
{
"identifier": "status",
"path": "nerfstudio/utils/rich_utils.py",
"snippet": "def status(msg: str, spinner: str = \"bouncingBall\", verbose: bool = False):\n \"\"\"A context manager that does nothing is verbose is True. Otherwise it hides logs under a message.\n\n Args:\n msg: The message... | import os
import shutil
import sys
import cv2
import numpy as np
from enum import Enum
from pathlib import Path
from typing import List, Optional, Tuple
from rich.console import Console
from typing_extensions import Literal, OrderedDict
from nerfstudio.utils.rich_utils import status
from nerfstudio.utils.scripts import run_command | 1,336 | # Copyright 2022 The Nerfstudio Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper utils for processing data into the nerfstudio format."""
CONSOLE = Console(width=120)
POLYCAM_UPSCALING_TIMES = 2
class CameraModel(Enum):
"""Enum for camera types."""
OPENCV = "OPENCV"
OPENCV_FISHEYE = "OPENCV_FISHEYE"
CAMERA_MODELS = {
"perspective": CameraModel.OPENCV,
"fisheye": CameraModel.OPENCV_FISHEYE,
"equirectangular": CameraModel.OPENCV,
}
def list_images(data: Path) -> List[Path]:
"""Lists all supported images in a directory
Args:
data: Path to the directory of images.
Returns:
Paths to images contained in the directory
"""
allowed_exts = [".jpg", ".jpeg", ".png", ".tif", ".tiff"]
image_paths = sorted([p for p in data.glob("[!.]*") if p.suffix.lower() in allowed_exts])
return image_paths
def get_image_filenames(directory: Path, max_num_images: int = -1) -> Tuple[List[Path], int]:
"""Returns a list of image filenames in a directory.
Args:
dir: Path to the directory.
max_num_images: The maximum number of images to return. -1 means no limit.
Returns:
A tuple of A list of image filenames, number of original image paths.
"""
image_paths = list_images(directory)
num_orig_images = len(image_paths)
if max_num_images != -1 and num_orig_images > max_num_images:
idx = np.round(np.linspace(0, num_orig_images - 1, max_num_images)).astype(int)
else:
idx = np.arange(num_orig_images)
image_filenames = list(np.array(image_paths)[idx])
return image_filenames, num_orig_images
def get_num_frames_in_video(video: Path) -> int:
"""Returns the number of frames in a video.
Args:
video: Path to a video.
Returns:
The number of frames in a video.
"""
cmd = f'ffprobe -v error -select_streams v:0 -count_packets \
-show_entries stream=nb_read_packets -of csv=p=0 "{video}"'
output = run_command(cmd)
assert output is not None
output = output.strip(" ,\t\n\r")
return int(output)
def convert_video_to_images(
video_path: Path,
image_dir: Path,
num_frames_target: int,
percent_crop: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0),
verbose: bool = False,
) -> Tuple[List[str], int]:
"""Converts a video into a sequence of images.
Args:
video_path: Path to the video.
output_dir: Path to the output directory.
num_frames_target: Number of frames to extract.
percent_crop: Percent of the image to crop. (top, bottom, left, right)
verbose: If True, logs the output of the command.
Returns:
A tuple containing summary of the conversion and the number of extracted frames.
"""
if video_path.is_dir():
CONSOLE.print(f"[bold red]Error: Video path is a directory, not a path: {video_path}")
sys.exit(1)
if video_path.exists() is False:
CONSOLE.print(f"[bold red]Error: Video does not exist: {video_path}")
sys.exit(1)
| # Copyright 2022 The Nerfstudio Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper utils for processing data into the nerfstudio format."""
CONSOLE = Console(width=120)
POLYCAM_UPSCALING_TIMES = 2
class CameraModel(Enum):
"""Enum for camera types."""
OPENCV = "OPENCV"
OPENCV_FISHEYE = "OPENCV_FISHEYE"
CAMERA_MODELS = {
"perspective": CameraModel.OPENCV,
"fisheye": CameraModel.OPENCV_FISHEYE,
"equirectangular": CameraModel.OPENCV,
}
def list_images(data: Path) -> List[Path]:
"""Lists all supported images in a directory
Args:
data: Path to the directory of images.
Returns:
Paths to images contained in the directory
"""
allowed_exts = [".jpg", ".jpeg", ".png", ".tif", ".tiff"]
image_paths = sorted([p for p in data.glob("[!.]*") if p.suffix.lower() in allowed_exts])
return image_paths
def get_image_filenames(directory: Path, max_num_images: int = -1) -> Tuple[List[Path], int]:
"""Returns a list of image filenames in a directory.
Args:
dir: Path to the directory.
max_num_images: The maximum number of images to return. -1 means no limit.
Returns:
A tuple of A list of image filenames, number of original image paths.
"""
image_paths = list_images(directory)
num_orig_images = len(image_paths)
if max_num_images != -1 and num_orig_images > max_num_images:
idx = np.round(np.linspace(0, num_orig_images - 1, max_num_images)).astype(int)
else:
idx = np.arange(num_orig_images)
image_filenames = list(np.array(image_paths)[idx])
return image_filenames, num_orig_images
def get_num_frames_in_video(video: Path) -> int:
"""Returns the number of frames in a video.
Args:
video: Path to a video.
Returns:
The number of frames in a video.
"""
cmd = f'ffprobe -v error -select_streams v:0 -count_packets \
-show_entries stream=nb_read_packets -of csv=p=0 "{video}"'
output = run_command(cmd)
assert output is not None
output = output.strip(" ,\t\n\r")
return int(output)
def convert_video_to_images(
video_path: Path,
image_dir: Path,
num_frames_target: int,
percent_crop: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0),
verbose: bool = False,
) -> Tuple[List[str], int]:
"""Converts a video into a sequence of images.
Args:
video_path: Path to the video.
output_dir: Path to the output directory.
num_frames_target: Number of frames to extract.
percent_crop: Percent of the image to crop. (top, bottom, left, right)
verbose: If True, logs the output of the command.
Returns:
A tuple containing summary of the conversion and the number of extracted frames.
"""
if video_path.is_dir():
CONSOLE.print(f"[bold red]Error: Video path is a directory, not a path: {video_path}")
sys.exit(1)
if video_path.exists() is False:
CONSOLE.print(f"[bold red]Error: Video does not exist: {video_path}")
sys.exit(1)
| with status(msg="Converting video to images...", spinner="bouncingBall", verbose=verbose): | 0 | 2023-10-26 04:39:15+00:00 | 2k |
sehyunkwon/ICTC | step2b.py | [
{
"identifier": "args",
"path": "utils/argument.py",
"snippet": "def str2bool(v):"
},
{
"identifier": "get_gpt_response",
"path": "utils/llm_utils.py",
"snippet": "def get_gpt_response(system_prompt, user_prompt, api_key, user, model):\n\n headers = {\n \"Content-Type\"... | import os
from dotenv import load_dotenv
from utils.argument import args
from utils.llm_utils import get_gpt_response, get_llama_response | 1,139 |
### Requires the file to be in the following format: "Image-file ... ; Answer: {label}"
def post_process():
answer_list = {}
# read line by line
with open(args.step2a_result_path, 'r') as answers:
answers = answers.readlines()
for answer in answers:
if "Image file-" in answer:
answer = answer.split(";")[1]
label = answer.split(" ")[1:]
real_label = ""
for lab in label:
real_label += lab + " "
real_label = real_label[:-1]
real_label = real_label.lower().strip().strip(".")
if 'answer: ' not in real_label:
real_label = 'answer: ' + real_label
if real_label not in answer_list:
answer_list[real_label] = 1
else:
answer_list[real_label] += 1
print('Full dictionary: ',answer_list)
print("Number of distinct labels: ", len(answer_list))
return answer_list
if __name__ == "__main__":
load_dotenv()
api_key = os.getenv("API_KEY")
user = os.getenv("USER")
model = os.getenv("MODEL")
url = ""
if args.llama_ver == "llama_70b":
url = os.getenv("LLAMA_70b_URL")
elif args.llama_ver == "llama_13b":
url = os.getenv("LLAMA_13b_URL")
elif args.llama_ver == "llama_7b":
url = os.getenv("LLAMA_7b_URL")
# post process gpt_labels.txt
answer_list = post_process()
answer_list = {k: v for k, v in answer_list.items() if v > 5}
print("Post-processed dictionary: ",answer_list)
# read system prompt
with open(args.step2b_prompt_path, 'r') as file:
system_prompt = file.read()
system_prompt = system_prompt.replace("[__NUM_CLASSES_CLUSTER__]", str(args.num_classes))
system_prompt = system_prompt.replace("[__LEN__]", str(len(answer_list)))
# print(system_prompt)
# feed into gpt.
user_prompt = f"list of labels: {answer_list}\n"
user_prompt += f"num_classes: {args.num_classes}"
if args.llama:
response = get_llama_response(system_prompt, user_prompt, url)
print(response)
else:
|
### Requires the file to be in the following format: "Image-file ... ; Answer: {label}"
def post_process():
answer_list = {}
# read line by line
with open(args.step2a_result_path, 'r') as answers:
answers = answers.readlines()
for answer in answers:
if "Image file-" in answer:
answer = answer.split(";")[1]
label = answer.split(" ")[1:]
real_label = ""
for lab in label:
real_label += lab + " "
real_label = real_label[:-1]
real_label = real_label.lower().strip().strip(".")
if 'answer: ' not in real_label:
real_label = 'answer: ' + real_label
if real_label not in answer_list:
answer_list[real_label] = 1
else:
answer_list[real_label] += 1
print('Full dictionary: ',answer_list)
print("Number of distinct labels: ", len(answer_list))
return answer_list
if __name__ == "__main__":
load_dotenv()
api_key = os.getenv("API_KEY")
user = os.getenv("USER")
model = os.getenv("MODEL")
url = ""
if args.llama_ver == "llama_70b":
url = os.getenv("LLAMA_70b_URL")
elif args.llama_ver == "llama_13b":
url = os.getenv("LLAMA_13b_URL")
elif args.llama_ver == "llama_7b":
url = os.getenv("LLAMA_7b_URL")
# post process gpt_labels.txt
answer_list = post_process()
answer_list = {k: v for k, v in answer_list.items() if v > 5}
print("Post-processed dictionary: ",answer_list)
# read system prompt
with open(args.step2b_prompt_path, 'r') as file:
system_prompt = file.read()
system_prompt = system_prompt.replace("[__NUM_CLASSES_CLUSTER__]", str(args.num_classes))
system_prompt = system_prompt.replace("[__LEN__]", str(len(answer_list)))
# print(system_prompt)
# feed into gpt.
user_prompt = f"list of labels: {answer_list}\n"
user_prompt += f"num_classes: {args.num_classes}"
if args.llama:
response = get_llama_response(system_prompt, user_prompt, url)
print(response)
else: | response = get_gpt_response(system_prompt, user_prompt, api_key, user, model) | 1 | 2023-10-27 05:00:14+00:00 | 2k |
phineas-pta/comfy-trt-test | comfy_trt/model_manager.py | [
{
"identifier": "ModelConfig",
"path": "comfy_trt/datastructures.py",
"snippet": "class ModelConfig:\n\tprofile: dict\n\tstatic_shapes: bool = False\n\tfp32: bool = False\n\tbaseline_model: str = \"SD15\" # save model info, for values see `comfy/supported_models.py`, breaking change incompatible A1111\... | import hashlib
import json
import os
import logging
import copy
import torch
from .datastructures import ModelConfig, ModelConfigEncoder | 1,538 | # -*- coding: utf-8 -*-
# modified from https://github.com/NVIDIA/Stable-Diffusion-WebUI-TensorRT/blob/main/model_manager.py
# CHANGE: retrieve checkpoint info from comfy
# STATUS: ok i guess
BASE_PATH = os.path.dirname(os.path.realpath(__file__))
ONNX_MODEL_DIR = os.path.join(BASE_PATH, "Unet-onnx")
if not os.path.exists(ONNX_MODEL_DIR):
os.makedirs(ONNX_MODEL_DIR)
TRT_MODEL_DIR = os.path.join(BASE_PATH, "Unet-trt")
if not os.path.exists(TRT_MODEL_DIR):
os.makedirs(TRT_MODEL_DIR)
MODEL_FILE = os.path.join(TRT_MODEL_DIR, "model.json")
def get_cc() -> tuple[int]:
res = torch.cuda.get_device_properties(int(os.getenv("CUDA_VISIBLE_DEVICES", 0)))
return res.major, res.minor
cc_major, cc_minor = get_cc()
class ModelManager:
def __init__(self, model_file: str = MODEL_FILE):
self.all_models = {}
self.model_file = model_file
self.cc = f"cc{cc_major}{cc_minor}"
if not os.path.exists(model_file):
logging.warning("Model file does not exist. Creating new one.")
else:
self.all_models = self.read_json()
self.update()
@staticmethod
def get_onnx_path(model_name: str) -> tuple[str]:
onnx_filename = f"{model_name}.onnx"
onnx_path = os.path.join(ONNX_MODEL_DIR, onnx_filename)
return onnx_filename, onnx_path
def get_trt_path(self, model_name: str, profile: dict, static_shape: bool) -> tuple[str]:
profile_hash = []
n_profiles = 1 if static_shape else 3
for k, v in profile.items():
dim_hash = []
for i in range(n_profiles):
dim_hash.append("x".join([str(x) for x in v[i]]))
profile_hash.append(k + "=" + "+".join(dim_hash))
# shorter hash coz windows file path length limit
hash_str = hashlib.blake2b("-".join(profile_hash).encode("utf-8"), digest_size=16).hexdigest() # 16 digest = 32 char (original >110 char)
trt_filename = model_name + "_" + hash_str + ".trt"
trt_path = os.path.join(TRT_MODEL_DIR, trt_filename)
return trt_filename, trt_path
def get_weights_map_path(self, model_name: str):
return os.path.join(TRT_MODEL_DIR, f"{model_name}_weights_map.json")
def update(self) -> None:
trt_engines = [trt_file for trt_file in os.listdir(TRT_MODEL_DIR) if trt_file.endswith(".trt")]
tmp_all_models = copy.deepcopy(self.all_models)
for cc, base_models in tmp_all_models.items():
for base_model, models in base_models.items():
tmp_config_list = {}
for model_config in models:
if model_config["filepath"] not in trt_engines:
logging.info(f"Model config outdated. {model_config['filepath']} was not found")
continue
tmp_config_list[model_config["filepath"]] = model_config
tmp_config_list = list(tmp_config_list.values())
if len(tmp_config_list) == 0:
self.all_models[cc].pop(base_model)
else:
self.all_models[cc][base_model] = models
self.write_json()
def add_entry(
self,
model_name: str,
profile: dict,
static_shapes: bool,
fp32: bool,
baseline_model: str,
prediction_type: str,
inpaint: bool,
refit: bool,
unet_hidden_dim: int,
lora: bool
) -> None:
| # -*- coding: utf-8 -*-
# modified from https://github.com/NVIDIA/Stable-Diffusion-WebUI-TensorRT/blob/main/model_manager.py
# CHANGE: retrieve checkpoint info from comfy
# STATUS: ok i guess
BASE_PATH = os.path.dirname(os.path.realpath(__file__))
ONNX_MODEL_DIR = os.path.join(BASE_PATH, "Unet-onnx")
if not os.path.exists(ONNX_MODEL_DIR):
os.makedirs(ONNX_MODEL_DIR)
TRT_MODEL_DIR = os.path.join(BASE_PATH, "Unet-trt")
if not os.path.exists(TRT_MODEL_DIR):
os.makedirs(TRT_MODEL_DIR)
MODEL_FILE = os.path.join(TRT_MODEL_DIR, "model.json")
def get_cc() -> tuple[int]:
res = torch.cuda.get_device_properties(int(os.getenv("CUDA_VISIBLE_DEVICES", 0)))
return res.major, res.minor
cc_major, cc_minor = get_cc()
class ModelManager:
def __init__(self, model_file: str = MODEL_FILE):
self.all_models = {}
self.model_file = model_file
self.cc = f"cc{cc_major}{cc_minor}"
if not os.path.exists(model_file):
logging.warning("Model file does not exist. Creating new one.")
else:
self.all_models = self.read_json()
self.update()
@staticmethod
def get_onnx_path(model_name: str) -> tuple[str]:
onnx_filename = f"{model_name}.onnx"
onnx_path = os.path.join(ONNX_MODEL_DIR, onnx_filename)
return onnx_filename, onnx_path
def get_trt_path(self, model_name: str, profile: dict, static_shape: bool) -> tuple[str]:
profile_hash = []
n_profiles = 1 if static_shape else 3
for k, v in profile.items():
dim_hash = []
for i in range(n_profiles):
dim_hash.append("x".join([str(x) for x in v[i]]))
profile_hash.append(k + "=" + "+".join(dim_hash))
# shorter hash coz windows file path length limit
hash_str = hashlib.blake2b("-".join(profile_hash).encode("utf-8"), digest_size=16).hexdigest() # 16 digest = 32 char (original >110 char)
trt_filename = model_name + "_" + hash_str + ".trt"
trt_path = os.path.join(TRT_MODEL_DIR, trt_filename)
return trt_filename, trt_path
def get_weights_map_path(self, model_name: str):
return os.path.join(TRT_MODEL_DIR, f"{model_name}_weights_map.json")
def update(self) -> None:
trt_engines = [trt_file for trt_file in os.listdir(TRT_MODEL_DIR) if trt_file.endswith(".trt")]
tmp_all_models = copy.deepcopy(self.all_models)
for cc, base_models in tmp_all_models.items():
for base_model, models in base_models.items():
tmp_config_list = {}
for model_config in models:
if model_config["filepath"] not in trt_engines:
logging.info(f"Model config outdated. {model_config['filepath']} was not found")
continue
tmp_config_list[model_config["filepath"]] = model_config
tmp_config_list = list(tmp_config_list.values())
if len(tmp_config_list) == 0:
self.all_models[cc].pop(base_model)
else:
self.all_models[cc][base_model] = models
self.write_json()
def add_entry(
self,
model_name: str,
profile: dict,
static_shapes: bool,
fp32: bool,
baseline_model: str,
prediction_type: str,
inpaint: bool,
refit: bool,
unet_hidden_dim: int,
lora: bool
) -> None: | config = ModelConfig(profile, static_shapes, fp32, baseline_model, prediction_type, inpaint, refit, lora, unet_hidden_dim) | 0 | 2023-10-25 23:58:12+00:00 | 2k |
hydrogram/hydrogram | hydrogram/raw/core/gzip_packed.py | [
{
"identifier": "Bytes",
"path": "hydrogram/raw/core/primitives/bytes.py",
"snippet": "class Bytes(bytes, TLObject):\n @classmethod\n def read(cls, data: BytesIO, *args: Any) -> bytes:\n length = int.from_bytes(data.read(1), \"little\")\n\n if length <= 253:\n x = data.rea... | from gzip import compress, decompress
from io import BytesIO
from typing import Any, cast
from .primitives.bytes import Bytes
from .primitives.int import Int
from .tl_object import TLObject | 1,159 | # Hydrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2023 Dan <https://github.com/delivrance>
# Copyright (C) 2023-present Hydrogram <https://hydrogram.org>
#
# This file is part of Hydrogram.
#
# Hydrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Hydrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
class GzipPacked(TLObject):
ID = 0x3072CFA1
__slots__ = ["packed_data"]
QUALNAME = "GzipPacked"
def __init__(self, packed_data: TLObject):
self.packed_data = packed_data
@staticmethod
def read(data: BytesIO, *args: Any) -> "GzipPacked":
# Return the Object itself instead of a GzipPacked wrapping it
| # Hydrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2023 Dan <https://github.com/delivrance>
# Copyright (C) 2023-present Hydrogram <https://hydrogram.org>
#
# This file is part of Hydrogram.
#
# Hydrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Hydrogram is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
class GzipPacked(TLObject):
ID = 0x3072CFA1
__slots__ = ["packed_data"]
QUALNAME = "GzipPacked"
def __init__(self, packed_data: TLObject):
self.packed_data = packed_data
@staticmethod
def read(data: BytesIO, *args: Any) -> "GzipPacked":
# Return the Object itself instead of a GzipPacked wrapping it | return cast(GzipPacked, TLObject.read(BytesIO(decompress(Bytes.read(data))))) | 0 | 2023-10-29 16:16:37+00:00 | 2k |
chenruduan/OAReactDiff | oa_reactdiff/tests/utils/test_graph_tools.py | [
{
"identifier": "get_edges_index",
"path": "oa_reactdiff/utils/_graph_tools.py",
"snippet": "def get_edges_index(\n combined_mask: Tensor,\n pos: Optional[Tensor] = None,\n edge_cutoff: Optional[float] = None,\n remove_self_edge: bool = False,\n) -> Tensor:\n r\"\"\"\n\n Args:\n ... | import unittest
import torch
from torch import Tensor, tensor
from oa_reactdiff.utils import (
get_edges_index,
get_subgraph_mask,
get_n_frag_switch,
get_mask_for_frag,
) | 1,138 |
class TestBasics(unittest.TestCase):
def test_get_mask_for_frag(self):
natms = Tensor([2, 0, 3]).long()
res = get_mask_for_frag(natms)
self.assertTrue(torch.allclose(res, Tensor([0, 0, 2, 2, 2]).long()))
def test_get_n_frag_switch(self):
natm_list = [tensor([2, 0]), tensor([1, 3]), tensor([3, 2])]
|
class TestBasics(unittest.TestCase):
def test_get_mask_for_frag(self):
natms = Tensor([2, 0, 3]).long()
res = get_mask_for_frag(natms)
self.assertTrue(torch.allclose(res, Tensor([0, 0, 2, 2, 2]).long()))
def test_get_n_frag_switch(self):
natm_list = [tensor([2, 0]), tensor([1, 3]), tensor([3, 2])] | res = get_n_frag_switch(natm_list) | 2 | 2023-10-30 02:53:38+00:00 | 2k |
lewandofskee/DiAD | ldm/models/diffusion/ddim.py | [
{
"identifier": "make_ddim_sampling_parameters",
"path": "ldm/modules/diffusionmodules/util.py",
"snippet": "def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):\n # select alphas for computing the variance schedule\n alphas = alphacums[ddim_timesteps]\n alphas_prev ... | import torch
import numpy as np
from tqdm import tqdm
from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor | 1,171 | """SAMPLING ONLY."""
class DDIMSampler(object):
def __init__(self, model, schedule="linear", **kwargs):
super().__init__()
self.model = model
self.ddpm_num_timesteps = model.num_timesteps
self.schedule = schedule
def register_buffer(self, name, attr):
if type(attr) == torch.Tensor:
if attr.device != torch.device("cuda"):
attr = attr.to(torch.device("cuda"))
setattr(self, name, attr)
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True,timesteps=1000):
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
alphas_cumprod = self.model.alphas_cumprod
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
self.register_buffer('betas', to_torch(self.model.betas))
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
# calculations for diffusion q(x_t | x_{t-1}) and others
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
# ddim sampling parameters
| """SAMPLING ONLY."""
class DDIMSampler(object):
def __init__(self, model, schedule="linear", **kwargs):
super().__init__()
self.model = model
self.ddpm_num_timesteps = model.num_timesteps
self.schedule = schedule
def register_buffer(self, name, attr):
if type(attr) == torch.Tensor:
if attr.device != torch.device("cuda"):
attr = attr.to(torch.device("cuda"))
setattr(self, name, attr)
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True,timesteps=1000):
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
alphas_cumprod = self.model.alphas_cumprod
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
self.register_buffer('betas', to_torch(self.model.betas))
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
# calculations for diffusion q(x_t | x_{t-1}) and others
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
# ddim sampling parameters | ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(), | 0 | 2023-10-30 14:21:09+00:00 | 2k |
nv-tlabs/trace | tbsim/models/temporal.py | [
{
"identifier": "SinusoidalPosEmb",
"path": "tbsim/models/trace_helpers.py",
"snippet": "class SinusoidalPosEmb(nn.Module):\n def __init__(self, dim):\n super().__init__()\n self.dim = dim\n\n def forward(self, x):\n device = x.device\n half_dim = self.dim // 2\n ... | import torch
import torch.nn as nn
import einops
from einops.layers.torch import Rearrange
from .trace_helpers import (
SinusoidalPosEmb,
Downsample1d,
Upsample1d,
Conv1dBlock,
) | 935 | #
# Based on Diffuser: https://github.com/jannerm/diffuser/blob/main/diffuser/models/temporal.py
#
class ResidualTemporalMapBlockConcat(nn.Module):
def __init__(self, inp_channels, out_channels, time_embed_dim, horizon, kernel_size=5):
super().__init__()
self.time_mlp = nn.Sequential(
nn.Mish(),
nn.Linear(time_embed_dim, out_channels),
Rearrange('batch t -> batch t 1'),
)
self.blocks = nn.ModuleList([
Conv1dBlock(inp_channels, out_channels, kernel_size),
Conv1dBlock(out_channels, out_channels, kernel_size),
])
self.residual_conv = nn.Conv1d(inp_channels, out_channels, 1) \
if inp_channels != out_channels else nn.Identity()
def forward(self, x, t):
'''
x : [ batch_size x inp_channels x horizon ]
t : [ batch_size x embed_dim ]
returns:
out : [ batch_size x out_channels x horizon ]
'''
out = self.blocks[0](x) + self.time_mlp(t)
out = self.blocks[1](out)
return out + self.residual_conv(x)
class TemporalMapUnet(nn.Module):
def __init__(
self,
horizon,
transition_dim,
cond_dim,
output_dim,
dim=32,
dim_mults=(1, 2, 4, 8),
):
super().__init__()
ResidualTemporalMapBlock = ResidualTemporalMapBlockConcat
dims = [transition_dim, *map(lambda m: dim * m, dim_mults)]
in_out = list(zip(dims[:-1], dims[1:]))
print(f'[ models/temporal ] Channel dimensions: {in_out}')
time_dim = dim
self.time_mlp = nn.Sequential(
| #
# Based on Diffuser: https://github.com/jannerm/diffuser/blob/main/diffuser/models/temporal.py
#
class ResidualTemporalMapBlockConcat(nn.Module):
def __init__(self, inp_channels, out_channels, time_embed_dim, horizon, kernel_size=5):
super().__init__()
self.time_mlp = nn.Sequential(
nn.Mish(),
nn.Linear(time_embed_dim, out_channels),
Rearrange('batch t -> batch t 1'),
)
self.blocks = nn.ModuleList([
Conv1dBlock(inp_channels, out_channels, kernel_size),
Conv1dBlock(out_channels, out_channels, kernel_size),
])
self.residual_conv = nn.Conv1d(inp_channels, out_channels, 1) \
if inp_channels != out_channels else nn.Identity()
def forward(self, x, t):
'''
x : [ batch_size x inp_channels x horizon ]
t : [ batch_size x embed_dim ]
returns:
out : [ batch_size x out_channels x horizon ]
'''
out = self.blocks[0](x) + self.time_mlp(t)
out = self.blocks[1](out)
return out + self.residual_conv(x)
class TemporalMapUnet(nn.Module):
def __init__(
self,
horizon,
transition_dim,
cond_dim,
output_dim,
dim=32,
dim_mults=(1, 2, 4, 8),
):
super().__init__()
ResidualTemporalMapBlock = ResidualTemporalMapBlockConcat
dims = [transition_dim, *map(lambda m: dim * m, dim_mults)]
in_out = list(zip(dims[:-1], dims[1:]))
print(f'[ models/temporal ] Channel dimensions: {in_out}')
time_dim = dim
self.time_mlp = nn.Sequential( | SinusoidalPosEmb(time_dim), | 0 | 2023-10-31 18:43:07+00:00 | 2k |
gydpku/PPTC | src/evaluate.py | [
{
"identifier": "api_doc",
"path": "src/api_doc.py",
"snippet": "class API(object):\n def __init__(self, name, parameters, description,\n parameter_description=\"\", composition_instruction=\"\", example=\"\", api_desc=\"\",\n type=\"\",\n implementatio... | from src import api_doc
from src import prompt_factor
from src import ppt_reader, utils
from pptx import Presentation
from src import pptx_check
from sacremoses import MosesTokenizer
from tqdm import tqdm
import mosestokenizer
import os | 1,181 |
def calc_token_cost(path):
text = open(path,'r').read()
tokenizer = MosesTokenizer()
tokens = tokenizer.tokenize(text)
return len(tokens)
def calc_acc(label_path, pred_path, instruction, additional_restrictions=[]):
pos_total, pos_correct, str_correct = 0,0,0
# position
splitted = instruction.split('##')
instruction, restrictions = splitted[0], splitted[1:]
restrictions += additional_restrictions
if len(restrictions) > 0:
pos_total = 1
pos_correct = 1
# try:
ppt = Presentation(pred_path)
for res in restrictions:
slide_id,A,B,rel = [x.strip(" ") for x in res.split(",")]
try:
slide = ppt.slides[int(slide_id)]
pos_correct *= pptx_check.check(slide, A, B, rel)
except:
print(res)
print(instruction)
pos_correct = 0
# string
|
def calc_token_cost(path):
text = open(path,'r').read()
tokenizer = MosesTokenizer()
tokens = tokenizer.tokenize(text)
return len(tokens)
def calc_acc(label_path, pred_path, instruction, additional_restrictions=[]):
pos_total, pos_correct, str_correct = 0,0,0
# position
splitted = instruction.split('##')
instruction, restrictions = splitted[0], splitted[1:]
restrictions += additional_restrictions
if len(restrictions) > 0:
pos_total = 1
pos_correct = 1
# try:
ppt = Presentation(pred_path)
for res in restrictions:
slide_id,A,B,rel = [x.strip(" ") for x in res.split(",")]
try:
slide = ppt.slides[int(slide_id)]
pos_correct *= pptx_check.check(slide, A, B, rel)
except:
print(res)
print(instruction)
pos_correct = 0
# string | label_string = ppt_reader.eval_get_contents(need_text=True, need_style=True, need_position=False,need_shape_list=None,ppt=Presentation(label_path)) | 2 | 2023-10-25 13:14:46+00:00 | 2k |
secarri/MipFlooding | mipflooding/image_processing.py | [
{
"identifier": "setup_logger",
"path": "mipflooding/logger.py",
"snippet": "def setup_logger(logger_name: str, abs_log_path: str) -> logging.Logger:\n \"\"\"Set up a logger with the specified name and log to the given absolute path, returning the logger instance.\"\"\"\n logger = logging.getLogge... | import logging
import math
import os
import time
from pathlib import Path
from typing import List, Optional
from PIL import Image
from .logger import setup_logger, terminate_loggers
from .file_utils import clear_log_file, get_output_directory, get_output_filename | 1,599 | # Default packages
# Third party packages
# From self package
def _open_image_inputs(color: str, alpha: str, logger: logging.Logger) -> List:
"""Open and return the color and alpha images as a list of Image objects."""
logger.info("--- Opening images in memory...")
if not color:
color = str(None)
if not alpha:
alpha = str(None)
color_map = None if not Path(color).exists() else Image.open(color)
alpha_mask = None if not Path(alpha).exists() else Image.open(alpha).convert('L')
if color_map:
logger.info(f"--- File disk size: {os.path.getsize(color) / float(1 << 20):,.2f} MB")
return [color_map, alpha_mask]
def _validate_inputs(color: Image, alpha_mask: Image, logger: logging.Logger,
input_texture_color_abs_path: str) -> str | Optional[None]:
if color is None or alpha_mask is None:
message = f"One or more inputs do not exist:\n\t-Color: {color}\n\t-Alpha: {alpha_mask}. Skipping..."
elif not _do_resolutions_match(color, alpha_mask, logger):
message = f"Inputs do not match in resolution for file: {input_texture_color_abs_path}. Skipping..."
elif not _is_power_of_two_image(color, logger):
message = f"Input is not a power of two image: {input_texture_color_abs_path}. Skipping..."
else:
message = None
return message
def _do_resolutions_match(color: Image, alpha: Image, logger: logging.Logger) -> bool:
"""Check if the resolutions of color and alpha images match."""
logger.info("--- Verifying that inputs resolutions do match ...")
return True if color.size == alpha.size else False
def _is_power_of_two_image(color: Image, logger: logging.Logger) -> bool:
"""Check if all dimensions of the input image are powers of two."""
logger.info("--- Verifying that inputs are power of two images ...")
for res in color.size:
if (res & (res - 1)) != 0:
return False
return True
def _get_mip_levels(image: Image, logger: logging.Logger) -> int:
"""Calculate the number of mip levels based on image size."""
logger.info("--- Calculating mip map levels...")
image_short_side = image.size[0] if image.size[0] < image.size[1] else image.size[1]
logger.info(f"--- Done. Miplevels: {round(math.log2(image_short_side))}")
return round(math.log2(image_short_side))
def _generate_background(image: Image, logger: logging.Logger) -> Image:
"""Generate a background image and returns the result Image object."""
logger.info("--- Generating background image and storing it in memory...")
average_image_color = image.resize((1, 1))
up_scaled_avg = average_image_color.resize(image.size, Image.NEAREST)
return up_scaled_avg
def _calculate_image_height(image_width: int, image: Image) -> int:
"""Calculate the height of the image based on the specified width."""
width_percent = (image_width / float(image.size[0]))
new_height = int((float(image.size[1]) * float(width_percent)))
return new_height
def _stack_mip_levels(average_bgr: str, miplevels: int, color: Image, origin_width: int, origin_height: int,
output_dir: str, logger: logging.Logger, resample: Image.Resampling = Image.BOX) -> None:
"""Stack Mipmap levels on a background Image with alpha integration to generate a single Image."""
stack = average_bgr
logger.info(f"--- Storing original resolution in memory: {origin_width, origin_height}")
logger.info(f"--- Beginning the stacking process. Please wait...")
for miplevel in range(miplevels):
width = 2 ** (miplevel + 1)
height = _calculate_image_height(width, color)
new_image = color.resize((width, height), resample)
to_stack = new_image.copy().resize((origin_width, origin_height), Image.NEAREST)
img_copy = stack.copy()
img_copy.paste(to_stack, (0, 0), to_stack)
stack = img_copy.copy()
logger.info(f"--- Saving stack to file: {output_dir}")
stack.save(output_dir)
logger.info(f"--- Output disk size: {os.path.getsize(output_dir) / float(1 << 20):,.2f} MB")
def _log_and_terminate(logger, message, level=logging.ERROR):
"""Log the given 'message' at the specified 'level' using the 'logger', and then terminate the logger."""
logger.log(level=level, msg=message)
terminate_loggers(logger)
def _make_logger_for_file(directory: str, filename: str) -> logging.Logger:
"""Constructs the full path to a log file, clears the existing log file, and sets up a logger."""
logs_directory = os.path.join(directory, "logs")
Path(logs_directory).mkdir(parents=True, exist_ok=True)
out_log_file = Path(os.path.join(logs_directory, f"{filename.split('.')[0]}.txt"))
clear_log_file(out_log_file)
| # Default packages
# Third party packages
# From self package
def _open_image_inputs(color: str, alpha: str, logger: logging.Logger) -> List:
"""Open and return the color and alpha images as a list of Image objects."""
logger.info("--- Opening images in memory...")
if not color:
color = str(None)
if not alpha:
alpha = str(None)
color_map = None if not Path(color).exists() else Image.open(color)
alpha_mask = None if not Path(alpha).exists() else Image.open(alpha).convert('L')
if color_map:
logger.info(f"--- File disk size: {os.path.getsize(color) / float(1 << 20):,.2f} MB")
return [color_map, alpha_mask]
def _validate_inputs(color: Image, alpha_mask: Image, logger: logging.Logger,
input_texture_color_abs_path: str) -> str | Optional[None]:
if color is None or alpha_mask is None:
message = f"One or more inputs do not exist:\n\t-Color: {color}\n\t-Alpha: {alpha_mask}. Skipping..."
elif not _do_resolutions_match(color, alpha_mask, logger):
message = f"Inputs do not match in resolution for file: {input_texture_color_abs_path}. Skipping..."
elif not _is_power_of_two_image(color, logger):
message = f"Input is not a power of two image: {input_texture_color_abs_path}. Skipping..."
else:
message = None
return message
def _do_resolutions_match(color: Image, alpha: Image, logger: logging.Logger) -> bool:
"""Check if the resolutions of color and alpha images match."""
logger.info("--- Verifying that inputs resolutions do match ...")
return True if color.size == alpha.size else False
def _is_power_of_two_image(color: Image, logger: logging.Logger) -> bool:
"""Check if all dimensions of the input image are powers of two."""
logger.info("--- Verifying that inputs are power of two images ...")
for res in color.size:
if (res & (res - 1)) != 0:
return False
return True
def _get_mip_levels(image: Image, logger: logging.Logger) -> int:
"""Calculate the number of mip levels based on image size."""
logger.info("--- Calculating mip map levels...")
image_short_side = image.size[0] if image.size[0] < image.size[1] else image.size[1]
logger.info(f"--- Done. Miplevels: {round(math.log2(image_short_side))}")
return round(math.log2(image_short_side))
def _generate_background(image: Image, logger: logging.Logger) -> Image:
"""Generate a background image and returns the result Image object."""
logger.info("--- Generating background image and storing it in memory...")
average_image_color = image.resize((1, 1))
up_scaled_avg = average_image_color.resize(image.size, Image.NEAREST)
return up_scaled_avg
def _calculate_image_height(image_width: int, image: Image) -> int:
"""Calculate the height of the image based on the specified width."""
width_percent = (image_width / float(image.size[0]))
new_height = int((float(image.size[1]) * float(width_percent)))
return new_height
def _stack_mip_levels(average_bgr: str, miplevels: int, color: Image, origin_width: int, origin_height: int,
output_dir: str, logger: logging.Logger, resample: Image.Resampling = Image.BOX) -> None:
"""Stack Mipmap levels on a background Image with alpha integration to generate a single Image."""
stack = average_bgr
logger.info(f"--- Storing original resolution in memory: {origin_width, origin_height}")
logger.info(f"--- Beginning the stacking process. Please wait...")
for miplevel in range(miplevels):
width = 2 ** (miplevel + 1)
height = _calculate_image_height(width, color)
new_image = color.resize((width, height), resample)
to_stack = new_image.copy().resize((origin_width, origin_height), Image.NEAREST)
img_copy = stack.copy()
img_copy.paste(to_stack, (0, 0), to_stack)
stack = img_copy.copy()
logger.info(f"--- Saving stack to file: {output_dir}")
stack.save(output_dir)
logger.info(f"--- Output disk size: {os.path.getsize(output_dir) / float(1 << 20):,.2f} MB")
def _log_and_terminate(logger, message, level=logging.ERROR):
"""Log the given 'message' at the specified 'level' using the 'logger', and then terminate the logger."""
logger.log(level=level, msg=message)
terminate_loggers(logger)
def _make_logger_for_file(directory: str, filename: str) -> logging.Logger:
"""Constructs the full path to a log file, clears the existing log file, and sets up a logger."""
logs_directory = os.path.join(directory, "logs")
Path(logs_directory).mkdir(parents=True, exist_ok=True)
out_log_file = Path(os.path.join(logs_directory, f"{filename.split('.')[0]}.txt"))
clear_log_file(out_log_file) | return setup_logger("mipmap_flooding", out_log_file.__str__()) | 0 | 2023-10-25 11:05:59+00:00 | 2k |
Lin-jun-xiang/chatgpt-line-bot | chatgpt_linebot/modules/horoscope.py | [
{
"identifier": "chat_completion",
"path": "chatgpt_linebot/modules/gpt.py",
"snippet": "def chat_completion(message: List[Dict]) -> str:\n \"\"\"Use OpenAI API via gpt4free providers\"\"\"\n try:\n response = g4f.ChatCompletion.create(\n model=g4f.models.default,\n me... | import json
import re
import requests
from bs4 import BeautifulSoup
from chatgpt_linebot.modules.gpt import chat_completion
from chatgpt_linebot.prompts import horoscope_template | 668 |
class Horoscope:
HOST = "https://www.cosmopolitan.com/tw/horoscopes/"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
error_msg = (
"Cannot get the horoscope, please try again.🥶\n"
"Or connect to developer: https://github.com/Lin-jun-xiang/chatgpt-line-bot/issues"
)
def __init__(self) -> None:
self.horoscope_urls = self.get_horoscope_urls()
def get_horoscope_urls(self) -> list:
"""Get all horoscope urls
Returns
-------
horoscope_urls (List[Dict]):
[
{'name': '天蠍座', 'url': 'https://www...'},
{'name': '獅子座', 'url': 'https://www...'},
...
]
"""
try:
response = requests.get(f"{self.HOST}weekly/", headers=self.headers)
soup = BeautifulSoup(response.content, 'html.parser')
# Find the script tag containing JSON data
script_tag = soup.find('script', {'id': 'json-ld'})
horoscope_urls = []
if not script_tag:
return
# Extract the text content of the script tag
script_content = script_tag.contents[0]
# Load the JSON data
json_data = json.loads(script_content)
# Extract the information for each zodiac sign
for item in json_data['itemListElement']:
name = item['name']
url = item['url']
horoscope_urls.append({"name": name, "url": url})
return horoscope_urls
except Exception as e:
print(e)
def _process_horoscope_response(self, content: str) -> str:
if not content:
return f"{self.error_msg}\nContent is None."
|
class Horoscope:
HOST = "https://www.cosmopolitan.com/tw/horoscopes/"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
error_msg = (
"Cannot get the horoscope, please try again.🥶\n"
"Or connect to developer: https://github.com/Lin-jun-xiang/chatgpt-line-bot/issues"
)
def __init__(self) -> None:
self.horoscope_urls = self.get_horoscope_urls()
def get_horoscope_urls(self) -> list:
"""Get all horoscope urls
Returns
-------
horoscope_urls (List[Dict]):
[
{'name': '天蠍座', 'url': 'https://www...'},
{'name': '獅子座', 'url': 'https://www...'},
...
]
"""
try:
response = requests.get(f"{self.HOST}weekly/", headers=self.headers)
soup = BeautifulSoup(response.content, 'html.parser')
# Find the script tag containing JSON data
script_tag = soup.find('script', {'id': 'json-ld'})
horoscope_urls = []
if not script_tag:
return
# Extract the text content of the script tag
script_content = script_tag.contents[0]
# Load the JSON data
json_data = json.loads(script_content)
# Extract the information for each zodiac sign
for item in json_data['itemListElement']:
name = item['name']
url = item['url']
horoscope_urls.append({"name": name, "url": url})
return horoscope_urls
except Exception as e:
print(e)
def _process_horoscope_response(self, content: str) -> str:
if not content:
return f"{self.error_msg}\nContent is None." | response = chat_completion( | 0 | 2023-10-24 09:01:13+00:00 | 2k |
nv-tlabs/pacer | pacer/env/tasks/vec_task_wrappers.py | [
{
"identifier": "VecTaskCPU",
"path": "pacer/env/tasks/vec_task.py",
"snippet": "class VecTaskCPU(VecTask):\n\n def __init__(self, task, rl_device, sync_frame_time=False, clip_observations=5.0):\n super().__init__(task, rl_device, clip_observations=clip_observations)\n self.sync_frame_t... | from gym import spaces
from pacer.env.tasks.vec_task import VecTaskCPU, VecTaskGPU, VecTaskPython
import numpy as np
import torch | 983 | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
class VecTaskCPUWrapper(VecTaskCPU):
def __init__(self, task, rl_device, sync_frame_time=False, clip_observations=5.0):
super().__init__(task, rl_device, sync_frame_time, clip_observations)
return
| # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
class VecTaskCPUWrapper(VecTaskCPU):
def __init__(self, task, rl_device, sync_frame_time=False, clip_observations=5.0):
super().__init__(task, rl_device, sync_frame_time, clip_observations)
return
| class VecTaskGPUWrapper(VecTaskGPU): | 1 | 2023-10-31 20:47:12+00:00 | 2k |
Improbable-AI/dexenv | dexenv/models/state_model.py | [
{
"identifier": "DiagGaussianPolicy",
"path": "dexenv/models/diag_gaussian_pol/diag_gaussian_policy.py",
"snippet": "class DiagGaussianPolicy(nn.Module):\n def __init__(self,\n body_net,\n action_dim,\n init_log_std=-0.2,\n std_cond_in=F... | import gym
import torch.nn as nn
from collections.abc import Sequence
from loguru import logger
from dexenv.models.diag_gaussian_pol.diag_gaussian_policy import \
DiagGaussianPolicy
from dexenv.models.utils import get_activation
from dexenv.models.value_nets.value_net import ValueNet | 1,138 |
class SimpleMLP(nn.Module):
def __init__(self, in_dim, out_dim, act):
super().__init__()
act = get_activation(act)
self.body = nn.Sequential(
nn.Linear(in_dim, 512),
act(),
nn.Linear(512, 256),
act(),
nn.Linear(256, out_dim),
act(),
)
def forward(self, x):
if isinstance(x, dict):
# assert len(x) == 1
x = list(x.values())[0]
out = self.body(x)
return out
def get_mlp_critic(ob_size, act='gelu'):
logger.info(f'Critic state input size:{ob_size}')
critic_body = SimpleMLP(in_dim=ob_size, out_dim=256, act=act)
|
class SimpleMLP(nn.Module):
def __init__(self, in_dim, out_dim, act):
super().__init__()
act = get_activation(act)
self.body = nn.Sequential(
nn.Linear(in_dim, 512),
act(),
nn.Linear(512, 256),
act(),
nn.Linear(256, out_dim),
act(),
)
def forward(self, x):
if isinstance(x, dict):
# assert len(x) == 1
x = list(x.values())[0]
out = self.body(x)
return out
def get_mlp_critic(ob_size, act='gelu'):
logger.info(f'Critic state input size:{ob_size}')
critic_body = SimpleMLP(in_dim=ob_size, out_dim=256, act=act) | critic = ValueNet(critic_body, | 2 | 2023-10-25 17:22:41+00:00 | 2k |
ai-safety-foundation/sparse_autoencoder | sparse_autoencoder/autoencoder/components/tests/test_tied_bias.py | [
{
"identifier": "TiedBias",
"path": "sparse_autoencoder/autoencoder/components/tied_bias.py",
"snippet": "class TiedBias(Module):\n \"\"\"Tied Bias Layer.\n\n The tied pre-encoder bias is a learned bias term that is subtracted from the input before\n encoding, and added back after decoding.\n\n... | from jaxtyping import Float
from torch import Tensor
from torch.nn import Parameter
from sparse_autoencoder.autoencoder.components.tied_bias import TiedBias, TiedBiasPosition
from sparse_autoencoder.tensor_types import Axis
import torch | 1,467 | """Tied Bias Tests."""
def test_pre_encoder_subtracts_bias() -> None:
"""Check that the pre-encoder bias subtracts the bias."""
encoder_input: Float[Tensor, Axis.names(Axis.BATCH, Axis.INPUT_OUTPUT_FEATURE)] = torch.tensor(
[[5.0, 3.0, 1.0]]
)
bias = Parameter(torch.tensor([2.0, 4.0, 6.0]))
expected = encoder_input - bias
| """Tied Bias Tests."""
def test_pre_encoder_subtracts_bias() -> None:
"""Check that the pre-encoder bias subtracts the bias."""
encoder_input: Float[Tensor, Axis.names(Axis.BATCH, Axis.INPUT_OUTPUT_FEATURE)] = torch.tensor(
[[5.0, 3.0, 1.0]]
)
bias = Parameter(torch.tensor([2.0, 4.0, 6.0]))
expected = encoder_input - bias
| pre_encoder = TiedBias(bias, TiedBiasPosition.PRE_ENCODER) | 0 | 2023-10-27 07:37:15+00:00 | 2k |
vb000/SemanticHearing | src/training/train.py | [
{
"identifier": "utils",
"path": "src/helpers/utils.py",
"snippet": "class Params():\n def __init__(self, json_path):\n def save(self, json_path):\n def update(self, json_path):\n def dict(self):\ndef save_graph(train_metrics, test_metrics, save_dir):\ndef import_attr(import_path):\ndef set_... | import argparse
import multiprocessing
import os
import logging
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import traceback # pylint: disable=import-outside-toplevel
import wandb
from pathlib import Path
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm # pylint: disable=unused-import
from torchmetrics.functional import(
scale_invariant_signal_noise_ratio as si_snr,
signal_noise_ratio as snr,
signal_distortion_ratio as sdr,
scale_invariant_signal_distortion_ratio as si_sdr)
from src.helpers import utils
from src.training.eval import test_epoch | 1,165 | """
The main training script for training on synthetic data
"""
def train_epoch(model: nn.Module, device: torch.device,
optimizer: optim.Optimizer,
| """
The main training script for training on synthetic data
"""
def train_epoch(model: nn.Module, device: torch.device,
optimizer: optim.Optimizer, | train_loader: torch.utils.data.dataloader.DataLoader, | 0 | 2023-10-30 05:36:07+00:00 | 2k |
openai/bugbounty-gpt | tests/test_openai_classification.py | [
{
"identifier": "OpenAIHandler",
"path": "bugbounty_gpt/handlers/openai_handler.py",
"snippet": "class OpenAIHandler:\n @staticmethod\n def _classifications_sanitization(input_string):\n \"\"\"\n Sanitizes the input string by removing spaces, converting to upper case, and replacing s... | from bugbounty_gpt.handlers.openai_handler import OpenAIHandler
from unittest.mock import patch, AsyncMock
from bugbounty_gpt.env import OPENAI_PROMPT, OPENAI_MODEL, DEFAULT_CATEGORY
import pytest, asyncio | 915 |
def test_classifications_sanitization():
assert OpenAIHandler._classifications_sanitization(" Test Category ") == "TEST_CATEGORY"
def test_build_request_data():
submission_content = "Sample content"
expected_data = {
"model": OPENAI_MODEL,
"temperature": 0,
"max_tokens": 512,
"messages": [
|
def test_classifications_sanitization():
assert OpenAIHandler._classifications_sanitization(" Test Category ") == "TEST_CATEGORY"
def test_build_request_data():
submission_content = "Sample content"
expected_data = {
"model": OPENAI_MODEL,
"temperature": 0,
"max_tokens": 512,
"messages": [ | {"role": "system", "content": OPENAI_PROMPT}, | 1 | 2023-10-27 22:41:24+00:00 | 2k |
LeapLabTHU/FamO2O | jax_cql/JaxCQL/sac.py | [
{
"identifier": "next_rng",
"path": "jax_cql/JaxCQL/jax_utils.py",
"snippet": "def next_rng(*args, **kwargs):\n global jax_utils_rng\n return jax_utils_rng(*args, **kwargs)"
},
{
"identifier": "value_and_multi_grad",
"path": "jax_cql/JaxCQL/jax_utils.py",
"snippet": "def value_and_... | from collections import OrderedDict
from copy import deepcopy
from functools import partial
from ml_collections import ConfigDict
from flax.training.train_state import TrainState
from .jax_utils import (
next_rng, value_and_multi_grad, mse_loss, JaxRNG, wrap_function_with_rng,
collect_jax_metrics
)
from .model import Scalar, update_target_network
import numpy as np
import jax
import jax.numpy as jnp
import flax
import flax.linen as nn
import optax
import distrax | 1,576 |
class SAC(object):
@staticmethod
def get_default_config(updates=None):
config = ConfigDict()
config.discount = 0.99
config.alpha_multiplier = 1.0
config.use_automatic_entropy_tuning = True
config.backup_entropy = False
config.target_entropy = 0.0
config.policy_lr = 3e-4
config.qf_lr = 3e-4
config.optimizer_type = 'adam'
config.soft_target_update_rate = 5e-3
if updates is not None:
config.update(ConfigDict(updates).copy_and_resolve_references())
return config
def __init__(self, config, policy, qf):
self.config = self.get_default_config(config)
self.policy = policy
self.qf = qf
self.observation_dim = policy.observation_dim
self.action_dim = policy.action_dim
self._train_states = {}
optimizer_class = {
'adam': optax.adam,
'sgd': optax.sgd,
}[self.config.optimizer_type]
policy_params = self.policy.init(
next_rng(self.policy.rng_keys()),
jnp.zeros((10, self.observation_dim))
)
self._train_states['policy'] = TrainState.create(
params=policy_params,
tx=optimizer_class(self.config.policy_lr),
apply_fn=None
)
qf1_params = self.qf.init(
next_rng(self.qf.rng_keys()),
jnp.zeros((10, self.observation_dim)),
jnp.zeros((10, self.action_dim))
)
self._train_states['qf1'] = TrainState.create(
params=qf1_params,
tx=optimizer_class(self.config.qf_lr),
apply_fn=None,
)
qf2_params = self.qf.init(
next_rng(self.qf.rng_keys()),
jnp.zeros((10, self.observation_dim)),
jnp.zeros((10, self.action_dim))
)
self._train_states['qf2'] = TrainState.create(
params=qf2_params,
tx=optimizer_class(self.config.qf_lr),
apply_fn=None,
)
self._target_qf_params = deepcopy({'qf1': qf1_params, 'qf2': qf2_params})
model_keys = ['policy', 'qf1', 'qf2']
if self.config.use_automatic_entropy_tuning:
|
class SAC(object):
@staticmethod
def get_default_config(updates=None):
config = ConfigDict()
config.discount = 0.99
config.alpha_multiplier = 1.0
config.use_automatic_entropy_tuning = True
config.backup_entropy = False
config.target_entropy = 0.0
config.policy_lr = 3e-4
config.qf_lr = 3e-4
config.optimizer_type = 'adam'
config.soft_target_update_rate = 5e-3
if updates is not None:
config.update(ConfigDict(updates).copy_and_resolve_references())
return config
def __init__(self, config, policy, qf):
self.config = self.get_default_config(config)
self.policy = policy
self.qf = qf
self.observation_dim = policy.observation_dim
self.action_dim = policy.action_dim
self._train_states = {}
optimizer_class = {
'adam': optax.adam,
'sgd': optax.sgd,
}[self.config.optimizer_type]
policy_params = self.policy.init(
next_rng(self.policy.rng_keys()),
jnp.zeros((10, self.observation_dim))
)
self._train_states['policy'] = TrainState.create(
params=policy_params,
tx=optimizer_class(self.config.policy_lr),
apply_fn=None
)
qf1_params = self.qf.init(
next_rng(self.qf.rng_keys()),
jnp.zeros((10, self.observation_dim)),
jnp.zeros((10, self.action_dim))
)
self._train_states['qf1'] = TrainState.create(
params=qf1_params,
tx=optimizer_class(self.config.qf_lr),
apply_fn=None,
)
qf2_params = self.qf.init(
next_rng(self.qf.rng_keys()),
jnp.zeros((10, self.observation_dim)),
jnp.zeros((10, self.action_dim))
)
self._train_states['qf2'] = TrainState.create(
params=qf2_params,
tx=optimizer_class(self.config.qf_lr),
apply_fn=None,
)
self._target_qf_params = deepcopy({'qf1': qf1_params, 'qf2': qf2_params})
model_keys = ['policy', 'qf1', 'qf2']
if self.config.use_automatic_entropy_tuning: | self.log_alpha = Scalar(0.0) | 6 | 2023-10-25 11:53:25+00:00 | 2k |
RenShuhuai-Andy/TESTA | data/pretrain_dataset.py | [
{
"identifier": "pre_caption",
"path": "data/utils.py",
"snippet": "def pre_caption(caption, max_words=50):\n caption = re.sub(\n r\"([!\\\"()*#~])\", #r\"([!\\\"()*#:;~])\" #r\"([.!\\\"()*#:;~])\",\n ' ',\n caption.lower(),\n )\n caption = re.sub(\n r\"\\s{2,}\",\n... | import json
import os
import random
import torch
import torch
import numpy as np
import decord
import os,glob
from pandas import Categorical
from torch.utils.data import Dataset
from PIL import Image
from PIL import ImageFile
from decord import VideoReader
from data.utils import pre_caption
from .randaugment import TemporalConsistentRandomAugment | 1,012 |
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None
decord.bridge.set_bridge('torch')
class pretrain_dataset(Dataset):
def __init__(self, ann_file, laion_path, transform):
self.ann_pretrain = []
for f in ann_file:
print('loading '+f)
ann = json.load(open(f,'r'))
self.ann_pretrain += ann
self.laion_path = laion_path
if self.laion_path:
self.laion_files = glob.glob(os.path.join(laion_path,'*.json'))
print('loading '+self.laion_files[0])
with open(self.laion_files[0],'r') as f:
self.ann_laion = json.load(f)
self.annotation = self.ann_pretrain + self.ann_laion
else:
self.annotation = self.ann_pretrain
self.transform = transform
def reload_laion(self, epoch):
n = epoch%len(self.laion_files)
print('loading '+self.laion_files[n])
with open(self.laion_files[n],'r') as f:
self.ann_laion = json.load(f)
self.annotation = self.ann_pretrain + self.ann_laion
def __len__(self):
return len(self.annotation)
def __getitem__(self, index):
ann = self.annotation[index]
image = Image.open(ann['image']).convert('RGB')
image = self.transform(image)
|
ImageFile.LOAD_TRUNCATED_IMAGES = True
Image.MAX_IMAGE_PIXELS = None
decord.bridge.set_bridge('torch')
class pretrain_dataset(Dataset):
def __init__(self, ann_file, laion_path, transform):
self.ann_pretrain = []
for f in ann_file:
print('loading '+f)
ann = json.load(open(f,'r'))
self.ann_pretrain += ann
self.laion_path = laion_path
if self.laion_path:
self.laion_files = glob.glob(os.path.join(laion_path,'*.json'))
print('loading '+self.laion_files[0])
with open(self.laion_files[0],'r') as f:
self.ann_laion = json.load(f)
self.annotation = self.ann_pretrain + self.ann_laion
else:
self.annotation = self.ann_pretrain
self.transform = transform
def reload_laion(self, epoch):
n = epoch%len(self.laion_files)
print('loading '+self.laion_files[n])
with open(self.laion_files[n],'r') as f:
self.ann_laion = json.load(f)
self.annotation = self.ann_pretrain + self.ann_laion
def __len__(self):
return len(self.annotation)
def __getitem__(self, index):
ann = self.annotation[index]
image = Image.open(ann['image']).convert('RGB')
image = self.transform(image) | caption = pre_caption(ann['caption'],30) | 0 | 2023-10-29 12:09:38+00:00 | 2k |
flbraun/poe-palette | data/beasts.py | [
{
"identifier": "League",
"path": "data/leagues.py",
"snippet": "class League:\n type_: LeagueType\n title: str # e.g. \"Ancestor\"\n slug: str # e.g. \"ancestor\"\n is_hardcore: bool"
},
{
"identifier": "get_ninja_index",
"path": "data/ninja.py",
"snippet": "@functools.cac... | from collections.abc import Generator
from .leagues import League
from .ninja import get_ninja_index, make_ninja_url
from .trade import make_trade_url
from .types import NinjaCategory
from .utils import Entry, make_wiki_url | 1,262 |
def get_beasts(league: League) -> Generator[Entry, None, None]:
index = get_ninja_index(league)
for beast in index.raw[NinjaCategory.BEASTS]:
yield Entry(
display_text=beast,
wiki_url=make_wiki_url(beast),
ninja_url=make_ninja_url(league, beast, None, NinjaCategory.BEASTS),
|
def get_beasts(league: League) -> Generator[Entry, None, None]:
index = get_ninja_index(league)
for beast in index.raw[NinjaCategory.BEASTS]:
yield Entry(
display_text=beast,
wiki_url=make_wiki_url(beast),
ninja_url=make_ninja_url(league, beast, None, NinjaCategory.BEASTS), | trade_url=make_trade_url(league, beast), | 3 | 2023-10-27 11:33:43+00:00 | 2k |
ATR-DBI/CityRefer | models/cityrefer.py | [
{
"identifier": "SparseConvEncoder",
"path": "models/basic_blocks.py",
"snippet": "class SparseConvEncoder(nn.Module):\n def __init__(self, input_dim):\n super().__init__()\n\n self.stem = nn.Sequential(\n BasicConvolutionBlock(input_dim, 32, 3)\n )\n\n self.sta... | import sys
import os
import importlib
import models
import torch
import torch.nn as nn
import torchsparse.nn as spnn
from torch.nn.utils.rnn import pad_sequence
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from torchsparse.utils.collate import sparse_collate
from transformers import BertConfig
from models.basic_blocks import SparseConvEncoder
from models.landlang_module import LandLangModule | 1,357 |
importlib.reload(models)
sys.path.append(os.path.join(os.getcwd(), "lib")) # HACK add the lib folder
sys.path.append(os.path.join(os.getcwd(), "models")) # HACK add the lib folder
class CityRefer(nn.Module):
def __init__(self, args, input_feature_dim=0, num_object_class=None, vocab_size=None, pad_token_id=0):
super().__init__()
self.args = args
self.input_feature_dim = input_feature_dim
self.num_object_class = num_object_class
self.drop_rate = args.drop_rate
self.use_lang_classifier=(not args.no_lang_cls),
hidden_size = args.hidden_size
# --------- Language Encoder ---------
embed_dim = hidden_size
self.word_embeddings = nn.Embedding(vocab_size, embed_dim, padding_idx=pad_token_id) #, **factory_kwargs)
self.lang_gru = nn.GRU(
input_size=hidden_size,
hidden_size=hidden_size,
num_layers=args.num_hidden_layers,
batch_first=True,
bidirectional=True,
)
# --------- Point Encoder ---------
# Sparse Volumetric Backbone
|
importlib.reload(models)
sys.path.append(os.path.join(os.getcwd(), "lib")) # HACK add the lib folder
sys.path.append(os.path.join(os.getcwd(), "models")) # HACK add the lib folder
class CityRefer(nn.Module):
def __init__(self, args, input_feature_dim=0, num_object_class=None, vocab_size=None, pad_token_id=0):
super().__init__()
self.args = args
self.input_feature_dim = input_feature_dim
self.num_object_class = num_object_class
self.drop_rate = args.drop_rate
self.use_lang_classifier=(not args.no_lang_cls),
hidden_size = args.hidden_size
# --------- Language Encoder ---------
embed_dim = hidden_size
self.word_embeddings = nn.Embedding(vocab_size, embed_dim, padding_idx=pad_token_id) #, **factory_kwargs)
self.lang_gru = nn.GRU(
input_size=hidden_size,
hidden_size=hidden_size,
num_layers=args.num_hidden_layers,
batch_first=True,
bidirectional=True,
)
# --------- Point Encoder ---------
# Sparse Volumetric Backbone | self.sparse_conv = SparseConvEncoder(self.input_feature_dim) # self.input_feature_dim = 3 -> 128 | 0 | 2023-10-25 10:02:28+00:00 | 2k |
OATML-Markslab/ProteinNPT | baselines/data_processing.py | [
{
"identifier": "slice_sequences",
"path": "utils/data_utils.py",
"snippet": "def slice_sequences(list_mutant_mutated_seq_pairs, max_positions=1024, method=\"rolling\", rolling_overlap=100, eval_mode=True, batch_target_labels=None, batch_masked_targets=None, target_names=None, start_idx=1, num_extra_tok... | import sys
import numpy as np
import h5py
import torch
from collections import defaultdict
from utils.data_utils import slice_sequences, get_indices_retrieved_embeddings
from utils.msa_utils import weighted_sample_MSA | 1,219 |
def process_batch(batch, model, alphabet, args, device, MSA_sequences=None, MSA_weights=None, MSA_start_position=None, MSA_end_position=None, eval_mode = True, indel_mode=False, start_idx=1):
"""
start_idx is the one-indexed postion of the first residue in the sequence. If full sequence is passed (as always assumed in this codebase) this is equal to 1.
"""
target_names = args.target_config.keys()
raw_sequence_length = len(batch['mutant_mutated_seq_pairs'][0][1])
raw_batch_size = len(batch['mutant_mutated_seq_pairs'])
if args.sequence_embeddings_location is not None and args.aa_embeddings!="One_hot_encoding":
try:
|
def process_batch(batch, model, alphabet, args, device, MSA_sequences=None, MSA_weights=None, MSA_start_position=None, MSA_end_position=None, eval_mode = True, indel_mode=False, start_idx=1):
"""
start_idx is the one-indexed postion of the first residue in the sequence. If full sequence is passed (as always assumed in this codebase) this is equal to 1.
"""
target_names = args.target_config.keys()
raw_sequence_length = len(batch['mutant_mutated_seq_pairs'][0][1])
raw_batch_size = len(batch['mutant_mutated_seq_pairs'])
if args.sequence_embeddings_location is not None and args.aa_embeddings!="One_hot_encoding":
try: | indices_retrieved_embeddings = get_indices_retrieved_embeddings(batch,args.sequence_embeddings_location) | 1 | 2023-10-28 11:41:05+00:00 | 2k |
dyhBUPT/iKUN | test.py | [
{
"identifier": "opt",
"path": "opts.py",
"snippet": "class opts:\n def __init__(self):\n def parse(self, args=''):"
},
{
"identifier": "get_model",
"path": "model.py",
"snippet": "def get_model(opt, name='Model'):\n model = eval(name)(opt)\n model.cuda()\n model = nn.Data... | import os
import json
import shutil
import numpy as np
import torch
import torch.nn.functional as F
import warnings
from tqdm import tqdm
from os.path import join, exists
from collections import defaultdict
from torch import nn
from torchvision.utils import save_image
from opts import opt
from utils import *
from model import get_model
from dataloader import get_dataloader, get_transform
from similarity_calibration import similarity_calibration | 916 |
warnings.filterwarnings('ignore')
# import `opts` first to set gpus
def test_accuracy_v1(model, dataloader, save_img=False):
model.eval()
TP, FP, FN = 0, 0, 0
assert dataloader.batch_size == 1
if save_img:
save_dir = join(opt.save_dir, 'images')
os.makedirs(save_dir, exist_ok=True)
global_idx = 1
|
warnings.filterwarnings('ignore')
# import `opts` first to set gpus
def test_accuracy_v1(model, dataloader, save_img=False):
model.eval()
TP, FP, FN = 0, 0, 0
assert dataloader.batch_size == 1
if save_img:
save_dir = join(opt.save_dir, 'images')
os.makedirs(save_dir, exist_ok=True)
global_idx = 1 | un_norm = get_transform('unnorm', opt, -1) | 3 | 2023-10-31 07:08:37+00:00 | 2k |
CVHub520/yolov5_obb | utils/augmentations.py | [
{
"identifier": "LOGGER",
"path": "utils/general.py",
"snippet": "LOGGER = set_logging(__name__) # define globally (used in train.py, val.py, detect.py, etc.)"
},
{
"identifier": "check_version",
"path": "utils/general.py",
"snippet": "def check_version(current='0.0.0', minimum='0.0.0',... | import math
import random
import cv2
import numpy as np
import albumentations as A
from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box
from utils.metrics import bbox_ioa
from utils.rboxs_utils import poly_filter | 1,519 | # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Image augmentation functions
"""
class Albumentations:
# YOLOv5 Albumentations class (optional, only used if package is installed)
def __init__(self):
self.transform = None
try:
| # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Image augmentation functions
"""
class Albumentations:
# YOLOv5 Albumentations class (optional, only used if package is installed)
def __init__(self):
self.transform = None
try: | check_version(A.__version__, '1.0.3', hard=True) # version requirement | 1 | 2023-10-31 06:06:41+00:00 | 2k |
hyw-dev/AFI-ForwardDeduplicate | models/gmflow/matching.py | [
{
"identifier": "coords_grid",
"path": "models/gmflow/geometry.py",
"snippet": "def coords_grid(b, h, w, homogeneous=False, device=None, dtype: torch.dtype=torch.float32):\r\n k = (str(device), str((b, h, w)))\r\n if k in coords_grid_cache:\r\n return coords_grid_cache[k]\r\n y, x = torc... | import torch
import torch.nn.functional as F
from models.gmflow.geometry import coords_grid, generate_window_grid, normalize_coords
| 767 |
def global_correlation_softmax(feature0, feature1,
pred_bidir_flow=False,
):
# global correlation
b, c, h, w = feature0.shape
feature0 = feature0.view(b, c, -1).permute(0, 2, 1) # [B, H*W, C]
feature1 = feature1.view(b, c, -1) # [B, C, H*W]
correlation = torch.matmul(feature0, feature1).view(b, h, w, h, w) / (c ** 0.5) # [B, H, W, H, W]
# flow from softmax
|
def global_correlation_softmax(feature0, feature1,
pred_bidir_flow=False,
):
# global correlation
b, c, h, w = feature0.shape
feature0 = feature0.view(b, c, -1).permute(0, 2, 1) # [B, H*W, C]
feature1 = feature1.view(b, c, -1) # [B, C, H*W]
correlation = torch.matmul(feature0, feature1).view(b, h, w, h, w) / (c ** 0.5) # [B, H, W, H, W]
# flow from softmax
| init_grid = coords_grid(b, h, w, device=correlation.device, dtype=feature0.dtype) # [B, 2, H, W]
| 0 | 2023-10-29 18:25:36+00:00 | 2k |
bmrussell/LGBattery | device.py | [
{
"identifier": "Shared",
"path": "globals.py",
"snippet": "class Shared:\n \"\"\"_Configuration_\n\n Args:\n Singleton class for application configuration\n \"\"\"\n\n appname = 'lgbattery'\n quit_selected = False\n datadir = f'{os.getenv(\"APPDATA\")}\\\\{app... | import asyncio
import json
import logging
import websockets
from globals import Shared
from icons import get_icon | 1,575 |
def get_device_by_id(id):
for dev in Shared.devices:
if dev.id == id:
return dev
return None
class Device:
def __init__(self, id, unitId, name, batteryLevel, charging):
self.id = id
self.unitId = unitId
self.name = name
self.batteryLevel = batteryLevel
self.charging = charging
def __repr__(self):
return f"<Device(id:{self.id} unitId:{self.unitId} name:{self.name} batteryLevel:{self.batteryLevel} charging:{self.charging})>"
def __str__(self):
return f"Device(id:{self.id} unitId:{self.unitId} name:{self.name} batteryLevel:{self.batteryLevel} charging:{self.charging})>"
async def get_battery(self):
level = None
charging = False
headers = {'Origin': 'file://',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
'Sec-WebSocket-Protocol': 'json'}
battery_request = {
'msgId': '',
'verb': 'GET',
'path': f'/battery/{self.id}/state'
}
async with websockets.connect(uri="ws://localhost:9010",
extra_headers=headers,
subprotocols=['json'],
) as websocket:
while True:
request = json.dumps(battery_request)
await websocket.send(request)
response = await websocket.recv()
message = json.loads(response)
Shared.logger.info(f'Received: {message}')
if message['path'] == f'/battery/{self.id}/state':
self.batteryLevel = message['payload']['percentage']
self.charging = (message['payload']['charging'] == True)
break
def select(self, tray):
logger = logging.getLogger(Shared.appname)
logger.info(f'Device.SELECT: Selected {self.id} {self.name}')
Shared.selected_device = self
Shared.selected_device_name = self.name
asyncio.run(self.get_battery())
if self.charging:
tooltip = f'{self.name}: {self.batteryLevel}% (charging)'
else:
tooltip = f'{self.name}: {str(self.batteryLevel)}%'
|
def get_device_by_id(id):
for dev in Shared.devices:
if dev.id == id:
return dev
return None
class Device:
def __init__(self, id, unitId, name, batteryLevel, charging):
self.id = id
self.unitId = unitId
self.name = name
self.batteryLevel = batteryLevel
self.charging = charging
def __repr__(self):
return f"<Device(id:{self.id} unitId:{self.unitId} name:{self.name} batteryLevel:{self.batteryLevel} charging:{self.charging})>"
def __str__(self):
return f"Device(id:{self.id} unitId:{self.unitId} name:{self.name} batteryLevel:{self.batteryLevel} charging:{self.charging})>"
async def get_battery(self):
level = None
charging = False
headers = {'Origin': 'file://',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
'Sec-WebSocket-Protocol': 'json'}
battery_request = {
'msgId': '',
'verb': 'GET',
'path': f'/battery/{self.id}/state'
}
async with websockets.connect(uri="ws://localhost:9010",
extra_headers=headers,
subprotocols=['json'],
) as websocket:
while True:
request = json.dumps(battery_request)
await websocket.send(request)
response = await websocket.recv()
message = json.loads(response)
Shared.logger.info(f'Received: {message}')
if message['path'] == f'/battery/{self.id}/state':
self.batteryLevel = message['payload']['percentage']
self.charging = (message['payload']['charging'] == True)
break
def select(self, tray):
logger = logging.getLogger(Shared.appname)
logger.info(f'Device.SELECT: Selected {self.id} {self.name}')
Shared.selected_device = self
Shared.selected_device_name = self.name
asyncio.run(self.get_battery())
if self.charging:
tooltip = f'{self.name}: {self.batteryLevel}% (charging)'
else:
tooltip = f'{self.name}: {str(self.batteryLevel)}%' | icon = get_icon(self.batteryLevel) | 1 | 2023-10-25 20:37:43+00:00 | 2k |
Kiteretsu77/VCISR-official | degradation/ESR/usm_sharp.py | [
{
"identifier": "filter2D",
"path": "degradation/ESR/utils.py",
"snippet": "def filter2D(img, kernel):\n \"\"\"PyTorch version of cv2.filter2D\n\n Args:\n img (Tensor): (b, c, h, w)\n kernel (Tensor): (b, k, k)\n \"\"\"\n k = kernel.size(-1)\n b, c, h, w = img.size()\n if... | import cv2
import numpy as np
import torch
import os, sys
from torch.nn import functional as F
from degradation.ESR.utils import filter2D, np2tensor, tensor2np | 948 | # -*- coding: utf-8 -*-
root_path = os.path.abspath('.')
sys.path.append(root_path)
def usm_sharp_func(img, weight=0.5, radius=50, threshold=10):
"""USM sharpening.
Input image: I; Blurry image: B.
1. sharp = I + weight * (I - B)
2. Mask = 1 if abs(I - B) > threshold, else: 0
3. Blur mask:
4. Out = Mask * sharp + (1 - Mask) * I
Args:
img (Numpy array): Input image, HWC, BGR; float32, [0, 1].
weight (float): Sharp weight. Default: 1.
radius (float): Kernel size of Gaussian blur. Default: 50.
threshold (int):
"""
if radius % 2 == 0:
radius += 1
blur = cv2.GaussianBlur(img, (radius, radius), 0)
residual = img - blur
mask = np.abs(residual) * 255 > threshold
mask = mask.astype('float32')
soft_mask = cv2.GaussianBlur(mask, (radius, radius), 0)
sharp = img + weight * residual
sharp = np.clip(sharp, 0, 1)
return soft_mask * sharp + (1 - soft_mask) * img
class USMSharp(torch.nn.Module):
def __init__(self, type, radius=50, sigma=0):
super(USMSharp, self).__init__()
if radius % 2 == 0:
radius += 1
self.radius = radius
kernel = cv2.getGaussianKernel(radius, sigma)
kernel = torch.FloatTensor(np.dot(kernel, kernel.transpose())).unsqueeze_(0).cuda()
self.register_buffer('kernel', kernel)
self.type = type
def forward(self, img, weight=0.5, threshold=10, store=False):
if self.type == "cv2":
# pre-process cv2 type
| # -*- coding: utf-8 -*-
root_path = os.path.abspath('.')
sys.path.append(root_path)
def usm_sharp_func(img, weight=0.5, radius=50, threshold=10):
"""USM sharpening.
Input image: I; Blurry image: B.
1. sharp = I + weight * (I - B)
2. Mask = 1 if abs(I - B) > threshold, else: 0
3. Blur mask:
4. Out = Mask * sharp + (1 - Mask) * I
Args:
img (Numpy array): Input image, HWC, BGR; float32, [0, 1].
weight (float): Sharp weight. Default: 1.
radius (float): Kernel size of Gaussian blur. Default: 50.
threshold (int):
"""
if radius % 2 == 0:
radius += 1
blur = cv2.GaussianBlur(img, (radius, radius), 0)
residual = img - blur
mask = np.abs(residual) * 255 > threshold
mask = mask.astype('float32')
soft_mask = cv2.GaussianBlur(mask, (radius, radius), 0)
sharp = img + weight * residual
sharp = np.clip(sharp, 0, 1)
return soft_mask * sharp + (1 - soft_mask) * img
class USMSharp(torch.nn.Module):
def __init__(self, type, radius=50, sigma=0):
super(USMSharp, self).__init__()
if radius % 2 == 0:
radius += 1
self.radius = radius
kernel = cv2.getGaussianKernel(radius, sigma)
kernel = torch.FloatTensor(np.dot(kernel, kernel.transpose())).unsqueeze_(0).cuda()
self.register_buffer('kernel', kernel)
self.type = type
def forward(self, img, weight=0.5, threshold=10, store=False):
if self.type == "cv2":
# pre-process cv2 type | img = np2tensor(img) | 1 | 2023-10-29 04:33:38+00:00 | 2k |
serengil/LightPHE | lightphe/models/Tensor.py | [
{
"identifier": "Homomorphic",
"path": "lightphe/models/Homomorphic.py",
"snippet": "class Homomorphic(ABC):\n keys: dict\n plaintext_modulo: int\n ciphertext_modulo: int\n\n @abstractmethod\n def generate_keys(self, key_size: int, s: Optional[int] = None) -> dict:\n pass\n\n @a... | from typing import Union, List
from lightphe.models.Homomorphic import Homomorphic
from lightphe.commons import phe_utils | 674 |
# pylint: disable=too-few-public-methods, no-else-return
class Fraction:
"""
Class to store fractional values
"""
def __init__(
self,
dividend: Union[int, tuple, list],
abs_dividend: Union[int, tuple, list],
divisor: Union[int, tuple, list],
sign: int = 1,
):
self.dividend = dividend
self.divisor = divisor
self.sign = sign
self.abs_dividend = abs_dividend
def __str__(self):
"""
Print Fraction Class Object
"""
sign = "-" if self.sign == -1 else "+"
return f"Fraction({sign}{self.abs_dividend} / {self.divisor})"
def __repr__(self):
"""
Print Fraction Class Object
"""
return self.__str__()
class EncryptedTensor:
"""
Class to store encrypted tensor objects
"""
|
# pylint: disable=too-few-public-methods, no-else-return
class Fraction:
"""
Class to store fractional values
"""
def __init__(
self,
dividend: Union[int, tuple, list],
abs_dividend: Union[int, tuple, list],
divisor: Union[int, tuple, list],
sign: int = 1,
):
self.dividend = dividend
self.divisor = divisor
self.sign = sign
self.abs_dividend = abs_dividend
def __str__(self):
"""
Print Fraction Class Object
"""
sign = "-" if self.sign == -1 else "+"
return f"Fraction({sign}{self.abs_dividend} / {self.divisor})"
def __repr__(self):
"""
Print Fraction Class Object
"""
return self.__str__()
class EncryptedTensor:
"""
Class to store encrypted tensor objects
"""
| def __init__(self, fractions: List[Fraction], cs: Homomorphic): | 0 | 2023-10-28 14:57:59+00:00 | 2k |
DataCanvasIO/LMS | lms/runtime/prune/llm_pruner/LLMPruner/peft/utils/save_and_load.py | [
{
"identifier": "PeftType",
"path": "lms/runtime/prune/llm_pruner/LLMPruner/peft/utils/config.py",
"snippet": "class PeftType(str, enum.Enum):\n PROMPT_TUNING = \"PROMPT_TUNING\"\n P_TUNING = \"P_TUNING\"\n PREFIX_TUNING = \"PREFIX_TUNING\"\n LORA = \"LORA\"\n ADALORA = \"ADALORA\""
},
... | from .config import PeftType, PromptLearningConfig | 732 | # coding=utf-8
# Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def get_peft_model_state_dict(model, state_dict=None, adapter_name="default"):
"""
Get the state dict of the Peft model.
Args:
model ([`PeftModel`]): The Peft model. When using torch.nn.DistributedDataParallel, DeepSpeed or FSDP,
the model should be the underlying model/unwrapped model (i.e. model.module).
state_dict (`dict`, *optional*, defaults to `None`):
The state dict of the model. If not provided, the state dict of the model
will be used.
"""
config = model.peft_config[adapter_name]
if state_dict is None:
state_dict = model.state_dict()
| # coding=utf-8
# Copyright 2023-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def get_peft_model_state_dict(model, state_dict=None, adapter_name="default"):
"""
Get the state dict of the Peft model.
Args:
model ([`PeftModel`]): The Peft model. When using torch.nn.DistributedDataParallel, DeepSpeed or FSDP,
the model should be the underlying model/unwrapped model (i.e. model.module).
state_dict (`dict`, *optional*, defaults to `None`):
The state dict of the model. If not provided, the state dict of the model
will be used.
"""
config = model.peft_config[adapter_name]
if state_dict is None:
state_dict = model.state_dict() | if config.peft_type in (PeftType.LORA, PeftType.ADALORA): | 0 | 2023-10-30 10:50:32+00:00 | 2k |
imhotep/hass-unifi-access | custom_components/unifi_access/hub.py | [
{
"identifier": "DEVICE_NOTIFICATIONS_URL",
"path": "custom_components/unifi_access/const.py",
"snippet": "DEVICE_NOTIFICATIONS_URL = \"/api/v1/developer/devices/notifications\""
},
{
"identifier": "DOOR_UNLOCK_URL",
"path": "custom_components/unifi_access/const.py",
"snippet": "DOOR_UNL... | import asyncio
import json
import logging
import ssl
import urllib3
import websocket
from datetime import timedelta
from threading import Thread
from urllib.parse import urlparse
from requests import request
from requests.exceptions import ConnectionError as ConnError, SSLError
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import (
DEVICE_NOTIFICATIONS_URL,
DOOR_UNLOCK_URL,
DOORS_URL,
UNIFI_ACCESS_API_PORT,
)
from .door import UnifiAccessDoor | 1,326 | """Unifi Access Hub.
This module interacts with the Unifi Access API server.
"""
_LOGGER = logging.getLogger(__name__)
class ApiAuthError(Exception):
"""Raised when we can't authenticate with the API Token."""
class ApiError(Exception):
"""Raised when we have some trouble using the API."""
class UnifiAccessHub:
"""UnifiAccessHub.
This class takes care of interacting with the Unifi Access API.
"""
def __init__(
self, host: str, verify_ssl: bool = False, use_polling: bool = False
) -> None:
"""Initialize."""
self.use_polling = use_polling
self.verify_ssl = verify_ssl
if self.verify_ssl is False:
_LOGGER.warning("SSL Verification disabled for %s", host)
urllib3.disable_warnings()
host_parts = host.split(":")
parsed_host = urlparse(host)
hostname = parsed_host.hostname if parsed_host.hostname else host_parts[0]
port = (
parsed_host.port
if parsed_host.port
else (host_parts[1] if len(host_parts) > 1 else UNIFI_ACCESS_API_PORT)
)
self._api_token = None
self.host = f"https://{hostname}:{port}"
self._http_headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
self.websocket_host = f"wss://{hostname}:{port}"
self._websocket_headers = {
"Upgrade": "websocket",
"Connection": "Upgrade",
}
self._doors: dict[str, UnifiAccessDoor] = {}
self.update_t = None
@property
def doors(self):
"""Get current doors."""
return self._doors
def set_api_token(self, api_token):
"""Set API Access Token."""
self._api_token = api_token
self._http_headers["Authorization"] = f"Bearer {self._api_token}"
self._websocket_headers["Authorization"] = f"Bearer {self._api_token}"
def update(self):
"""Get latest door data."""
_LOGGER.info(
"Getting door updates from Unifi Access %s Use Polling %s",
self.host,
self.use_polling,
)
| """Unifi Access Hub.
This module interacts with the Unifi Access API server.
"""
_LOGGER = logging.getLogger(__name__)
class ApiAuthError(Exception):
"""Raised when we can't authenticate with the API Token."""
class ApiError(Exception):
"""Raised when we have some trouble using the API."""
class UnifiAccessHub:
"""UnifiAccessHub.
This class takes care of interacting with the Unifi Access API.
"""
def __init__(
self, host: str, verify_ssl: bool = False, use_polling: bool = False
) -> None:
"""Initialize."""
self.use_polling = use_polling
self.verify_ssl = verify_ssl
if self.verify_ssl is False:
_LOGGER.warning("SSL Verification disabled for %s", host)
urllib3.disable_warnings()
host_parts = host.split(":")
parsed_host = urlparse(host)
hostname = parsed_host.hostname if parsed_host.hostname else host_parts[0]
port = (
parsed_host.port
if parsed_host.port
else (host_parts[1] if len(host_parts) > 1 else UNIFI_ACCESS_API_PORT)
)
self._api_token = None
self.host = f"https://{hostname}:{port}"
self._http_headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
self.websocket_host = f"wss://{hostname}:{port}"
self._websocket_headers = {
"Upgrade": "websocket",
"Connection": "Upgrade",
}
self._doors: dict[str, UnifiAccessDoor] = {}
self.update_t = None
@property
def doors(self):
"""Get current doors."""
return self._doors
def set_api_token(self, api_token):
"""Set API Access Token."""
self._api_token = api_token
self._http_headers["Authorization"] = f"Bearer {self._api_token}"
self._websocket_headers["Authorization"] = f"Bearer {self._api_token}"
def update(self):
"""Get latest door data."""
_LOGGER.info(
"Getting door updates from Unifi Access %s Use Polling %s",
self.host,
self.use_polling,
) | data = self._make_http_request(f"{self.host}{DOORS_URL}") | 2 | 2023-10-27 20:34:27+00:00 | 2k |
aws-samples/amazon-bedrock-serverless-prompt-chaining | stacks/trip_planner_stack.py | [
{
"identifier": "get_lambda_bundling_options",
"path": "stacks/util.py",
"snippet": "def get_lambda_bundling_options():\n return lambda_python.BundlingOptions(\n asset_excludes=[\".venv\", \".mypy_cache\", \"__pycache__\"],\n command_hooks=CommandHooks(),\n )"
},
{
"identifie... | from aws_cdk import (
Duration,
Stack,
RemovalPolicy,
aws_lambda as lambda_,
aws_lambda_python_alpha as lambda_python,
aws_s3 as s3,
aws_ssm as ssm,
aws_stepfunctions as sfn,
aws_stepfunctions_tasks as tasks,
)
from constructs import Construct
from .util import (
get_lambda_bundling_options,
get_claude_instant_invoke_chain,
) | 692 |
class TripPlannerStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
# Agent #1: suggest places to stay
|
class TripPlannerStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
# Agent #1: suggest places to stay | hotels_job = get_claude_instant_invoke_chain( | 1 | 2023-10-26 22:17:30+00:00 | 2k |
pengsongyou/lseg_feature_extraction | modules/models/lseg_blocks.py | [
{
"identifier": "_make_pretrained_clip_vitl16_384",
"path": "modules/models/lseg_vit.py",
"snippet": "def _make_pretrained_clip_vitl16_384(\n pretrained, use_readout=\"ignore\", hooks=None, enable_attention_hooks=False\n):\n clip_pretrained, _ = clip.load(\"ViT-B/32\", device='cuda', jit=False)\n ... | import torch
import torch.nn as nn
from .lseg_vit import (
_make_pretrained_clip_vitl16_384,
_make_pretrained_clip_vitb32_384,
_make_pretrained_clipRN50x16_vitl16_384,
forward_vit,
) | 1,199 |
def _make_encoder(
backbone,
features,
use_pretrained=True,
groups=1,
expand=False,
exportable=True,
hooks=None,
use_vit_only=False,
use_readout="ignore",
enable_attention_hooks=False,
):
if backbone == "clip_vitl16_384":
|
def _make_encoder(
backbone,
features,
use_pretrained=True,
groups=1,
expand=False,
exportable=True,
hooks=None,
use_vit_only=False,
use_readout="ignore",
enable_attention_hooks=False,
):
if backbone == "clip_vitl16_384": | clip_pretrained, pretrained = _make_pretrained_clip_vitl16_384( | 0 | 2023-10-27 15:40:36+00:00 | 2k |
chenran-li/RQL-release | rl_zoo3/plots/plot_train.py | [
{
"identifier": "LoadMonitorResultsError",
"path": "stable_baselines3/common/monitor.py",
"snippet": "class LoadMonitorResultsError(Exception):\n \"\"\"\n Raised when loading the monitor log fails.\n \"\"\"\n\n pass"
},
{
"identifier": "load_results",
"path": "stable_baselines3/c... | import argparse
import os
import numpy as np
import seaborn
from matplotlib import pyplot as plt
from stable_baselines3.common.monitor import LoadMonitorResultsError, load_results
from stable_baselines3.common.results_plotter import X_EPISODES, X_TIMESTEPS, X_WALLTIME, ts2xy, window_func | 1,247 | """
Plot training reward/success rate
"""
# Activate seaborn
seaborn.set()
def plot_train():
parser = argparse.ArgumentParser("Gather results, plot training reward/success")
parser.add_argument("-a", "--algo", help="Algorithm to include", type=str, required=True)
parser.add_argument("-e", "--env", help="Environment(s) to include", nargs="+", type=str, required=True)
parser.add_argument("-f", "--exp-folder", help="Folders to include", type=str, required=True)
parser.add_argument("--figsize", help="Figure size, width, height in inches.", nargs=2, type=int, default=[6.4, 4.8])
parser.add_argument("--fontsize", help="Font size", type=int, default=14)
parser.add_argument("-max", "--max-timesteps", help="Max number of timesteps to display", type=int)
parser.add_argument("-x", "--x-axis", help="X-axis", choices=["steps", "episodes", "time"], type=str, default="steps")
parser.add_argument("-y", "--y-axis", help="Y-axis", choices=["success", "reward", "length"], type=str, default="reward")
parser.add_argument("-w", "--episode-window", help="Rolling window size", type=int, default=100)
args = parser.parse_args()
algo = args.algo
envs = args.env
log_path = os.path.join(args.exp_folder, algo)
x_axis = {
| """
Plot training reward/success rate
"""
# Activate seaborn
seaborn.set()
def plot_train():
parser = argparse.ArgumentParser("Gather results, plot training reward/success")
parser.add_argument("-a", "--algo", help="Algorithm to include", type=str, required=True)
parser.add_argument("-e", "--env", help="Environment(s) to include", nargs="+", type=str, required=True)
parser.add_argument("-f", "--exp-folder", help="Folders to include", type=str, required=True)
parser.add_argument("--figsize", help="Figure size, width, height in inches.", nargs=2, type=int, default=[6.4, 4.8])
parser.add_argument("--fontsize", help="Font size", type=int, default=14)
parser.add_argument("-max", "--max-timesteps", help="Max number of timesteps to display", type=int)
parser.add_argument("-x", "--x-axis", help="X-axis", choices=["steps", "episodes", "time"], type=str, default="steps")
parser.add_argument("-y", "--y-axis", help="Y-axis", choices=["success", "reward", "length"], type=str, default="reward")
parser.add_argument("-w", "--episode-window", help="Rolling window size", type=int, default=100)
args = parser.parse_args()
algo = args.algo
envs = args.env
log_path = os.path.join(args.exp_folder, algo)
x_axis = { | "steps": X_TIMESTEPS, | 3 | 2023-10-28 01:09:21+00:00 | 2k |
AmgdGocha/DriveFS-Sleuth | drivefs_sleuth/tasks.py | [
{
"identifier": "copy_file",
"path": "drivefs_sleuth/utils.py",
"snippet": "def copy_file(file_path, dest_filename, recovery_path=''):\n if not recovery_path:\n recovery_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'recovered_items')\n\n if not os.path.exists(recovery_pat... | import os
import csv
from jinja2 import Environment
from jinja2 import FileSystemLoader
from drivefs_sleuth.utils import copy_file
from drivefs_sleuth.utils import lookup_account_id
from drivefs_sleuth.utils import get_properties_list
from drivefs_sleuth.utils import get_account_properties
from drivefs_sleuth.utils import get_available_profiles
from drivefs_sleuth.utils import get_experiment_account_ids
from drivefs_sleuth.synced_files_tree import File
from drivefs_sleuth.synced_files_tree import Link | 1,505 |
def get_accounts(drivefs_path):
accounts = {}
experiments_ids = get_experiment_account_ids(drivefs_path)
profiles = get_available_profiles(drivefs_path)
available_accounts = set(experiments_ids + profiles)
for account_id in available_accounts:
accounts[account_id] = {
'email': lookup_account_id(drivefs_path, account_id)
}
logged_in = account_id in profiles
accounts[account_id]['logged_in'] = logged_in
accounts[account_id]['properties'] = get_account_properties(os.path.join(drivefs_path, account_id))
return accounts
def __build_headers(setup):
headers = ['stable_id', 'type', 'url_id', 'local_title', 'mime_type', 'path_in_content_cache', 'is_owner',
'file_size', 'modified_date', 'viewed_by_me_date', 'trashed', 'tree_path', 'md5']
for account in setup.get_accounts():
if account.is_logged_in():
|
def get_accounts(drivefs_path):
accounts = {}
experiments_ids = get_experiment_account_ids(drivefs_path)
profiles = get_available_profiles(drivefs_path)
available_accounts = set(experiments_ids + profiles)
for account_id in available_accounts:
accounts[account_id] = {
'email': lookup_account_id(drivefs_path, account_id)
}
logged_in = account_id in profiles
accounts[account_id]['logged_in'] = logged_in
accounts[account_id]['properties'] = get_account_properties(os.path.join(drivefs_path, account_id))
return accounts
def __build_headers(setup):
headers = ['stable_id', 'type', 'url_id', 'local_title', 'mime_type', 'path_in_content_cache', 'is_owner',
'file_size', 'modified_date', 'viewed_by_me_date', 'trashed', 'tree_path', 'md5']
for account in setup.get_accounts():
if account.is_logged_in(): | for prop in get_properties_list(os.path.join(setup.get_drivefs_path(), account.get_account_id())): | 2 | 2023-10-29 11:05:04+00:00 | 2k |
zyang1580/CoLLM | minigpt4/datasets/builders/rec_base_dataset_builder.py | [
{
"identifier": "is_dist_avail_and_initialized",
"path": "minigpt4/common/dist_utils.py",
"snippet": "def is_dist_avail_and_initialized():\n if not dist.is_available():\n return False\n if not dist.is_initialized():\n return False\n return True"
},
{
"identifier": "is_main... | import logging
import os
import shutil
import warnings
import torch.distributed as dist
import minigpt4.common.utils as utils
from omegaconf import OmegaConf
from torchvision.datasets.utils import download_url
from minigpt4.common.dist_utils import is_dist_avail_and_initialized, is_main_process
from minigpt4.common.registry import registry
from minigpt4.processors.base_processor import BaseProcessor | 799 | """
This file is from
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
class RecBaseDatasetBuilder:
train_dataset_cls, eval_dataset_cls = None, None
def __init__(self, cfg=None):
super().__init__()
if cfg is None:
# help to create datasets from default config.
self.config = load_dataset_config(self.default_config_path())
elif isinstance(cfg, str):
self.config = load_dataset_config(cfg)
else:
# when called from task.build_dataset()
self.config = cfg
self.data_type = self.config.data_type
# self.vis_processors = {"train": BaseProcessor(), "eval": BaseProcessor()}
self.text_processors = {"train": BaseProcessor(), "eval": BaseProcessor()}
def build_datasets(self):
# download, split, etc...
# only called on 1 GPU/TPU in distributed
| """
This file is from
Copyright (c) 2022, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE_Lavis file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
class RecBaseDatasetBuilder:
train_dataset_cls, eval_dataset_cls = None, None
def __init__(self, cfg=None):
super().__init__()
if cfg is None:
# help to create datasets from default config.
self.config = load_dataset_config(self.default_config_path())
elif isinstance(cfg, str):
self.config = load_dataset_config(cfg)
else:
# when called from task.build_dataset()
self.config = cfg
self.data_type = self.config.data_type
# self.vis_processors = {"train": BaseProcessor(), "eval": BaseProcessor()}
self.text_processors = {"train": BaseProcessor(), "eval": BaseProcessor()}
def build_datasets(self):
# download, split, etc...
# only called on 1 GPU/TPU in distributed
| if is_main_process(): | 1 | 2023-10-29 12:47:25+00:00 | 2k |
naver/bq-nco | learning/op/traj_learner.py | [
{
"identifier": "decode",
"path": "learning/op/decoding.py",
"snippet": "def decode(node_coords: Tensor, node_values: Tensor, upper_bounds: Tensor, dist_matrices: Tensor, net: Module,\n beam_size: int, knns: int) -> Tensor:\n if beam_size == 1:\n tours, collected_rewards = greedy_dec... | import time
import torch
from torch import nn
from learning.op.decoding import decode
from utils.misc import do_lr_decay, EpochMetrics | 791 | """
BQ-NCO
Copyright (c) 2023-present NAVER Corp.
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 license
"""
DEBUG_NUM_BATCHES = 3
class TrajectoryLearner:
def __init__(self, args, net, module, device, data_iterator, optimizer=None, checkpointer=None):
# same supervisor is used for training and testing, during testing we do not have optimizer, mlflow etc.
self.net = net
self.module = module
self.device = device
self.data_iterator = data_iterator
self.optimizer = optimizer
self.checkpointer = checkpointer
self.beam_size = args.beam_size
self.knns = args.knns
self.output_dir = args.output_dir
self.test_only = args.test_only
self.debug = args.debug
if not args.test_only:
try:
self.test_every = args.test_every if args.test_every > 0 else None
except AttributeError:
self.test_every = None
self.decay_rate = args.decay_rate
self.decay_every = args.decay_every
self.loss = nn.CrossEntropyLoss()
self.best_current_val_metric = float('inf')
self.epoch_done = 0
self.nb_epochs = args.nb_total_epochs
def train(self):
assert not self.test_only
for _ in range(self.nb_epochs):
# Train one epoch
start = time.time()
self.net.train()
| """
BQ-NCO
Copyright (c) 2023-present NAVER Corp.
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 license
"""
DEBUG_NUM_BATCHES = 3
class TrajectoryLearner:
def __init__(self, args, net, module, device, data_iterator, optimizer=None, checkpointer=None):
# same supervisor is used for training and testing, during testing we do not have optimizer, mlflow etc.
self.net = net
self.module = module
self.device = device
self.data_iterator = data_iterator
self.optimizer = optimizer
self.checkpointer = checkpointer
self.beam_size = args.beam_size
self.knns = args.knns
self.output_dir = args.output_dir
self.test_only = args.test_only
self.debug = args.debug
if not args.test_only:
try:
self.test_every = args.test_every if args.test_every > 0 else None
except AttributeError:
self.test_every = None
self.decay_rate = args.decay_rate
self.decay_every = args.decay_every
self.loss = nn.CrossEntropyLoss()
self.best_current_val_metric = float('inf')
self.epoch_done = 0
self.nb_epochs = args.nb_total_epochs
def train(self):
assert not self.test_only
for _ in range(self.nb_epochs):
# Train one epoch
start = time.time()
self.net.train() | epoch_metrics_train = EpochMetrics() | 2 | 2023-10-27 09:08:45+00:00 | 2k |
coder-pig/YuQueBackups | app.py | [
{
"identifier": "init_token",
"path": "yuque_doc_backups.py",
"snippet": "def is_dir_existed(file_path, mkdir=True):\ndef write_text_to_file(content, file_path, mode=\"w+\"):\ndef scan_file_list_by_suffix(file_dir=os.getcwd(), suffix=\"\"):\n def __init__(self, repo_id, repo_type, repo_slug, repo_nam... | from yuque_doc_backups import init_token, fetch_user_id, fetch_repo_list, fetch_toc_list, doc_count
from yeque_md_to_local import search_all_file, md_to_local, pic_url_path_record_list, download_pic
import asyncio
import time | 685 | # -*- coding: utf-8 -*-
# !/usr/bin/env python
"""
-------------------------------------------------
File : app.py
Author : CoderPig
date : 2023-10-26 14:57
Desc : 语雀备份脚本-入口
-------------------------------------------------
"""
if __name__ == '__main__':
yq_token = input("请输入你的语雀Token:")
if len(yq_token) == 0:
exit("请输入正确的Token!")
init_token(yq_token)
start_time = time.time()
yq_user_id = fetch_user_id()
print("开始执行文档备份,请稍等...")
yq_repo_list = fetch_repo_list(yq_user_id)
for yq_repo in yq_repo_list:
print("开始拉取【{}】仓库下的文档".format(yq_repo.repo_name))
fetch_toc_list(yq_repo.repo_id, yq_repo.repo_name)
print("文档备份完毕,共记备份文档【{}】篇,开始执行Markdown文件批量本地化...".format(doc_count))
yq_doc_file_list = search_all_file()
print("共扫描到Markdown文件【{}】篇,开始批量本地化...".format(len(yq_doc_file_list)))
| # -*- coding: utf-8 -*-
# !/usr/bin/env python
"""
-------------------------------------------------
File : app.py
Author : CoderPig
date : 2023-10-26 14:57
Desc : 语雀备份脚本-入口
-------------------------------------------------
"""
if __name__ == '__main__':
yq_token = input("请输入你的语雀Token:")
if len(yq_token) == 0:
exit("请输入正确的Token!")
init_token(yq_token)
start_time = time.time()
yq_user_id = fetch_user_id()
print("开始执行文档备份,请稍等...")
yq_repo_list = fetch_repo_list(yq_user_id)
for yq_repo in yq_repo_list:
print("开始拉取【{}】仓库下的文档".format(yq_repo.repo_name))
fetch_toc_list(yq_repo.repo_id, yq_repo.repo_name)
print("文档备份完毕,共记备份文档【{}】篇,开始执行Markdown文件批量本地化...".format(doc_count))
yq_doc_file_list = search_all_file()
print("共扫描到Markdown文件【{}】篇,开始批量本地化...".format(len(yq_doc_file_list))) | md_to_local(yq_doc_file_list) | 1 | 2023-10-26 08:35:04+00:00 | 2k |
tobagin/whakarere | whakarere/pages/whatsapp.py | [
{
"identifier": "ChatItem",
"path": "whakarere/types/chat.py",
"snippet": "class ChatItem(GObject.Object):\n chat_id = GObject.Property(type=str)\n chat_name = GObject.Property(type=str)\n chat_picture = GObject.Property(type=Gdk.Texture)\n last_message_body = GObject.Property(type=str)\n ... | import gi
import base64, requests, threading
from whakarere.types.chat import ChatItem
from whakarere.widgets.titlebar import WindowTitlebarWidget
from whakarere.widgets.main_menu import MainMenuButtonWidget
from gi.repository import Gtk, Adw, GLib, Gio, GdkPixbuf, Pango, Gdk, GObject
from datetime import datetime | 1,319 |
gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
gi.require_version("GdkPixbuf", "2.0")
class WhatsappMessengerPage(Adw.NavigationPage):
def __init__(self, app_manager, session_id):
super().__init__()
self.set_title("Whakarere")
self.app_manager = app_manager
self.session_id = session_id
# Create TitleBar Widget
|
gi.require_version("Gtk", "4.0")
gi.require_version("Adw", "1")
gi.require_version("GdkPixbuf", "2.0")
class WhatsappMessengerPage(Adw.NavigationPage):
def __init__(self, app_manager, session_id):
super().__init__()
self.set_title("Whakarere")
self.app_manager = app_manager
self.session_id = session_id
# Create TitleBar Widget | self.window_titlebar_widget = WindowTitlebarWidget() | 1 | 2023-10-29 15:46:50+00:00 | 2k |
Agricultural-Robotics-Bonn/pagnerf | loss/lin_assignment_things.py | [
{
"identifier": "centers_from_3d_points_with_ids",
"path": "utils/outlier_rejection.py",
"snippet": "def centers_from_3d_points_with_ids(points):\n # points: [N,[x,y,z,ID]]\n # return: [I,[x,y,z,ID]]\n # K: number of unique IDs\n # [K,[x,y,z,ID]]: centers of the points with t... | import numpy as np
import torch
import scipy
import torch.nn.functional as F
from torch import nn
from utils.outlier_rejection import centers_from_3d_points_with_ids, add_position_id_range_cost | 1,485 | # from panoptic lifting implementation
#
#https://github.com/nihalsid/panoptic-lifting/blob/7af7a3e8477ead8e57f699a240d993e3bc21ee42/trainer/train_panopli_tensorf.py#L195-L206
class LinAssignmentThingsLoss(nn.Module):
def __init__(self, outlier_rejection=False, min_distance=0.2, max_distance=0.5, *args, **kwargs):
super().__init__()
self.outlier_rejection = outlier_rejection
self.min_distance = min_distance
self.max_distance = max_distance
self.inst_centers_db = torch.zeros([0,4]).to('cuda')
@torch.no_grad()
def create_virtual_gt_with_linear_assignment(self, inst_probabilities, labels_gt, points_3d=None):
# Leave first element for stuff
things_mask = labels_gt > 0
things_gt = labels_gt[things_mask]
things_prob = inst_probabilities[things_mask][...,1:]
# Compute surrogate labels
labels = sorted(torch.unique(things_gt).cpu().tolist())[:things_prob.shape[-1]]
cost_matrix = np.zeros([len(labels), things_prob.shape[-1]])
for lidx, label in enumerate(labels):
cost_matrix[lidx, :] = -(things_prob[things_gt == label, :].sum(dim=0) / ((things_gt == label).sum() + 1e-4)).cpu().numpy()
# Update cost matrix to avoid early assignment of repeated IDs
assert self.outlier_rejection and points_3d is not None or not self.outlier_rejection, \
'Outlier rejection requires 3d points'
if self.outlier_rejection:
# Compute centers of the current things Id gts
points_3d_gt = torch.cat([points_3d[things_mask], things_gt[:,None]], dim=-1)
current_inst_centers = centers_from_3d_points_with_ids(points_3d_gt)
# Update cost matrix to have high cost when trying to assign repeated IDs
| # from panoptic lifting implementation
#
#https://github.com/nihalsid/panoptic-lifting/blob/7af7a3e8477ead8e57f699a240d993e3bc21ee42/trainer/train_panopli_tensorf.py#L195-L206
class LinAssignmentThingsLoss(nn.Module):
def __init__(self, outlier_rejection=False, min_distance=0.2, max_distance=0.5, *args, **kwargs):
super().__init__()
self.outlier_rejection = outlier_rejection
self.min_distance = min_distance
self.max_distance = max_distance
self.inst_centers_db = torch.zeros([0,4]).to('cuda')
@torch.no_grad()
def create_virtual_gt_with_linear_assignment(self, inst_probabilities, labels_gt, points_3d=None):
# Leave first element for stuff
things_mask = labels_gt > 0
things_gt = labels_gt[things_mask]
things_prob = inst_probabilities[things_mask][...,1:]
# Compute surrogate labels
labels = sorted(torch.unique(things_gt).cpu().tolist())[:things_prob.shape[-1]]
cost_matrix = np.zeros([len(labels), things_prob.shape[-1]])
for lidx, label in enumerate(labels):
cost_matrix[lidx, :] = -(things_prob[things_gt == label, :].sum(dim=0) / ((things_gt == label).sum() + 1e-4)).cpu().numpy()
# Update cost matrix to avoid early assignment of repeated IDs
assert self.outlier_rejection and points_3d is not None or not self.outlier_rejection, \
'Outlier rejection requires 3d points'
if self.outlier_rejection:
# Compute centers of the current things Id gts
points_3d_gt = torch.cat([points_3d[things_mask], things_gt[:,None]], dim=-1)
current_inst_centers = centers_from_3d_points_with_ids(points_3d_gt)
# Update cost matrix to have high cost when trying to assign repeated IDs | cost_matrix = add_position_id_range_cost(cost_matrix, current_inst_centers) | 1 | 2023-10-30 16:14:39+00:00 | 2k |
John-WL/sd-webui-inpaint-difference | lib_inpaint_difference/webui_hijacks.py | [
{
"identifier": "DifferenceGlobals",
"path": "lib_inpaint_difference/globals.py",
"snippet": "class DifferenceGlobals:\n tab_index = None\n\n base_image = None\n altered_image = None\n generated_mask = None\n\n is_extension_enabled = opts.data.get('inpaint_difference_enabled', True)\n ... | import gradio as gr
from modules import img2img, ui_loadsave
from lib_inpaint_difference.globals import DifferenceGlobals
from lib_inpaint_difference.one_time_callable import one_time_callable
from lib_inpaint_difference.img2img_tab_extender import Img2imgTabExtender | 1,429 |
@one_time_callable
def hijack_img2img_processing():
original_img2img_processing = img2img.img2img
def hijack_func(id_task: str, mode: int, prompt: str, negative_prompt: str, prompt_styles, init_img, sketch,
init_img_with_mask, inpaint_color_sketch, inpaint_color_sketch_orig, init_img_inpaint,
init_mask_inpaint, steps: int, sampler_name: str, mask_blur: int, mask_alpha: float,
inpainting_fill: int, n_iter: int, batch_size: int, cfg_scale: float, image_cfg_scale: float,
denoising_strength: float, selected_scale_tab: int, height: int, width: int, scale_by: float,
resize_mode: int, inpaint_full_res: bool, inpaint_full_res_padding: int,
inpainting_mask_invert: int, img2img_batch_input_dir: str, img2img_batch_output_dir: str,
img2img_batch_inpaint_mask_dir: str, override_settings_texts, img2img_batch_use_png_info: bool,
img2img_batch_png_info_props: list, img2img_batch_png_info_dir: str, request: gr.Request, *args,
):
|
@one_time_callable
def hijack_img2img_processing():
original_img2img_processing = img2img.img2img
def hijack_func(id_task: str, mode: int, prompt: str, negative_prompt: str, prompt_styles, init_img, sketch,
init_img_with_mask, inpaint_color_sketch, inpaint_color_sketch_orig, init_img_inpaint,
init_mask_inpaint, steps: int, sampler_name: str, mask_blur: int, mask_alpha: float,
inpainting_fill: int, n_iter: int, batch_size: int, cfg_scale: float, image_cfg_scale: float,
denoising_strength: float, selected_scale_tab: int, height: int, width: int, scale_by: float,
resize_mode: int, inpaint_full_res: bool, inpaint_full_res_padding: int,
inpainting_mask_invert: int, img2img_batch_input_dir: str, img2img_batch_output_dir: str,
img2img_batch_inpaint_mask_dir: str, override_settings_texts, img2img_batch_use_png_info: bool,
img2img_batch_png_info_props: list, img2img_batch_png_info_dir: str, request: gr.Request, *args,
): | if mode == DifferenceGlobals.tab_index: | 0 | 2023-10-30 16:17:34+00:00 | 2k |
BIT-DA/Annotator | tools/utils/train_utils.py | [
{
"identifier": "common_utils",
"path": "tools/utils/common/common_utils.py",
"snippet": "def check_numpy_to_torch(x):\ndef limit_period(val, offset=0.5, period=np.pi):\ndef drop_info_with_name(info, name):\ndef rotate_points_along_z(points, angle):\ndef mask_points_by_range(points, limit_range):\ndef g... | import glob
import os
import torch
import tqdm
import time
import pcdet
from torch.nn.utils import clip_grad_norm_
from tools.utils.common import common_utils, commu_utils | 756 |
def train_one_epoch(model, optimizer, train_loader, model_func, lr_scheduler, accumulated_iter, optim_cfg,
rank, tbar, total_it_each_epoch, dataloader_iter, tb_log=None, leave_pbar=False):
if total_it_each_epoch == len(train_loader):
dataloader_iter = iter(train_loader)
if rank == 0:
pbar = tqdm.tqdm(total=total_it_each_epoch, leave=leave_pbar, desc='train', dynamic_ncols=True)
data_time = common_utils.AverageMeter()
batch_time = common_utils.AverageMeter()
forward_time = common_utils.AverageMeter()
for cur_it in range(total_it_each_epoch):
end = time.time()
try:
batch = next(dataloader_iter)
except StopIteration:
dataloader_iter = iter(train_loader)
batch = next(dataloader_iter)
print('new iters')
data_timer = time.time()
cur_data_time = data_timer - end
lr_scheduler.step(accumulated_iter)
try:
cur_lr = float(optimizer.lr)
except:
cur_lr = optimizer.param_groups[0]['lr']
if tb_log is not None:
tb_log.add_scalar('meta_data/learning_rate', cur_lr, accumulated_iter)
model.train()
optimizer.zero_grad()
loss, tb_dict, disp_dict = model_func(model, batch)
forward_timer = time.time()
cur_forward_time = forward_timer - data_timer
loss.backward()
clip_grad_norm_(model.parameters(), optim_cfg.GRAD_NORM_CLIP)
optimizer.step()
accumulated_iter += 1
cur_batch_time = time.time() - end
# average reduce
|
def train_one_epoch(model, optimizer, train_loader, model_func, lr_scheduler, accumulated_iter, optim_cfg,
rank, tbar, total_it_each_epoch, dataloader_iter, tb_log=None, leave_pbar=False):
if total_it_each_epoch == len(train_loader):
dataloader_iter = iter(train_loader)
if rank == 0:
pbar = tqdm.tqdm(total=total_it_each_epoch, leave=leave_pbar, desc='train', dynamic_ncols=True)
data_time = common_utils.AverageMeter()
batch_time = common_utils.AverageMeter()
forward_time = common_utils.AverageMeter()
for cur_it in range(total_it_each_epoch):
end = time.time()
try:
batch = next(dataloader_iter)
except StopIteration:
dataloader_iter = iter(train_loader)
batch = next(dataloader_iter)
print('new iters')
data_timer = time.time()
cur_data_time = data_timer - end
lr_scheduler.step(accumulated_iter)
try:
cur_lr = float(optimizer.lr)
except:
cur_lr = optimizer.param_groups[0]['lr']
if tb_log is not None:
tb_log.add_scalar('meta_data/learning_rate', cur_lr, accumulated_iter)
model.train()
optimizer.zero_grad()
loss, tb_dict, disp_dict = model_func(model, batch)
forward_timer = time.time()
cur_forward_time = forward_timer - data_timer
loss.backward()
clip_grad_norm_(model.parameters(), optim_cfg.GRAD_NORM_CLIP)
optimizer.step()
accumulated_iter += 1
cur_batch_time = time.time() - end
# average reduce | avg_data_time = commu_utils.average_reduce_value(cur_data_time) | 1 | 2023-10-31 08:11:57+00:00 | 2k |
hl123-123/yiyan-ppt | gradio_test.py | [
{
"identifier": "yiyan_api",
"path": "yiyan.py",
"snippet": "def yiyan_api(message,access_token,use4=False):\n if use4:\n url = \"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=\" + access_token\n else:\n url = \"https://aip.baidubce.co... | import gradio as gr
import gradio as gr
import os
import time
import random
import structure_article
import shutil
from yiyan import yiyan_api, get_access_token
from mdtree import tree2ppt
from PIL import Image | 953 | # def image_mod():
# return Image.open("pptx_static/static/img.png")
def save_knowledge_func(task_name,knowledge_content,mode,sub_num):
time1= time.time()
sub_num = int(sub_num)
rand_seed = str(random.randint(0,10000000000000000000000000000000000000000000000000000))
character_a = "你是一个精通各方面知识的人"
struct_article = structure_article.StructureArticle(api_type="yiyan",main_idea_knowledge=knowledge_content,max_sub_idea_num=sub_num,min_sub_idea_num=sub_num)
content = struct_article.generate_final_summary(task_name,character_a)
# md_content = read_md_file("./"+task_name+".md")
if len(os.listdir("./myppt"))>100:
shutil.rmtree("./myppt")
os.makedirs("./myppt")
save_path = "./myppt/test" + rand_seed + ".pptx"
| # def image_mod():
# return Image.open("pptx_static/static/img.png")
def save_knowledge_func(task_name,knowledge_content,mode,sub_num):
time1= time.time()
sub_num = int(sub_num)
rand_seed = str(random.randint(0,10000000000000000000000000000000000000000000000000000))
character_a = "你是一个精通各方面知识的人"
struct_article = structure_article.StructureArticle(api_type="yiyan",main_idea_knowledge=knowledge_content,max_sub_idea_num=sub_num,min_sub_idea_num=sub_num)
content = struct_article.generate_final_summary(task_name,character_a)
# md_content = read_md_file("./"+task_name+".md")
if len(os.listdir("./myppt"))>100:
shutil.rmtree("./myppt")
os.makedirs("./myppt")
save_path = "./myppt/test" + rand_seed + ".pptx" | tree2ppt.Tree2PPT(content,"./my_ppt_mode/"+str(int(mode)),save_path=save_path) | 2 | 2023-10-29 15:10:06+00:00 | 2k |
thoddnn/open-datagen | opendatagen/anonymizer.py | [
{
"identifier": "OpenAIChatModel",
"path": "opendatagen/model.py",
"snippet": "class OpenAIChatModel(BaseModel):\n\n name:str = \"gpt-3.5-turbo-1106\"\n system_prompt:Optional[str] = \"No verbose.\"\n max_tokens:Optional[int] = 256\n temperature:Optional[List[float]] = [1]\n json_mode:Opt... | import re
import spacy
from opendatagen.model import OpenAIChatModel, ModelName
from opendatagen.utils import load_file | 1,575 |
class Anonymizer:
NER_PLACEHOLDER = {
"PERSON": "{person}",
"ORG": "{organization}",
"GPE": "{location}",
"DATE": "{date}",
"TIME": "{time}",
"NORP": "{group}",
"FAC": "{facility}",
"LOC": "{location}",
"PRODUCT": "{product}",
"EVENT": "{event}",
"WORK_OF_ART": "{artwork}",
"LAW": "{law}",
"LANGUAGE": "{language}",
"MONEY": "{money}",
"PERCENT": "{percentage}",
"ORDINAL": "{ordinal}",
"CARDINAL": "{number}",
# Add more if needed
}
REGEX_PATTERN = {
"{phone_number}": r"\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}",
"{email}": r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b",
"{credit_card_pattern}": r"\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}",
"{address_pattern}": r"\d{1,5}\s\w+(\s\w+)*,\s\w+,\s\w+(\s\w+)*",
"{date_pattern}": r"(\d{4}[-/]\d{1,2}[-/]\d{1,2})|(\d{1,2}[-/]\d{1,2}[-/]\d{4})",
"{time_pattern}": r"(?:[01]\d|2[0-3]):[0-5]\d",
"{ipv4_pattern}": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",
"{url_pattern}": r"https?://(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)",
"{ssn_pattern}": r"\d{3}-\d{2}-\d{4}",
"{license_plate_pattern}": r"[A-Z0-9]{2,}-[A-Z0-9]{2,}",
"{zip_code_pattern}": r"\d{5}(-\d{4})?",
"{vin_pattern}": r"[A-HJ-NPR-Z0-9]{17}",
"{iban_pattern}": r"[A-Z]{2}\d{2}[A-Z0-9]{1,30}",
"{driver_license_pattern}": r"[A-Z]{1,2}-\d{4,9}"
}
|
class Anonymizer:
NER_PLACEHOLDER = {
"PERSON": "{person}",
"ORG": "{organization}",
"GPE": "{location}",
"DATE": "{date}",
"TIME": "{time}",
"NORP": "{group}",
"FAC": "{facility}",
"LOC": "{location}",
"PRODUCT": "{product}",
"EVENT": "{event}",
"WORK_OF_ART": "{artwork}",
"LAW": "{law}",
"LANGUAGE": "{language}",
"MONEY": "{money}",
"PERCENT": "{percentage}",
"ORDINAL": "{ordinal}",
"CARDINAL": "{number}",
# Add more if needed
}
REGEX_PATTERN = {
"{phone_number}": r"\+?\d{1,4}?[-.\s]?\(?\d{1,3}?\)?[-.\s]?\d{1,4}[-.\s]?\d{1,4}[-.\s]?\d{1,9}",
"{email}": r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b",
"{credit_card_pattern}": r"\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}",
"{address_pattern}": r"\d{1,5}\s\w+(\s\w+)*,\s\w+,\s\w+(\s\w+)*",
"{date_pattern}": r"(\d{4}[-/]\d{1,2}[-/]\d{1,2})|(\d{1,2}[-/]\d{1,2}[-/]\d{4})",
"{time_pattern}": r"(?:[01]\d|2[0-3]):[0-5]\d",
"{ipv4_pattern}": r"\b(?:\d{1,3}\.){3}\d{1,3}\b",
"{url_pattern}": r"https?://(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)",
"{ssn_pattern}": r"\d{3}-\d{2}-\d{4}",
"{license_plate_pattern}": r"[A-Z0-9]{2,}-[A-Z0-9]{2,}",
"{zip_code_pattern}": r"\d{5}(-\d{4})?",
"{vin_pattern}": r"[A-HJ-NPR-Z0-9]{17}",
"{iban_pattern}": r"[A-Z]{2}\d{2}[A-Z0-9]{1,30}",
"{driver_license_pattern}": r"[A-Z]{1,2}-\d{4,9}"
}
| def __init__(self, completion_model:OpenAIChatModel): | 0 | 2023-10-27 17:38:37+00:00 | 2k |
HAMNET-AI/PDFTriage | src/routers.py | [
{
"identifier": "fetch_figure",
"path": "src/triage.py",
"snippet": "def fetch_figure(query):\n query_prompt = f\"What contents mentioned in the figure of this pdf\"\n path = query_engine.query(query_prompt).metadata['json_path_response_str'].replace(\"&&\", \"&\")\n jsonpath_expression = parse... | from llama_index.tools import ToolMetadata
from llama_index.selectors.llm_selectors import LLMSingleSelector
from .triage import fetch_figure, fetch_pages, fetch_sections, fetch_table, retrieve | 884 |
def router(query):
choices = [
ToolMetadata(description="Get the text contained in the pages listed", name="fetch_pages"),
ToolMetadata(description="Get the text contained in the section listed", name="fetch_sections"),
ToolMetadata(description="Get the text contained in the figure caption listed", name="fetch_figure"),
ToolMetadata(description="Get the text contained in the table caption listed", name="fetch_table"),
ToolMetadata(description="Issue a natural language query over the document, and fetch relevant chunks.",
name="retrieve"),
]
# choices as a list of strings
# choices = ["fetch_pages", "fetch_sections", "fetch_figure", "fetch_table", "retrieve"]
selector = LLMSingleSelector.from_defaults()
result = selector.select(choices, query=query).selections
flag = result[0].index
print(flag)
if flag == 0:
|
def router(query):
choices = [
ToolMetadata(description="Get the text contained in the pages listed", name="fetch_pages"),
ToolMetadata(description="Get the text contained in the section listed", name="fetch_sections"),
ToolMetadata(description="Get the text contained in the figure caption listed", name="fetch_figure"),
ToolMetadata(description="Get the text contained in the table caption listed", name="fetch_table"),
ToolMetadata(description="Issue a natural language query over the document, and fetch relevant chunks.",
name="retrieve"),
]
# choices as a list of strings
# choices = ["fetch_pages", "fetch_sections", "fetch_figure", "fetch_table", "retrieve"]
selector = LLMSingleSelector.from_defaults()
result = selector.select(choices, query=query).selections
flag = result[0].index
print(flag)
if flag == 0: | content = fetch_pages(query=query) | 1 | 2023-10-30 14:36:23+00:00 | 2k |
zhanggang001/HEDNet | pcdet/models/backbones_3d/vfe/dynamic_voxel_vfe.py | [
{
"identifier": "VFETemplate",
"path": "pcdet/models/backbones_3d/vfe/vfe_template.py",
"snippet": "class VFETemplate(nn.Module):\n def __init__(self, model_cfg, **kwargs):\n super().__init__()\n self.model_cfg = model_cfg\n\n def get_output_feature_dim(self):\n raise NotImple... | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch_scatter
from .vfe_template import VFETemplate
from .dynamic_pillar_vfe import PFNLayerV2 | 746 |
try:
except Exception as e:
# Incase someone doesn't want to use dynamic pillar vfe and hasn't installed torch_scatter
pass
class DynamicVoxelVFE(VFETemplate):
def __init__(self, model_cfg, num_point_features, voxel_size, grid_size, point_cloud_range, **kwargs):
super().__init__(model_cfg=model_cfg)
self.use_norm = self.model_cfg.USE_NORM
self.with_distance = self.model_cfg.WITH_DISTANCE
self.use_absolute_xyz = self.model_cfg.USE_ABSLOTE_XYZ
num_point_features += 6 if self.use_absolute_xyz else 3
if self.with_distance:
num_point_features += 1
self.num_filters = self.model_cfg.NUM_FILTERS
assert len(self.num_filters) > 0
num_filters = [num_point_features] + list(self.num_filters)
pfn_layers = []
for i in range(len(num_filters) - 1):
in_filters = num_filters[i]
out_filters = num_filters[i + 1]
pfn_layers.append(
|
try:
except Exception as e:
# Incase someone doesn't want to use dynamic pillar vfe and hasn't installed torch_scatter
pass
class DynamicVoxelVFE(VFETemplate):
def __init__(self, model_cfg, num_point_features, voxel_size, grid_size, point_cloud_range, **kwargs):
super().__init__(model_cfg=model_cfg)
self.use_norm = self.model_cfg.USE_NORM
self.with_distance = self.model_cfg.WITH_DISTANCE
self.use_absolute_xyz = self.model_cfg.USE_ABSLOTE_XYZ
num_point_features += 6 if self.use_absolute_xyz else 3
if self.with_distance:
num_point_features += 1
self.num_filters = self.model_cfg.NUM_FILTERS
assert len(self.num_filters) > 0
num_filters = [num_point_features] + list(self.num_filters)
pfn_layers = []
for i in range(len(num_filters) - 1):
in_filters = num_filters[i]
out_filters = num_filters[i + 1]
pfn_layers.append( | PFNLayerV2(in_filters, out_filters, self.use_norm, last_layer=(i >= len(num_filters) - 2)) | 1 | 2023-10-25 02:57:35+00:00 | 2k |
deepsearch-ai/deepsearch | deepsearchai/tests/sources/test_local.py | [
{
"identifier": "MEDIA_TYPE",
"path": "deepsearchai/enums.py",
"snippet": "class MEDIA_TYPE(Enum):\n UNKNOWN = -1\n IMAGE = 1\n TEXT = 2\n AUDIO = 3\n VIDEO = 4"
},
{
"identifier": "DataSource",
"path": "deepsearchai/sources/data_source.py",
"snippet": "class DataSource(En... | import unittest
import mock.mock
from unittest import mock
from unittest.mock import patch
from deepsearchai.enums import MEDIA_TYPE
from deepsearchai.sources.data_source import DataSource
from deepsearchai.sources.local import LocalDataSource | 862 |
class LocalDataSourceTest(unittest.TestCase):
def setUp(self):
self.local_data_source = LocalDataSource()
@patch("os.walk")
@patch("PIL.Image.open")
def test_add_data_image_directory_with_no_existing_files(
self, mock_image_file, mock_listdir
):
embedding_models_config = mock.Mock()
embedding_model = mock.Mock()
embedding_models_config.get_embedding_model.return_value = [embedding_model]
# Create a mock image file
image_data = mock.Mock()
mock_listdir.return_value = [
("test_directory", "", ["image1.jpg", "image2.png"])
]
mock_image_file.return_value = image_data
# Create a mock vector database
vector_database = mock.Mock()
vector_database.get_existing_document_ids.return_value = []
# Add local datasource data for a local directory
directory = "test_directory"
self.local_data_source.add_data(
directory, embedding_models_config, vector_database
)
assert vector_database.add.mock_calls == [
mock.call(
image_data,
|
class LocalDataSourceTest(unittest.TestCase):
def setUp(self):
self.local_data_source = LocalDataSource()
@patch("os.walk")
@patch("PIL.Image.open")
def test_add_data_image_directory_with_no_existing_files(
self, mock_image_file, mock_listdir
):
embedding_models_config = mock.Mock()
embedding_model = mock.Mock()
embedding_models_config.get_embedding_model.return_value = [embedding_model]
# Create a mock image file
image_data = mock.Mock()
mock_listdir.return_value = [
("test_directory", "", ["image1.jpg", "image2.png"])
]
mock_image_file.return_value = image_data
# Create a mock vector database
vector_database = mock.Mock()
vector_database.get_existing_document_ids.return_value = []
# Add local datasource data for a local directory
directory = "test_directory"
self.local_data_source.add_data(
directory, embedding_models_config, vector_database
)
assert vector_database.add.mock_calls == [
mock.call(
image_data, | DataSource.LOCAL, | 1 | 2023-10-27 06:46:22+00:00 | 2k |
jerpint/RAGTheDocs | app.py | [
{
"identifier": "embed_documents",
"path": "embed_docs.py",
"snippet": "def embed_documents(homepage_url, save_directory, target_version=None):\n # adds https:// and trailing slash\n homepage_url = sanitize_url(homepage_url)\n\n # Crawl the website using scrapy\n run_spider(\n homepag... | import os
import gradio as gr
import pandas as pd
import cfg
from typing import Optional, Tuple
from buster.completers import Completion
from embed_docs import embed_documents
from cfg import setup_buster | 922 |
# from embed_docs import embed_rtd_website
# from rtd_scraper.scrape_rtd import scrape_rtd
# Typehint for chatbot history
ChatHistory = list[list[Optional[str], Optional[str]]]
# Because this is a one-click deploy app, we will be relying on env. variables being set
openai_api_key = os.getenv("OPENAI_API_KEY") # Mandatory for app to work
readthedocs_url = os.getenv("READTHEDOCS_URL") # Mandatory for app to work as intended
readthedocs_version = os.getenv("READTHEDOCS_VERSION")
if openai_api_key is None:
print(
"Warning: No OPENAI_API_KEY detected. Set it with 'export OPENAI_API_KEY=sk-...'."
)
if readthedocs_url is None:
raise ValueError(
"No READTHEDOCS_URL detected. Set it with e.g. 'export READTHEDOCS_URL=https://orion.readthedocs.io/'"
)
if readthedocs_version is None:
print(
"""
Warning: No READTHEDOCS_VERSION detected. If multiple versions of the docs exist, they will all be scraped.
Set it with e.g. 'export READTHEDOCS_VERSION=en/stable'
"""
)
# Override to put it anywhere
save_directory = "outputs/"
# scrape and embed content from readthedocs website
# You only need to embed the first time the app runs, comment it out to skip
|
# from embed_docs import embed_rtd_website
# from rtd_scraper.scrape_rtd import scrape_rtd
# Typehint for chatbot history
ChatHistory = list[list[Optional[str], Optional[str]]]
# Because this is a one-click deploy app, we will be relying on env. variables being set
openai_api_key = os.getenv("OPENAI_API_KEY") # Mandatory for app to work
readthedocs_url = os.getenv("READTHEDOCS_URL") # Mandatory for app to work as intended
readthedocs_version = os.getenv("READTHEDOCS_VERSION")
if openai_api_key is None:
print(
"Warning: No OPENAI_API_KEY detected. Set it with 'export OPENAI_API_KEY=sk-...'."
)
if readthedocs_url is None:
raise ValueError(
"No READTHEDOCS_URL detected. Set it with e.g. 'export READTHEDOCS_URL=https://orion.readthedocs.io/'"
)
if readthedocs_version is None:
print(
"""
Warning: No READTHEDOCS_VERSION detected. If multiple versions of the docs exist, they will all be scraped.
Set it with e.g. 'export READTHEDOCS_VERSION=en/stable'
"""
)
# Override to put it anywhere
save_directory = "outputs/"
# scrape and embed content from readthedocs website
# You only need to embed the first time the app runs, comment it out to skip | embed_documents( | 0 | 2023-10-31 03:36:43+00:00 | 2k |
Paulo-Lopes-Estevao/ci-generator | cigen/core/github/nodejs_action.py | [
{
"identifier": "Steps",
"path": "cigen/core/github/github_action.py",
"snippet": "class Steps:\n def __init__(self, steps: list[dict]) -> None:\n self.steps = steps\n\n def to_dict(self) -> list[dict]:\n return self.steps\n\n def add(self, step: dict) -> None:\n self.steps... | from abc import ABC, abstractmethod
from cigen.core.github.github_action import Steps, Action | 792 | from __future__ import annotations
class NodejsActionBuilder(ABC):
@property
@abstractmethod
def build(self) -> Action:
pass
@property
@abstractmethod
def build_steps(self) -> NodejsActionSteps:
pass
@abstractmethod
def base(self) -> None:
pass
@abstractmethod
def base_version_list(self) -> None:
pass
def add_steps(self, step):
pass
@abstractmethod
def base_to_yaml(self) -> None:
pass
@abstractmethod
def run(self) -> None:
pass
@abstractmethod
def run_with_env(self) -> None:
pass
@abstractmethod
def step_checkout(self) -> None:
pass
@abstractmethod
def step_setup_node(self) -> None:
pass
@abstractmethod
def step_setup_node_with_version_matrix(self) -> None:
pass
@abstractmethod
def step_install_dependencies(self) -> None:
pass
@abstractmethod
def step_build(self) -> None:
pass
@abstractmethod
def step_test(self) -> None:
pass
@abstractmethod
def step_publish(self) -> None:
pass
@abstractmethod
def step_publish_with_tag(self) -> None:
pass
@abstractmethod
def step_publish_with_access(self) -> None:
pass
@abstractmethod
def step_security_scan(self) -> None:
pass
@abstractmethod
def step_run_cache(self) -> None:
pass
class NodejsActionBuilderImpl(NodejsActionBuilder):
def __init__(self, name, version, on, env=None) -> None:
self._steps = None
self._build = None
self.name = name
self.version = version
self.on = on
self.env = env
| from __future__ import annotations
class NodejsActionBuilder(ABC):
@property
@abstractmethod
def build(self) -> Action:
pass
@property
@abstractmethod
def build_steps(self) -> NodejsActionSteps:
pass
@abstractmethod
def base(self) -> None:
pass
@abstractmethod
def base_version_list(self) -> None:
pass
def add_steps(self, step):
pass
@abstractmethod
def base_to_yaml(self) -> None:
pass
@abstractmethod
def run(self) -> None:
pass
@abstractmethod
def run_with_env(self) -> None:
pass
@abstractmethod
def step_checkout(self) -> None:
pass
@abstractmethod
def step_setup_node(self) -> None:
pass
@abstractmethod
def step_setup_node_with_version_matrix(self) -> None:
pass
@abstractmethod
def step_install_dependencies(self) -> None:
pass
@abstractmethod
def step_build(self) -> None:
pass
@abstractmethod
def step_test(self) -> None:
pass
@abstractmethod
def step_publish(self) -> None:
pass
@abstractmethod
def step_publish_with_tag(self) -> None:
pass
@abstractmethod
def step_publish_with_access(self) -> None:
pass
@abstractmethod
def step_security_scan(self) -> None:
pass
@abstractmethod
def step_run_cache(self) -> None:
pass
class NodejsActionBuilderImpl(NodejsActionBuilder):
def __init__(self, name, version, on, env=None) -> None:
self._steps = None
self._build = None
self.name = name
self.version = version
self.on = on
self.env = env | self.step = Steps([]) | 0 | 2023-10-31 03:36:36+00:00 | 2k |
TheCompAce/ShellSpeak | modules/llm.py | [
{
"identifier": "get_token_count",
"path": "modules/utils.py",
"snippet": "def get_token_count(text, token_adjust=1):\n # Define the maximum length for a text chunk\n max_length = 1000000\n\n # Initialize the total token count\n total_token_count = 0\n\n # Split the text into chunks of up... | from enum import Enum
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
from concurrent.futures import ThreadPoolExecutor
from modules.utils import get_token_count
from modules.responseCache import ResponseCache
import json
import sqlite3
import os
import torch
import transformers
import requests
import asyncio | 1,430 |
transformers.logging.set_verbosity_error()
executor = ThreadPoolExecutor()
class ModelTypes(Enum):
OpenAI = "OpenAI"
OpenAI4 = "OpenAI4"
Mistral = "Mistral"
StableBeluga7B = "StableBeluga7B"
Zephyr7bAlpha = "Zephyr7bAlpha"
Zephyr7bBeta = "Zephyr7bBeta"
Falcon7BInst = "Falcon7BInst"
class LLM:
def __init__(self, model_type, use_cache=False, cache_file=None):
self.ClearModel(model_type)
self.use_cache = use_cache
if use_cache:
self.cache = ResponseCache(cache_file)
def ClearModel(self, model_type):
self.model = ModelTypes(model_type)
self.modelObj = None
self.tokenizerObj = None
self.pipeObj = None
def SetupModel(self):
if self.model == ModelTypes.Mistral:
return self._setup_mistral()
elif self.model == ModelTypes.StableBeluga7B:
return self._setup_beluga_7b()
elif self.model == ModelTypes.Zephyr7bAlpha:
return self._setup_zephyr_7b()
elif self.model == ModelTypes.Zephyr7bBeta:
return self._setup_zephyr_7bB()
async def async_ask(llm, system_prompt, user_prompt, model_type=None, max_tokens=4096, return_type="text"):
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(executor, llm.ask, system_prompt, user_prompt, model_type, max_tokens, return_type)
return response
def ask(self, system_prompt, user_prompt, model_type=None, max_tokens=4096, return_type="text"):
if self.use_cache:
cached_response = self.cache.get(system_prompt, user_prompt)
if cached_response:
return cached_response
response = self._ask(system_prompt, user_prompt, model_type, max_tokens, return_type)
if self.use_cache:
self.cache.set(system_prompt, user_prompt, response)
return response
def _ask(self, system_prompt, user_prompt, model_type = None, max_tokens=4096, return_type="text"):
if model_type is None:
model_type = self.model
elif model_type is not self.model:
self.ClearModel(model_type)
if model_type == ModelTypes.OpenAI:
return self._ask_openai(system_prompt, user_prompt, max_tokens=16000, return_type=return_type)
elif model_type == ModelTypes.OpenAI4:
return self._ask_openai(system_prompt, user_prompt, model="gpt-4-1106-preview", max_tokens=140000, return_type=return_type)
elif model_type == ModelTypes.Mistral:
return self._ask_mistral(system_prompt, user_prompt)
elif model_type == ModelTypes.StableBeluga7B:
return self._ask_stable_beluga_7b(system_prompt, user_prompt)
elif model_type == ModelTypes.Zephyr7bAlpha:
return self._ask_zephyr_7b(system_prompt, user_prompt)
elif model_type == ModelTypes.Zephyr7bBeta:
return self._ask_zephyr_7bB(system_prompt, user_prompt)
elif model_type == ModelTypes.Falcon7BInst:
return self._ask_falcon_7b_instruct(system_prompt, user_prompt)
def _ask_openai(self, system_prompt, user_prompt, model = "gpt-3.5-turbo-1106", max_tokens=16000, return_type="text"):
# Placeholder for actual OpenAI API request
# Uncomment and complete the following code in your local environment
api_key = os.environ.get("OPENAI_API_KEY", "your-default-openai-api-key-here")
api_url = "https://api.openai.com/v1/chat/completions"
token_ct = 0
|
transformers.logging.set_verbosity_error()
executor = ThreadPoolExecutor()
class ModelTypes(Enum):
OpenAI = "OpenAI"
OpenAI4 = "OpenAI4"
Mistral = "Mistral"
StableBeluga7B = "StableBeluga7B"
Zephyr7bAlpha = "Zephyr7bAlpha"
Zephyr7bBeta = "Zephyr7bBeta"
Falcon7BInst = "Falcon7BInst"
class LLM:
def __init__(self, model_type, use_cache=False, cache_file=None):
self.ClearModel(model_type)
self.use_cache = use_cache
if use_cache:
self.cache = ResponseCache(cache_file)
def ClearModel(self, model_type):
self.model = ModelTypes(model_type)
self.modelObj = None
self.tokenizerObj = None
self.pipeObj = None
def SetupModel(self):
if self.model == ModelTypes.Mistral:
return self._setup_mistral()
elif self.model == ModelTypes.StableBeluga7B:
return self._setup_beluga_7b()
elif self.model == ModelTypes.Zephyr7bAlpha:
return self._setup_zephyr_7b()
elif self.model == ModelTypes.Zephyr7bBeta:
return self._setup_zephyr_7bB()
async def async_ask(llm, system_prompt, user_prompt, model_type=None, max_tokens=4096, return_type="text"):
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(executor, llm.ask, system_prompt, user_prompt, model_type, max_tokens, return_type)
return response
def ask(self, system_prompt, user_prompt, model_type=None, max_tokens=4096, return_type="text"):
if self.use_cache:
cached_response = self.cache.get(system_prompt, user_prompt)
if cached_response:
return cached_response
response = self._ask(system_prompt, user_prompt, model_type, max_tokens, return_type)
if self.use_cache:
self.cache.set(system_prompt, user_prompt, response)
return response
def _ask(self, system_prompt, user_prompt, model_type = None, max_tokens=4096, return_type="text"):
if model_type is None:
model_type = self.model
elif model_type is not self.model:
self.ClearModel(model_type)
if model_type == ModelTypes.OpenAI:
return self._ask_openai(system_prompt, user_prompt, max_tokens=16000, return_type=return_type)
elif model_type == ModelTypes.OpenAI4:
return self._ask_openai(system_prompt, user_prompt, model="gpt-4-1106-preview", max_tokens=140000, return_type=return_type)
elif model_type == ModelTypes.Mistral:
return self._ask_mistral(system_prompt, user_prompt)
elif model_type == ModelTypes.StableBeluga7B:
return self._ask_stable_beluga_7b(system_prompt, user_prompt)
elif model_type == ModelTypes.Zephyr7bAlpha:
return self._ask_zephyr_7b(system_prompt, user_prompt)
elif model_type == ModelTypes.Zephyr7bBeta:
return self._ask_zephyr_7bB(system_prompt, user_prompt)
elif model_type == ModelTypes.Falcon7BInst:
return self._ask_falcon_7b_instruct(system_prompt, user_prompt)
def _ask_openai(self, system_prompt, user_prompt, model = "gpt-3.5-turbo-1106", max_tokens=16000, return_type="text"):
# Placeholder for actual OpenAI API request
# Uncomment and complete the following code in your local environment
api_key = os.environ.get("OPENAI_API_KEY", "your-default-openai-api-key-here")
api_url = "https://api.openai.com/v1/chat/completions"
token_ct = 0 | token_ct = max_tokens - int(get_token_count(system_prompt + "\n" + user_prompt) + 20) | 0 | 2023-10-31 23:35:19+00:00 | 2k |
qym7/SparseDiff | sparse_diffusion/models/transconv_layer.py | [
{
"identifier": "SparseXtoy",
"path": "sparse_diffusion/models/layers.py",
"snippet": "class SparseXtoy(nn.Module):\n def __init__(self, dx, dy):\n \"\"\"Map node features to global features\"\"\"\n super().__init__()\n self.lin = nn.Linear(4 * dx, dy)\n\n def forward(self, X,... | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, Tuple, Union
from torch import Tensor
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.dense.linear import Linear
from torch_geometric.typing import Adj, OptTensor, Size
from torch_geometric.utils import softmax
from sparse_diffusion.models.layers import SparseXtoy, SparseEtoy | 1,359 |
class TransformerConv(MessagePassing):
r"""The graph transformer operator from the `"Masked Label Prediction:
Unified Message Passing Model for Semi-Supervised Classification"
<https://arxiv.org/abs/2009.03509>`_ paper
.. math::
\mathbf{x}^{\prime}_i = \mathbf{W}_1 \mathbf{x}_i +
\sum_{j \in \mathcal{N}(i)} \alpha_{i,j} \mathbf{W}_2 \mathbf{x}_{j},
where the attention coefficients :math:`\alpha_{i,j}` are computed via
multi-head dot product attention:
.. math::
\alpha_{i,j} = \textrm{softmax} \left(
\frac{(\mathbf{W}_3\mathbf{x}_i)^{\top} (\mathbf{W}_4\mathbf{x}_j)}
{\sqrt{d}} \right)
"""
_alpha: OptTensor
def __init__(
self,
dx: int,
de: int,
dy: int,
heads: int = 1,
concat: bool = True,
dropout: float = 0.0,
bias: bool = True,
last_layer: bool = True,
**kwargs,
):
kwargs.setdefault("aggr", "add")
super().__init__(node_dim=0, **kwargs)
self.dx = dx
self.de = de
self.dy = dy
self.df = int(dx / heads)
self.heads = heads
self.concat = concat
self.dropout = dropout
self.last_layer = last_layer
self.lin_key = Linear(dx, heads * self.df)
self.lin_query = Linear(dx, heads * self.df)
self.lin_value = Linear(dx, heads * self.df)
if concat:
self.lin_skip = Linear(dx, heads * self.df, bias=bias)
else:
self.lin_skip = Linear(dx, self.df, bias=bias)
# FiLM E to X: de = dx here as defined in lin_edge
self.e_add = Linear(de, heads)
self.e_mul = Linear(de, heads)
# FiLM y to E
self.y_e_mul = Linear(dy, de)
self.y_e_add = Linear(dy, de)
# FiLM y to X
self.y_x_mul = Linear(dy, dx)
self.y_x_add = Linear(dy, dx)
# Process y
if self.last_layer:
self.y_y = Linear(dy, dy)
self.x_y = SparseXtoy(dx, dy)
|
class TransformerConv(MessagePassing):
r"""The graph transformer operator from the `"Masked Label Prediction:
Unified Message Passing Model for Semi-Supervised Classification"
<https://arxiv.org/abs/2009.03509>`_ paper
.. math::
\mathbf{x}^{\prime}_i = \mathbf{W}_1 \mathbf{x}_i +
\sum_{j \in \mathcal{N}(i)} \alpha_{i,j} \mathbf{W}_2 \mathbf{x}_{j},
where the attention coefficients :math:`\alpha_{i,j}` are computed via
multi-head dot product attention:
.. math::
\alpha_{i,j} = \textrm{softmax} \left(
\frac{(\mathbf{W}_3\mathbf{x}_i)^{\top} (\mathbf{W}_4\mathbf{x}_j)}
{\sqrt{d}} \right)
"""
_alpha: OptTensor
def __init__(
self,
dx: int,
de: int,
dy: int,
heads: int = 1,
concat: bool = True,
dropout: float = 0.0,
bias: bool = True,
last_layer: bool = True,
**kwargs,
):
kwargs.setdefault("aggr", "add")
super().__init__(node_dim=0, **kwargs)
self.dx = dx
self.de = de
self.dy = dy
self.df = int(dx / heads)
self.heads = heads
self.concat = concat
self.dropout = dropout
self.last_layer = last_layer
self.lin_key = Linear(dx, heads * self.df)
self.lin_query = Linear(dx, heads * self.df)
self.lin_value = Linear(dx, heads * self.df)
if concat:
self.lin_skip = Linear(dx, heads * self.df, bias=bias)
else:
self.lin_skip = Linear(dx, self.df, bias=bias)
# FiLM E to X: de = dx here as defined in lin_edge
self.e_add = Linear(de, heads)
self.e_mul = Linear(de, heads)
# FiLM y to E
self.y_e_mul = Linear(dy, de)
self.y_e_add = Linear(dy, de)
# FiLM y to X
self.y_x_mul = Linear(dy, dx)
self.y_x_add = Linear(dy, dx)
# Process y
if self.last_layer:
self.y_y = Linear(dy, dy)
self.x_y = SparseXtoy(dx, dy) | self.e_y = SparseEtoy(de, dy) | 1 | 2023-10-30 12:12:16+00:00 | 2k |
ZhangLin-PKU/FedFTG | train.py | [
{
"identifier": "util_dataset",
"path": "utils/util_dataset.py",
"snippet": "COLOR_MAP = ['red', 'green', 'blue', 'black', 'brown', 'purple', 'yellow', 'pink', 'cyan', 'gray']\r\nclass DatasetObject:\r\nclass Dataset(torch.utils.data.Dataset):\r\nclass DatasetFromDir(data.Dataset):\r\n def __init__(s... | from utils import util_dataset, util_parser
from models import model_choose_fn
from methods import FedAvg, FedProx, SCAFFOLD, MOON, FedDyn
from methods import FedFTG, FedProxGAN, SCAFFOLDGAN, MOONGAN, FedDynGAN
import torch
import os
import random
import numpy as np
import matplotlib.pyplot as plt
| 1,537 |
def run(conf):
print('Init-------------------------')
root_path = os.getcwd()
# print(root_path)
if root_path.endswith('scripts'):
root_path = os.path.dirname(root_path)
conf['savepath'] = os.path.join(root_path, conf['savepath'].strip())
print('Data and results save path is: ', conf['savepath'])
######################################################
# Provide reproducibility
torch.manual_seed(conf['seed'])
random.seed(conf['seed'])
np.random.seed(conf['seed'])
in_channel = 3
out_channel = 10
######################################################
# Split the dataset
|
def run(conf):
print('Init-------------------------')
root_path = os.getcwd()
# print(root_path)
if root_path.endswith('scripts'):
root_path = os.path.dirname(root_path)
conf['savepath'] = os.path.join(root_path, conf['savepath'].strip())
print('Data and results save path is: ', conf['savepath'])
######################################################
# Provide reproducibility
torch.manual_seed(conf['seed'])
random.seed(conf['seed'])
np.random.seed(conf['seed'])
in_channel = 3
out_channel = 10
######################################################
# Split the dataset
| data_obj = util_dataset.DatasetObject(dataset=conf['dataset'],
| 0 | 2023-10-26 03:35:17+00:00 | 2k |
Shou-Hsu/Report.ai | summarize.py | [
{
"identifier": "convert_json",
"path": "utils.py",
"snippet": "def convert_json(txt:str, item_list:list) -> str:\n txt = txt.replace('\\n', '').replace('#', '')\n\n output = dict()\n for i in range(len(item_list)):\n start = txt.lower().find(item_list[i].lower() + ':')\n\n if i !... | from langchain.chains.combine_documents.stuff import StuffDocumentsChain
from utils import convert_json, get_items
from langchain.docstore.document import Document
from langchain.prompts import PromptTemplate
from langchain.chains.llm import LLMChain
from tqdm import tqdm
from utils import llm
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.chains.summarize import load_summarize_chain
from langchain.chains.combine_documents.stuff import StuffDocumentsChain
from langchain.docstore.document import Document
from langchain.prompts import PromptTemplate
from langchain.chains.llm import LLMChain
from langdetect import detect_langs
from utils import add_hyperlink, divide_audio
import json
import docx, datetime | 669 |
class generate_summary():
def __init__(self, file_name:str, original_language:str, translated_language:str, chunk_size:int, output_dir:str) -> None:
self.file_name = file_name
self.chunk_size = chunk_size
self.original_language = original_language
self.translated_language = translated_language
self.output_dir = output_dir
self.llm = llm
def _get_general_summary(self, article_divided:dict) -> None:
text_splitter = RecursiveCharacterTextSplitter(
chunk_size = self.chunk_size//2,
chunk_overlap = 0,
length_function = len)
# load transcript
with open(f'./transcript/{self.file_name}.txt', 'r') as f:
transcript = ''.join(f.readlines())
split_text = text_splitter.split_text(transcript)
|
class generate_summary():
def __init__(self, file_name:str, original_language:str, translated_language:str, chunk_size:int, output_dir:str) -> None:
self.file_name = file_name
self.chunk_size = chunk_size
self.original_language = original_language
self.translated_language = translated_language
self.output_dir = output_dir
self.llm = llm
def _get_general_summary(self, article_divided:dict) -> None:
text_splitter = RecursiveCharacterTextSplitter(
chunk_size = self.chunk_size//2,
chunk_overlap = 0,
length_function = len)
# load transcript
with open(f'./transcript/{self.file_name}.txt', 'r') as f:
transcript = ''.join(f.readlines())
split_text = text_splitter.split_text(transcript)
| item_list, items, item_format = get_items('general') | 1 | 2023-10-30 12:29:20+00:00 | 2k |
Thinksy-app/thinksy | app/review_ops.py | [
{
"identifier": "SYSTEM_TEXT",
"path": "app/env.py",
"snippet": "SYSTEM_TEXT = os.environ.get(\"OPENAI_SYSTEM_TEXT\", DEFAULT_SYSTEM_TEXT)"
},
{
"identifier": "fetch_channel_messages",
"path": "app/slack_ops.py",
"snippet": "def fetch_channel_messages(\n client: WebClient,\n user: ... | from datetime import datetime
from slack_sdk import WebClient
from app.env import (
SYSTEM_TEXT,
)
from app.slack_ops import fetch_channel_messages, filter_non_membership_and_join
from app.openai_ops import make_synchronous_openai_call
import json
import re | 1,105 | """
Business logic writing the reviews
"""
def generate_review(context, user: str, web_client: WebClient, selected_conversations, start_date, end_date, logger):
"""
Generates the review based on the user's criteria
Parameters:
user (str): The user ID from Slack
slack_enc_team_id (str): The team ID from Slack
Returns:
dict: The payload for setting up review criteria
"""
filter_non_membership_and_join(web_client, logger, selected_conversations)
start_date_num = datetime.strptime(start_date, "%Y-%m-%d")
end_date_num = datetime.strptime(end_date, "%Y-%m-%d")
slack_messages = fetch_channel_messages(web_client, user, selected_conversations, start_date_num, end_date_num)
messages = [
{
"role": "system",
| """
Business logic writing the reviews
"""
def generate_review(context, user: str, web_client: WebClient, selected_conversations, start_date, end_date, logger):
"""
Generates the review based on the user's criteria
Parameters:
user (str): The user ID from Slack
slack_enc_team_id (str): The team ID from Slack
Returns:
dict: The payload for setting up review criteria
"""
filter_non_membership_and_join(web_client, logger, selected_conversations)
start_date_num = datetime.strptime(start_date, "%Y-%m-%d")
end_date_num = datetime.strptime(end_date, "%Y-%m-%d")
slack_messages = fetch_channel_messages(web_client, user, selected_conversations, start_date_num, end_date_num)
messages = [
{
"role": "system", | "content": SYSTEM_TEXT | 0 | 2023-10-26 23:47:28+00:00 | 2k |
CrystalWindSnake/nicegui-toolkit | __tests/test_componentStore.py | [
{
"identifier": "ComponentStore",
"path": "niceguiToolkit/layout/componentStore.py",
"snippet": "class ComponentStore:\n def __init__(self) -> None:\n self.cpMapper: Dict[_TNiceguiComponentId, ComponentInfo] = {}\n self._styles_records: Set[_TNiceguiComponentId] = set()\n self._c... | from niceguiToolkit.layout.componentStore import ComponentStore
from niceguiToolkit.utils import astCore
from .utils import get_data_file | 1,464 |
def test_create_new_style_call():
mock_code_file = get_data_file("code1.py")
exp_file = get_data_file("code1_exp.txt")
store = ComponentStore()
|
def test_create_new_style_call():
mock_code_file = get_data_file("code1.py")
exp_file = get_data_file("code1_exp.txt")
store = ComponentStore()
| entry_info = astCore._T_entry_point_info( | 1 | 2023-10-27 13:50:03+00:00 | 2k |
EnVision-Research/Defect_Spectrum | models/stylegan/mapper.py | [
{
"identifier": "EqualLinear",
"path": "models/stylegan/modules.py",
"snippet": "class EqualLinear(nn.Module):\r\n def __init__(\r\n self, in_dim, out_dim, bias=True, bias_init=0, lr_mul=1, activation=None\r\n ):\r\n super().__init__()\r\n\r\n self.weight = nn.Parameter(torch.... | from abc import abstractmethod
from torch import nn
from models.stylegan.modules import EqualLinear, PixelNorm
import torch | 1,149 |
STYLESPACE_DIMENSIONS = [512 for _ in range(15)] + [256, 256, 256] + [128, 128, 128] + [64, 64, 64] + [32, 32]
class ConcatSquashLinear(nn.Module):
def __init__(self, dim_in, dim_out, dim_ctx):
super(ConcatSquashLinear, self).__init__()
self._layer = EqualLinear(dim_in, dim_out, lr_mul=0.01, activation='fused_lrelu')
self._hyper_bias = EqualLinear(dim_ctx, dim_out, lr_mul=0.01, activation='fused_lrelu')
self._hyper_gate = EqualLinear(dim_ctx, dim_out, lr_mul=0.01, activation='fused_lrelu')
def forward(self, x, ctx):
gate = torch.sigmoid(self._hyper_gate(ctx))
bias = self._hyper_bias(ctx)
# if x.dim() == 3:
# gate = gate.unsqueeze(1)
# bias = bias.unsqueeze(1)
ret = self._layer(x) * gate + bias
return ret
class TimeStyleSpaceMapper(nn.Module):
def __init__(self, dim_ctx):
super(TimeStyleSpaceMapper, self).__init__()
for c, c_dim in enumerate(STYLESPACE_DIMENSIONS):
setattr(self, f"mapper_{c}", ConcatSquashLinear(dim_in=c_dim, dim_out=c_dim, dim_ctx=dim_ctx+3))
def forward(self, x, beta, context):
batch_size = x.size(0)
beta = beta.view(batch_size, 1, 1) # (B, 1, 1)
context = context.view(batch_size, 1, -1) # (B, 1, F)
time_emb = torch.cat([beta, torch.sin(beta), torch.cos(beta)], dim=-1) # (B, 1, 3)
ctx_emb = torch.cat([time_emb, context], dim=-1) # (B, 1, F+3)
out = []
for c, c_dim in enumerate(STYLESPACE_DIMENSIONS):
curr_mapper = getattr(self, f"mapper_{c}")
x_c = x[:, :, sum(STYLESPACE_DIMENSIONS[:c]):sum(STYLESPACE_DIMENSIONS[:c])+c_dim]
# (B, 1, 512*15 + 256*3 + 128*3 + 64*3 + 32*2)
x_c_res = curr_mapper(x_c, ctx_emb).view(x_c.shape)
out.append(x_c_res)
return torch.cat(out, dim=-1)
class TimestepBlock(nn.Module):
"""
Any module where forward() takes timestep embeddings as a second argument.
"""
@abstractmethod
def forward(self, x, emb):
"""
Apply the module to `x` given `emb` timestep embeddings.
"""
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
"""
A sequential module that passes timestep embeddings to the children that
support it as an extra input.
"""
def forward(self, x, emb):
for layer in self:
if isinstance(layer, TimestepBlock):
x = layer(x, emb)
else:
x = layer(x)
return x
class Mapper(nn.Module):
def __init__(self, opts, latent_dim=512):
super(Mapper, self).__init__()
self.opts = opts
|
STYLESPACE_DIMENSIONS = [512 for _ in range(15)] + [256, 256, 256] + [128, 128, 128] + [64, 64, 64] + [32, 32]
class ConcatSquashLinear(nn.Module):
def __init__(self, dim_in, dim_out, dim_ctx):
super(ConcatSquashLinear, self).__init__()
self._layer = EqualLinear(dim_in, dim_out, lr_mul=0.01, activation='fused_lrelu')
self._hyper_bias = EqualLinear(dim_ctx, dim_out, lr_mul=0.01, activation='fused_lrelu')
self._hyper_gate = EqualLinear(dim_ctx, dim_out, lr_mul=0.01, activation='fused_lrelu')
def forward(self, x, ctx):
gate = torch.sigmoid(self._hyper_gate(ctx))
bias = self._hyper_bias(ctx)
# if x.dim() == 3:
# gate = gate.unsqueeze(1)
# bias = bias.unsqueeze(1)
ret = self._layer(x) * gate + bias
return ret
class TimeStyleSpaceMapper(nn.Module):
def __init__(self, dim_ctx):
super(TimeStyleSpaceMapper, self).__init__()
for c, c_dim in enumerate(STYLESPACE_DIMENSIONS):
setattr(self, f"mapper_{c}", ConcatSquashLinear(dim_in=c_dim, dim_out=c_dim, dim_ctx=dim_ctx+3))
def forward(self, x, beta, context):
batch_size = x.size(0)
beta = beta.view(batch_size, 1, 1) # (B, 1, 1)
context = context.view(batch_size, 1, -1) # (B, 1, F)
time_emb = torch.cat([beta, torch.sin(beta), torch.cos(beta)], dim=-1) # (B, 1, 3)
ctx_emb = torch.cat([time_emb, context], dim=-1) # (B, 1, F+3)
out = []
for c, c_dim in enumerate(STYLESPACE_DIMENSIONS):
curr_mapper = getattr(self, f"mapper_{c}")
x_c = x[:, :, sum(STYLESPACE_DIMENSIONS[:c]):sum(STYLESPACE_DIMENSIONS[:c])+c_dim]
# (B, 1, 512*15 + 256*3 + 128*3 + 64*3 + 32*2)
x_c_res = curr_mapper(x_c, ctx_emb).view(x_c.shape)
out.append(x_c_res)
return torch.cat(out, dim=-1)
class TimestepBlock(nn.Module):
"""
Any module where forward() takes timestep embeddings as a second argument.
"""
@abstractmethod
def forward(self, x, emb):
"""
Apply the module to `x` given `emb` timestep embeddings.
"""
class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
"""
A sequential module that passes timestep embeddings to the children that
support it as an extra input.
"""
def forward(self, x, emb):
for layer in self:
if isinstance(layer, TimestepBlock):
x = layer(x, emb)
else:
x = layer(x)
return x
class Mapper(nn.Module):
def __init__(self, opts, latent_dim=512):
super(Mapper, self).__init__()
self.opts = opts | layers = [PixelNorm()] | 1 | 2023-10-26 10:28:26+00:00 | 2k |
ORI-Muchim/BEGANSing | main.py | [
{
"identifier": "update_text_file_in_yaml",
"path": "main_util.py",
"snippet": "def update_text_file_in_yaml(yaml_path):\n yaml = YAML()\n yaml.preserve_quotes = True\n try:\n with open(yaml_path, 'r', encoding='utf-8') as file:\n data = yaml.load(file)\n\n current_text... | import os
import sys
import shutil
import argparse
from main_util import update_text_file_in_yaml, find_index_files
from get_models import get_model | 1,003 |
if len(sys.argv) < 4:
print("Usage: python main.py <model_name> <song_name> <f0_up_key> [--audiosr]")
sys.exit(1)
# Init
model_name = sys.argv[1]
song_name = sys.argv[2]
f0_up_key = int(sys.argv[3]) # transpose value
input_path = f"../samples/latest_G_{song_name}.wav"
output_path = f"../samples/latest_G_{song_name}.wav"
model_path = f"./weights/{model_name}.pth"
device = "cuda:0"
f0_method = "rmvpe" # pm or harvest or crepe or rmvpe
parser = argparse.ArgumentParser()
parser.add_argument('--audiosr', action='store_true', help='Enable audio processing')
args = parser.parse_args(sys.argv[4:])
yaml_path = "./config/default_infer.yml"
update_text_file_in_yaml(yaml_path)
# Download Necessary Models / Files
|
if len(sys.argv) < 4:
print("Usage: python main.py <model_name> <song_name> <f0_up_key> [--audiosr]")
sys.exit(1)
# Init
model_name = sys.argv[1]
song_name = sys.argv[2]
f0_up_key = int(sys.argv[3]) # transpose value
input_path = f"../samples/latest_G_{song_name}.wav"
output_path = f"../samples/latest_G_{song_name}.wav"
model_path = f"./weights/{model_name}.pth"
device = "cuda:0"
f0_method = "rmvpe" # pm or harvest or crepe or rmvpe
parser = argparse.ArgumentParser()
parser.add_argument('--audiosr', action='store_true', help='Enable audio processing')
args = parser.parse_args(sys.argv[4:])
yaml_path = "./config/default_infer.yml"
update_text_file_in_yaml(yaml_path)
# Download Necessary Models / Files | get_model() | 2 | 2023-10-29 09:32:19+00:00 | 2k |
Charl-AI/stochastic-caching | run_benchmark.py | [
{
"identifier": "DummyDataset",
"path": "benchmark/dataset.py",
"snippet": "class DummyDataset(Dataset):\n def __init__(self, data_dir: str, cache_limit_gib: int):\n \"\"\"PyTorch dataset for dummy data.\n No cache is used if cache_limit_gib is 0.\"\"\"\n self.data_dir = data_dir... | import argparse
import os
import pandas as pd
import torch
from torch.utils.data import DataLoader
from benchmark.dataset import DummyDataset
from benchmark.trainer import train | 889 |
parser = argparse.ArgumentParser()
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--data-dir", type=str, default="/data2/dummy_data")
parser.add_argument("--cache-limit-gib", type=int, default=0)
parser.add_argument("--batch-size", type=int, default=256)
parser.add_argument("--num-workers", type=int, default=8)
parser.add_argument("--pin-memory", type=bool, default=True)
parser.add_argument("--output-dir", type=str, default="outputs/")
NUM_EPOCHS = 2
def main(args):
# first epoch fills cache, second epoch uses cache
torch.manual_seed(args.seed)
|
parser = argparse.ArgumentParser()
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--data-dir", type=str, default="/data2/dummy_data")
parser.add_argument("--cache-limit-gib", type=int, default=0)
parser.add_argument("--batch-size", type=int, default=256)
parser.add_argument("--num-workers", type=int, default=8)
parser.add_argument("--pin-memory", type=bool, default=True)
parser.add_argument("--output-dir", type=str, default="outputs/")
NUM_EPOCHS = 2
def main(args):
# first epoch fills cache, second epoch uses cache
torch.manual_seed(args.seed) | dataset = DummyDataset(args.data_dir, args.cache_limit_gib) | 0 | 2023-10-27 09:33:43+00:00 | 2k |
hugoycj/light-hloc | lighthloc/pipeline.py | [
{
"identifier": "extract_features",
"path": "lighthloc/extract_features.py",
"snippet": "def resize_image(image, size, interp):\n def __init__(self, root, conf, paths=None):\n def __getitem__(self, idx):\n def __len__(self):\ndef main(conf: Dict,\n image_dir: Path,\n export_dir:... | from lighthloc import extract_features, match_features, reconstruction
from lighthloc.associators import pairs_from_retrieval, pairs_from_exhaustive, pairs_from_sequance
from pathlib import Path
import click | 1,377 | # To install hloc, see: https://github.com/cvg/Hierarchical-retrivalization
mapper_confs = {
'default' : {},
'fast' : {'ba_global_max_num_iterations': 20, "ba_global_max_refinements":1,
"ba_global_points_freq":200000}
}
@click.command()
@click.option('--data', type=str, help='Path to data directory')
@click.option('--match-type', default='retrival', help='Type of matching to perform (default: retrival)', type=click.Choice(['exhaustive', 'sequential', 'retrival']))
@click.option('--feature-type', default='superpoint_inloc', help='Type of feature extraction (default: superpoint_inloc)', type=click.Choice(['superpoint_inloc', 'superpoint_aachen']))
@click.option('--matcher-type', default='lightglue', help='Type of feature matching (default: lightglue)', type=click.Choice(['lightglue', 'lightglue_trt', 'superglue']))
@click.option('--mapper-type', default='default', help='Type of mapper (default: default)', type=click.Choice(['default', 'fast']))
def main(data, match_type, feature_type, matcher_type, mapper_type):
images = Path(data) / 'images/'
outputs = Path(data)
sfm_pairs = outputs / 'pairs-sfm.txt'
loc_pairs = outputs / 'pairs-loc.txt'
sfm_dir = outputs / 'sparse' / '0'
features = outputs / 'features.h5'
matches = outputs / 'matches.h5'
feature_conf = extract_features.confs[feature_type]
| # To install hloc, see: https://github.com/cvg/Hierarchical-retrivalization
mapper_confs = {
'default' : {},
'fast' : {'ba_global_max_num_iterations': 20, "ba_global_max_refinements":1,
"ba_global_points_freq":200000}
}
@click.command()
@click.option('--data', type=str, help='Path to data directory')
@click.option('--match-type', default='retrival', help='Type of matching to perform (default: retrival)', type=click.Choice(['exhaustive', 'sequential', 'retrival']))
@click.option('--feature-type', default='superpoint_inloc', help='Type of feature extraction (default: superpoint_inloc)', type=click.Choice(['superpoint_inloc', 'superpoint_aachen']))
@click.option('--matcher-type', default='lightglue', help='Type of feature matching (default: lightglue)', type=click.Choice(['lightglue', 'lightglue_trt', 'superglue']))
@click.option('--mapper-type', default='default', help='Type of mapper (default: default)', type=click.Choice(['default', 'fast']))
def main(data, match_type, feature_type, matcher_type, mapper_type):
images = Path(data) / 'images/'
outputs = Path(data)
sfm_pairs = outputs / 'pairs-sfm.txt'
loc_pairs = outputs / 'pairs-loc.txt'
sfm_dir = outputs / 'sparse' / '0'
features = outputs / 'features.h5'
matches = outputs / 'matches.h5'
feature_conf = extract_features.confs[feature_type] | matcher_conf = match_features.confs[matcher_type] | 1 | 2023-10-27 01:20:50+00:00 | 2k |
KUNLP/XAI_EvidenceExtraction | src/functions/utils.py | [
{
"identifier": "SquadV1Processor",
"path": "src/functions/processor_sent.py",
"snippet": "class SquadV1Processor(SquadProcessor):\r\n train_file = \"train-v1.1.json\"\r\n dev_file = \"dev-v1.1.json\"\r"
},
{
"identifier": "squad_convert_examples_to_features",
"path": "src/functions/pr... | import logging
import random
import torch
import numpy as np
import os
from src.functions.processor_sent import (
SquadV1Processor,
squad_convert_examples_to_features
)
| 1,277 |
def init_logger():
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if not args.no_cuda and torch.cuda.is_available():
torch.cuda.manual_seed_all(args.seed)
# tensor를 list 형으로 변환하기위한 함수
def to_list(tensor):
return tensor.detach().cpu().tolist()
# dataset을 load 하는 함수
def load_examples(args, tokenizer, evaluate=False, output_examples=False, do_predict=False, input_dict=None):
'''
:param args: 하이퍼 파라미터
:param tokenizer: tokenization에 사용되는 tokenizer
:param evaluate: 평가나 open test시, True
:param output_examples: 평가나 open test 시, True / True 일 경우, examples와 features를 같이 return
:param do_predict: open test시, True
:param input_dict: open test시 입력되는 문서와 질문으로 이루어진 dictionary
:return:
examples : max_length 상관 없이, 원문으로 각 데이터를 저장한 리스트
features : max_length에 따라 분할 및 tokenize된 원문 리스트
dataset : max_length에 따라 분할 및 학습에 직접적으로 사용되는 tensor 형태로 변환된 입력 ids
'''
input_dir = args.data_dir
print("Creating features from dataset file at {}".format(input_dir))
# processor 선언
|
def init_logger():
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S',
level=logging.INFO)
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if not args.no_cuda and torch.cuda.is_available():
torch.cuda.manual_seed_all(args.seed)
# tensor를 list 형으로 변환하기위한 함수
def to_list(tensor):
return tensor.detach().cpu().tolist()
# dataset을 load 하는 함수
def load_examples(args, tokenizer, evaluate=False, output_examples=False, do_predict=False, input_dict=None):
'''
:param args: 하이퍼 파라미터
:param tokenizer: tokenization에 사용되는 tokenizer
:param evaluate: 평가나 open test시, True
:param output_examples: 평가나 open test 시, True / True 일 경우, examples와 features를 같이 return
:param do_predict: open test시, True
:param input_dict: open test시 입력되는 문서와 질문으로 이루어진 dictionary
:return:
examples : max_length 상관 없이, 원문으로 각 데이터를 저장한 리스트
features : max_length에 따라 분할 및 tokenize된 원문 리스트
dataset : max_length에 따라 분할 및 학습에 직접적으로 사용되는 tensor 형태로 변환된 입력 ids
'''
input_dir = args.data_dir
print("Creating features from dataset file at {}".format(input_dir))
# processor 선언
| processor = SquadV1Processor()
| 0 | 2023-10-25 07:03:47+00:00 | 2k |
joenghl/HYPO | hypo/algo/hypo_bc.py | [
{
"identifier": "PPOPolicy",
"path": "hypo/network/policy.py",
"snippet": "class PPOPolicy(nn.Module):\n\n def __init__(self, state_shape, action_shape, hidden_units=(64, 64),\n hidden_activation=nn.Tanh()):\n super().__init__()\n\n self.net = build_mlp(\n inp... | from torch import nn
from torch.optim import Adam
from hypo.network import PPOPolicy
from .base import Algorithm
import torch | 768 |
class HBC(Algorithm):
def __init__(self, buffer_exp, state_shape, action_shape, device, seed, logger, gamma=0.995,
log_interval=1e3, lr_actor=3e-4, batch_size=64, units_actor=(64, 64), **kwargs):
super().__init__(state_shape, action_shape, device, seed, logger, gamma)
self.buffer_exp = buffer_exp
self.batch_size = batch_size
|
class HBC(Algorithm):
def __init__(self, buffer_exp, state_shape, action_shape, device, seed, logger, gamma=0.995,
log_interval=1e3, lr_actor=3e-4, batch_size=64, units_actor=(64, 64), **kwargs):
super().__init__(state_shape, action_shape, device, seed, logger, gamma)
self.buffer_exp = buffer_exp
self.batch_size = batch_size
| self.actor = PPOPolicy( | 0 | 2023-10-27 10:37:44+00:00 | 2k |
jmcruvellier/little_monkey | custom_components/little_monkey/sensor.py | [
{
"identifier": "EcojokoEntity",
"path": "custom_components/little_monkey/entity.py",
"snippet": "class EcojokoEntity(CoordinatorEntity):\n \"\"\"EcojokoEntity class.\"\"\"\n\n _attr_attribution = ATTRIBUTION\n\n def __init__(self, coordinator, device_name, firmware_version):\n \"\"\"Ini... | from homeassistant.components.sensor import (
SensorStateClass,
SensorDeviceClass,
)
from homeassistant.const import UnitOfPower, UnitOfEnergy, UnitOfTemperature, PERCENTAGE, CONF_NAME
from custom_components.little_monkey.entity import EcojokoEntity, EcojokoSensor
from .const import (
DOMAIN,
CONF_USE_HCHP_FEATURE,
CONF_USE_TEMPO_FEATURE,
CONF_USE_TEMPHUM_FEATURE,
CONF_USE_PROD_FEATURE
) | 1,325 | """Sensor platform for mon_ecojoko."""
from __future__ import annotations
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the custom component sensors."""
# Fetch data or configure your sensors here
coordinator = hass.data[DOMAIN][config_entry.entry_id]
# Create the main device entity
firmware = coordinator.data["gateway_firmware_version"]
main_device = EcojokoEntity(coordinator, config_entry.data.get(CONF_NAME), firmware)
# Create child entities and link them to the main device
# Real time sensor
| """Sensor platform for mon_ecojoko."""
from __future__ import annotations
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the custom component sensors."""
# Fetch data or configure your sensors here
coordinator = hass.data[DOMAIN][config_entry.entry_id]
# Create the main device entity
firmware = coordinator.data["gateway_firmware_version"]
main_device = EcojokoEntity(coordinator, config_entry.data.get(CONF_NAME), firmware)
# Create child entities and link them to the main device
# Real time sensor | main_device.add_child_entity(EcojokoSensor( | 1 | 2023-10-29 21:03:13+00:00 | 2k |
stanleylsx/text_embedding | engines/predict.py | [
{
"identifier": "configure",
"path": "config.py",
"snippet": ""
},
{
"identifier": "Model",
"path": "engines/model.py",
"snippet": "class Model(torch.nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.model_type = configure['model_type']\n se... | from config import configure
from engines.model import Model
from engines.utils.metrics import MyModel
from torch.utils.data import DataLoader
from mteb import MTEB
import pandas as pd
import torch
import os | 837 | # -*- coding: utf-8 -*-
# @Time : 2023/10/27 22:05
# @Author : lishouxian
# @Email : gzlishouxian@gmail.com
# @File : predict.py
# @Software: VSCode
class Predictor:
def __init__(self, data_manage, device, logger):
self.logger = logger
self.data_manage = data_manage
self.device = device
self.checkpoints_dir = configure['checkpoints_dir']
self.model_name = configure['model_name']
| # -*- coding: utf-8 -*-
# @Time : 2023/10/27 22:05
# @Author : lishouxian
# @Email : gzlishouxian@gmail.com
# @File : predict.py
# @Software: VSCode
class Predictor:
def __init__(self, data_manage, device, logger):
self.logger = logger
self.data_manage = data_manage
self.device = device
self.checkpoints_dir = configure['checkpoints_dir']
self.model_name = configure['model_name'] | self.model = Model().to(device) | 1 | 2023-10-27 07:47:02+00:00 | 2k |
akekic/causal-component-analysis | data_generator/mixing_function.py | [
{
"identifier": "leaky_tanh",
"path": "data_generator/utils.py",
"snippet": "def leaky_tanh(x: Tensor, alpha: float = 1.0, beta: float = 0.1) -> Tensor:\n return torch.tanh(alpha * x) + beta * x"
},
{
"identifier": "sample_invertible_matrix",
"path": "data_generator/utils.py",
"snippe... | from abc import ABC
from pathlib import Path
from torch import Tensor
from .utils import leaky_tanh, sample_invertible_matrix
import pandas as pd
import torch | 1,048 | """
def __init__(self, latent_dim: int, observation_dim: int) -> None:
self.latent_dim = latent_dim
self.observation_dim = observation_dim
def __call__(self, v: Tensor) -> Tensor:
"""
Apply the mixing function to the latent variables.
Parameters
----------
v: Tensor, shape (num_samples, latent_dim)
Latent variables.
Returns
-------
x: Tensor, shape (num_samples, observation_dim)
Observed variables.
"""
raise NotImplementedError()
def save_coeffs(self, path: Path) -> None:
"""
Save the coefficients of the mixing function to disk.
Parameters
----------
path: Path
Path to save the coefficients to.
"""
raise NotImplementedError()
def unmixing_jacobian(self, v: Tensor) -> Tensor:
"""
Compute the jacobian of the inverse mixing function using autograd and the inverse function theorem.
Parameters
----------
v: Tensor, shape (num_samples, latent_dim)
Latent variables.
Returns
-------
unmixing_jacobian: Tensor, shape (num_samples, observation_dim, latent_dim)
Jacobian of the inverse mixing function.
References
----------
https://en.wikipedia.org/wiki/Inverse_function_theorem
https://discuss.pytorch.org/t/computing-batch-jacobian-efficiently/80771/7
"""
func = self.__call__
inputs = v
mixing_jacobian = torch.vmap(torch.func.jacrev(func))(inputs)
unmixing_jacobian = torch.inverse(mixing_jacobian)
return unmixing_jacobian
class LinearMixing(MixingFunction):
"""
Linear mixing function. The coefficients are sampled from a uniform distribution.
Parameters
----------
latent_dim: int
Dimension of the latent space.
observation_dim: int
Dimension of the observation space.
"""
def __init__(self, latent_dim: int, observation_dim: int) -> None:
super().__init__(latent_dim, observation_dim)
self.coeffs = torch.rand((latent_dim, observation_dim))
def __call__(self, v: Tensor) -> Tensor:
return torch.matmul(v, self.coeffs.to(v.device))
def save_coeffs(self, path: Path) -> None:
# save matrix coefficients
torch.save(self.coeffs, path / "matrix.pt")
matrix_np = self.coeffs.numpy() # convert to Numpy array
df = pd.DataFrame(matrix_np) # convert to a dataframe
df.to_csv(path / "matrix.csv", index=False) # save as csv
class NonlinearMixing(MixingFunction):
"""
Nonlinear mixing function.
The function is composed of a number of invertible matrices and leaky-tanh nonlinearities. I.e. we
apply a random neural network to the latent variables.
Parameters
----------
latent_dim: int
Dimension of the latent space.
observation_dim: int
Dimension of the observation space.
n_nonlinearities: int
Number of layers (i.e. invertible maps and nonlinearities) in the mixing function. Default: 1.
"""
def __init__(
self, latent_dim: int, observation_dim: int, n_nonlinearities: int = 1
) -> None:
super().__init__(latent_dim, observation_dim)
assert latent_dim == observation_dim
self.coefs = torch.rand((latent_dim, observation_dim))
self.n_nonlinearities = n_nonlinearities
matrices = []
for i in range(n_nonlinearities):
matrices.append(sample_invertible_matrix(observation_dim))
self.matrices = matrices
nonlinearities = []
for i in range(n_nonlinearities):
|
class MixingFunction(ABC):
"""
Base class for mixing functions.
The mixing function is the function that maps from the latent space to the observation space.
Parameters
----------
latent_dim: int
Dimension of the latent space.
observation_dim: int
Dimension of the observation space.
"""
def __init__(self, latent_dim: int, observation_dim: int) -> None:
self.latent_dim = latent_dim
self.observation_dim = observation_dim
def __call__(self, v: Tensor) -> Tensor:
"""
Apply the mixing function to the latent variables.
Parameters
----------
v: Tensor, shape (num_samples, latent_dim)
Latent variables.
Returns
-------
x: Tensor, shape (num_samples, observation_dim)
Observed variables.
"""
raise NotImplementedError()
def save_coeffs(self, path: Path) -> None:
"""
Save the coefficients of the mixing function to disk.
Parameters
----------
path: Path
Path to save the coefficients to.
"""
raise NotImplementedError()
def unmixing_jacobian(self, v: Tensor) -> Tensor:
"""
Compute the jacobian of the inverse mixing function using autograd and the inverse function theorem.
Parameters
----------
v: Tensor, shape (num_samples, latent_dim)
Latent variables.
Returns
-------
unmixing_jacobian: Tensor, shape (num_samples, observation_dim, latent_dim)
Jacobian of the inverse mixing function.
References
----------
https://en.wikipedia.org/wiki/Inverse_function_theorem
https://discuss.pytorch.org/t/computing-batch-jacobian-efficiently/80771/7
"""
func = self.__call__
inputs = v
mixing_jacobian = torch.vmap(torch.func.jacrev(func))(inputs)
unmixing_jacobian = torch.inverse(mixing_jacobian)
return unmixing_jacobian
class LinearMixing(MixingFunction):
"""
Linear mixing function. The coefficients are sampled from a uniform distribution.
Parameters
----------
latent_dim: int
Dimension of the latent space.
observation_dim: int
Dimension of the observation space.
"""
def __init__(self, latent_dim: int, observation_dim: int) -> None:
super().__init__(latent_dim, observation_dim)
self.coeffs = torch.rand((latent_dim, observation_dim))
def __call__(self, v: Tensor) -> Tensor:
return torch.matmul(v, self.coeffs.to(v.device))
def save_coeffs(self, path: Path) -> None:
# save matrix coefficients
torch.save(self.coeffs, path / "matrix.pt")
matrix_np = self.coeffs.numpy() # convert to Numpy array
df = pd.DataFrame(matrix_np) # convert to a dataframe
df.to_csv(path / "matrix.csv", index=False) # save as csv
class NonlinearMixing(MixingFunction):
"""
Nonlinear mixing function.
The function is composed of a number of invertible matrices and leaky-tanh nonlinearities. I.e. we
apply a random neural network to the latent variables.
Parameters
----------
latent_dim: int
Dimension of the latent space.
observation_dim: int
Dimension of the observation space.
n_nonlinearities: int
Number of layers (i.e. invertible maps and nonlinearities) in the mixing function. Default: 1.
"""
def __init__(
self, latent_dim: int, observation_dim: int, n_nonlinearities: int = 1
) -> None:
super().__init__(latent_dim, observation_dim)
assert latent_dim == observation_dim
self.coefs = torch.rand((latent_dim, observation_dim))
self.n_nonlinearities = n_nonlinearities
matrices = []
for i in range(n_nonlinearities):
matrices.append(sample_invertible_matrix(observation_dim))
self.matrices = matrices
nonlinearities = []
for i in range(n_nonlinearities): | nonlinearities.append(leaky_tanh) | 0 | 2023-10-25 09:25:26+00:00 | 2k |
facebookresearch/verde | src/generate/export.py | [
{
"identifier": "to_cuda",
"path": "src/utils.py",
"snippet": "def to_cuda(*args):\n \"\"\"\n Move tensors to CUDA.\n \"\"\"\n if not CUDA:\n return args\n return [None if x is None else x.cuda() for x in args]"
},
{
"identifier": "timeout",
"path": "src/utils.py",
... | import os
import io
import sys
import ast
import time
import numpy as np
import torch
from logging import getLogger
from collections import OrderedDict
from torch import nn
from ..utils import to_cuda, timeout, TimeoutError | 1,067 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
logger = getLogger()
class Generator(object):
def __init__(self, params, gen):
"""
Initialize trainer.
"""
# params
self.params = params
self.gen = gen
self.print_cycle = 500 if params.step == "Ab" else 1
# epoch / iteration size
self.epoch_size = params.epoch_size
assert self.epoch_size > 0
# training statistics
self.epoch = 0
self.n_iter = 0
self.n_total_iter = 0
self.timeout_count = 0
self.total_count = 0
self.stats = { "processed_e": 0 }
self.last_time = time.time()
# file handler to export data
export_path_prefix = os.path.join(params.dump_path, "data.prefix")
if params.step == 'Ab':
export_path_prefix = os.path.join(params.dump_path, "test.prefix")
self.file_handler_prefix = io.open(export_path_prefix, mode="a", encoding="utf-8")
logger.info(f"Data will be stored in: {export_path_prefix} ...")
def iter(self):
"""
End of iteration.
"""
self.n_iter += 1
self.n_total_iter += 1
self.print_stats()
def print_stats(self):
"""
Print statistics about the training.
"""
if self.n_total_iter % self.print_cycle != 0:
return
s_iter = "%7i - " % self.n_total_iter
s_stat = " || ".join(
[
"{}: {:7.4f}".format(k.upper().replace("_", "-"), np.mean(v))
for k, v in self.stats.items()
if type(v) is list and len(v) > 0
]
)
for k in self.stats.keys():
if type(self.stats[k]) is list:
del self.stats[k][:]
# processing speed
new_time = time.time()
diff = new_time - self.last_time
s_speed = "{:7.2f} equations/s - ".format(
self.stats["processed_e"] * 1.0 / diff,
)
self.stats["processed_e"] = 0
self.last_time = new_time
# log speed + stats
logger.info(s_iter + s_speed + s_stat)
def end_epoch(self):
"""
End the epoch.
"""
if self.params.step == 'Ab':
np.save(os.path.join(self.params.dump_path, 'diff.npy'), self.gen.diff)
logger.info(f'Saved diff at {os.path.join(self.params.dump_path, "diff.npy")}')
def export_data(self):
"""
Export data to the disk.
"""
while True:
try:
sample = self.gen.generate()
break
| # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
logger = getLogger()
class Generator(object):
def __init__(self, params, gen):
"""
Initialize trainer.
"""
# params
self.params = params
self.gen = gen
self.print_cycle = 500 if params.step == "Ab" else 1
# epoch / iteration size
self.epoch_size = params.epoch_size
assert self.epoch_size > 0
# training statistics
self.epoch = 0
self.n_iter = 0
self.n_total_iter = 0
self.timeout_count = 0
self.total_count = 0
self.stats = { "processed_e": 0 }
self.last_time = time.time()
# file handler to export data
export_path_prefix = os.path.join(params.dump_path, "data.prefix")
if params.step == 'Ab':
export_path_prefix = os.path.join(params.dump_path, "test.prefix")
self.file_handler_prefix = io.open(export_path_prefix, mode="a", encoding="utf-8")
logger.info(f"Data will be stored in: {export_path_prefix} ...")
def iter(self):
"""
End of iteration.
"""
self.n_iter += 1
self.n_total_iter += 1
self.print_stats()
def print_stats(self):
"""
Print statistics about the training.
"""
if self.n_total_iter % self.print_cycle != 0:
return
s_iter = "%7i - " % self.n_total_iter
s_stat = " || ".join(
[
"{}: {:7.4f}".format(k.upper().replace("_", "-"), np.mean(v))
for k, v in self.stats.items()
if type(v) is list and len(v) > 0
]
)
for k in self.stats.keys():
if type(self.stats[k]) is list:
del self.stats[k][:]
# processing speed
new_time = time.time()
diff = new_time - self.last_time
s_speed = "{:7.2f} equations/s - ".format(
self.stats["processed_e"] * 1.0 / diff,
)
self.stats["processed_e"] = 0
self.last_time = new_time
# log speed + stats
logger.info(s_iter + s_speed + s_stat)
def end_epoch(self):
"""
End the epoch.
"""
if self.params.step == 'Ab':
np.save(os.path.join(self.params.dump_path, 'diff.npy'), self.gen.diff)
logger.info(f'Saved diff at {os.path.join(self.params.dump_path, "diff.npy")}')
def export_data(self):
"""
Export data to the disk.
"""
while True:
try:
sample = self.gen.generate()
break | except TimeoutError: | 2 | 2023-10-30 17:53:57+00:00 | 2k |
Paiman-Rasoli/flatway | src/tests/test_flatten.py | [
{
"identifier": "mock_list_with_deep_one",
"path": "src/tests/fixtures.py",
"snippet": "@pytest.fixture\ndef mock_list_with_deep_one():\n return [1, 2, 3, 4, 5, 6, 7, 8, [9, 10, 11], 12]"
},
{
"identifier": "mock_list_with_deep_five",
"path": "src/tests/fixtures.py",
"snippet": "@pyte... | from flatway.flatten import flatten, flattenDict
from .fixtures import (mock_list_with_deep_one, mock_list_with_deep_five,
mock_tuple_with_deep_one, mock_tuple_with_deep_five,
mock_dictionary_deep_one, mock_dictionary_deep_three) | 646 |
def test_flatten_of_list_with_deep_one(mock_list_with_deep_one):
result = flatten(mock_list_with_deep_one)
expect = [x for x in range(1, 13)]
assert result == expect
assert isinstance(result, list)
|
def test_flatten_of_list_with_deep_one(mock_list_with_deep_one):
result = flatten(mock_list_with_deep_one)
expect = [x for x in range(1, 13)]
assert result == expect
assert isinstance(result, list)
| def test_flatten_of_list_with_deep_five(mock_list_with_deep_five): | 1 | 2023-10-25 20:47:36+00:00 | 2k |
Muhammadali-Akbarov/aiogram-bot-template | aiogram_bot_template/db/db_api/storages/postgres/storage.py | [
{
"identifier": "MultipleQueryResults",
"path": "aiogram_bot_template/db/db_api/storages/basestorage/storage.py",
"snippet": "class MultipleQueryResults:\n def __init__(self, results: list[typing.Mapping[str, Any]]):\n self._data: list[dict[str, Any]] = [{**i} for i in results]\n\n @propert... | import time
import asyncpg
import structlog
from typing import Any, Optional, TypeVar
from ..basestorage.storage import MultipleQueryResults, RawConnection, SingleQueryResult | 901 |
T = TypeVar("T")
class PostgresConnection(RawConnection):
def __init__(
self,
connection_poll: asyncpg.Pool,
logger: structlog.typing.FilteringBoundLogger,
):
self._pool = connection_poll
self._logger = logger
async def _fetch(
self,
sql: str,
params: Optional[tuple[Any, ...] | list[tuple[Any, ...]]] = None,
con: Optional[asyncpg.Connection] = None,
) -> MultipleQueryResults:
st = time.monotonic()
request_logger = self._logger.bind(sql=sql, params=params)
request_logger.debug("Making query to DB")
try:
if con is None:
async with self._pool.acquire() as con:
if params is not None:
raw_result = await con.fetch(sql, *params)
else:
raw_result = await con.fetch(sql)
else:
if params is not None:
raw_result = await con.fetch(sql, *params)
else:
raw_result = await con.fetch(sql)
except Exception as e:
# change to appropriate error handling
request_logger = request_logger.bind(error=e)
request_logger.error(f"Error while making query: {e}")
raise e
else:
results = [i for i in raw_result]
finally:
request_logger.debug(
"Finished query to DB", spent_time_ms=(time.monotonic() - st) * 1000
)
return MultipleQueryResults(results)
async def _fetchrow(
self,
sql: str,
params: Optional[tuple[Any, ...] | list[tuple[Any, ...]]] = None,
con: Optional[asyncpg.Connection] = None,
|
T = TypeVar("T")
class PostgresConnection(RawConnection):
def __init__(
self,
connection_poll: asyncpg.Pool,
logger: structlog.typing.FilteringBoundLogger,
):
self._pool = connection_poll
self._logger = logger
async def _fetch(
self,
sql: str,
params: Optional[tuple[Any, ...] | list[tuple[Any, ...]]] = None,
con: Optional[asyncpg.Connection] = None,
) -> MultipleQueryResults:
st = time.monotonic()
request_logger = self._logger.bind(sql=sql, params=params)
request_logger.debug("Making query to DB")
try:
if con is None:
async with self._pool.acquire() as con:
if params is not None:
raw_result = await con.fetch(sql, *params)
else:
raw_result = await con.fetch(sql)
else:
if params is not None:
raw_result = await con.fetch(sql, *params)
else:
raw_result = await con.fetch(sql)
except Exception as e:
# change to appropriate error handling
request_logger = request_logger.bind(error=e)
request_logger.error(f"Error while making query: {e}")
raise e
else:
results = [i for i in raw_result]
finally:
request_logger.debug(
"Finished query to DB", spent_time_ms=(time.monotonic() - st) * 1000
)
return MultipleQueryResults(results)
async def _fetchrow(
self,
sql: str,
params: Optional[tuple[Any, ...] | list[tuple[Any, ...]]] = None,
con: Optional[asyncpg.Connection] = None, | ) -> SingleQueryResult: | 2 | 2023-10-28 19:44:58+00:00 | 2k |
Doubling-Open-Source/git_calculator | src/calculators/throughput_calculator.py | [
{
"identifier": "git_log",
"path": "src/git_ir.py",
"snippet": "def git_log():\n def to_obj(line):\n parts = line.split('|', 5)\n parts[3] = parts[3].split() # Multiple parents\n return git_obj.commit(*parts)\n res = [\n to_obj(line)\n for line in git_run('log',... | from datetime import datetime
from src.git_ir import git_log, format_git_logs_as_string
from collections import defaultdict
from io import StringIO
from subprocess import run as sp_run
import logging | 880 |
# Logging configuration
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
def extract_commits_and_authors(logs):
"""
Extract commits and their authors from git logs.
Args:
logs (list): List of commit logs.
Returns:
dict: Dictionary with months as keys and tuples (set of authors, commit count) as values.
"""
data_by_month = defaultdict(lambda: (set(), 0))
for commit in logs:
author_email = commit._author[0]
commit_date = datetime.fromtimestamp(commit._when)
month_key = f"{commit_date.year}-{commit_date.month}"
authors_set, commit_count = data_by_month[month_key]
authors_set.add(author_email)
data_by_month[month_key] = (authors_set, commit_count + 1)
return data_by_month
def calculate_throughput(data_by_month):
"""
Calculate the number of commits per active unique developer per month.
Args:
data_by_month (dict): Dictionary with months as keys and tuples (set of authors, commit count) as values.
Returns:
dict: Dictionary with months as keys and throughput (commits per unique developer) as values.
"""
throughput_stats = {}
for month, (authors, commit_count) in data_by_month.items():
if authors:
throughput_stats[month] = commit_count / len(authors)
else:
throughput_stats[month] = 0
return throughput_stats
def throughput_stats_to_string(throughput_stats):
"""
Convert throughput statistics to a CSV-formatted string.
Args:
throughput_stats (dict): Dictionary with months as keys and throughput values as values.
Returns:
str: CSV-formatted string.
"""
buf = StringIO()
print("Month,Commits Per Unique Developer", file=buf)
for month, throughput in sorted(throughput_stats.items()):
print(f"{month},{throughput:.2f}", file=buf)
return buf.getvalue()
def write_throughput_stats_to_file(throughput_stats, fname='throughput_by_month.csv'):
"""
Write the throughput statistics to a file.
Args:
throughput_stats (dict): Dictionary with months as keys and throughput values as values.
fname (str): Filename for the output.
"""
stats_string = throughput_stats_to_string(throughput_stats)
with open(fname, 'wt') as fout:
fout.write(stats_string)
if fname.endswith('.csv'):
sp_run(['open', fname])
def monthly_throughput_analysis():
"""
Main function to calculate and write monthly throughput statistics.
"""
logs = git_log()
|
# Logging configuration
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
def extract_commits_and_authors(logs):
"""
Extract commits and their authors from git logs.
Args:
logs (list): List of commit logs.
Returns:
dict: Dictionary with months as keys and tuples (set of authors, commit count) as values.
"""
data_by_month = defaultdict(lambda: (set(), 0))
for commit in logs:
author_email = commit._author[0]
commit_date = datetime.fromtimestamp(commit._when)
month_key = f"{commit_date.year}-{commit_date.month}"
authors_set, commit_count = data_by_month[month_key]
authors_set.add(author_email)
data_by_month[month_key] = (authors_set, commit_count + 1)
return data_by_month
def calculate_throughput(data_by_month):
"""
Calculate the number of commits per active unique developer per month.
Args:
data_by_month (dict): Dictionary with months as keys and tuples (set of authors, commit count) as values.
Returns:
dict: Dictionary with months as keys and throughput (commits per unique developer) as values.
"""
throughput_stats = {}
for month, (authors, commit_count) in data_by_month.items():
if authors:
throughput_stats[month] = commit_count / len(authors)
else:
throughput_stats[month] = 0
return throughput_stats
def throughput_stats_to_string(throughput_stats):
"""
Convert throughput statistics to a CSV-formatted string.
Args:
throughput_stats (dict): Dictionary with months as keys and throughput values as values.
Returns:
str: CSV-formatted string.
"""
buf = StringIO()
print("Month,Commits Per Unique Developer", file=buf)
for month, throughput in sorted(throughput_stats.items()):
print(f"{month},{throughput:.2f}", file=buf)
return buf.getvalue()
def write_throughput_stats_to_file(throughput_stats, fname='throughput_by_month.csv'):
"""
Write the throughput statistics to a file.
Args:
throughput_stats (dict): Dictionary with months as keys and throughput values as values.
fname (str): Filename for the output.
"""
stats_string = throughput_stats_to_string(throughput_stats)
with open(fname, 'wt') as fout:
fout.write(stats_string)
if fname.endswith('.csv'):
sp_run(['open', fname])
def monthly_throughput_analysis():
"""
Main function to calculate and write monthly throughput statistics.
"""
logs = git_log() | logging.debug('Logs: %s', format_git_logs_as_string(logs)) | 1 | 2023-10-28 13:43:03+00:00 | 2k |
sisl/SceneInformer | sceneinformer/model/encoder.py | [
{
"identifier": "MLPPointEncoder",
"path": "sceneinformer/model/utils.py",
"snippet": "class MLPPointEncoder(nn.Module):\n def __init__(self, config):\n super(MLPPointEncoder, self).__init__()\n self.config = config\n in_dim = config['in_dim'] * 11\n out_dim = config['out_... | import torch
import torch.nn as nn
import torch.nn.functional as F
import lightning.pytorch as pl
from sceneinformer.model.utils import MLPPointEncoder, PointEncoder, count_parameters | 861 |
class Encoder(pl.LightningModule):
def __init__(self, config: dict) -> None:
super(Encoder, self).__init__()
self.config = config
self.hidden_dim = config['d_model']
if 'point_enc' in config.keys():
if config['point_enc'] == 'mlp':
self.veh_encoder = MLPPointEncoder(config['vehicle_encoder'])
self.ped_encoder = MLPPointEncoder(config['pedestrian_encoder'])
self.bike_encoder = MLPPointEncoder(config['bike_encoder'])
elif config['point_enc'] == 'pointnet':
|
class Encoder(pl.LightningModule):
def __init__(self, config: dict) -> None:
super(Encoder, self).__init__()
self.config = config
self.hidden_dim = config['d_model']
if 'point_enc' in config.keys():
if config['point_enc'] == 'mlp':
self.veh_encoder = MLPPointEncoder(config['vehicle_encoder'])
self.ped_encoder = MLPPointEncoder(config['pedestrian_encoder'])
self.bike_encoder = MLPPointEncoder(config['bike_encoder'])
elif config['point_enc'] == 'pointnet': | self.veh_encoder = PointEncoder(config['vehicle_encoder']) | 1 | 2023-10-31 08:08:26+00:00 | 2k |
LFhase/GALA | drugood/models/algorithms/groupdro.py | [
{
"identifier": "BaseAlgorithm",
"path": "drugood/models/algorithms/base.py",
"snippet": "class BaseAlgorithm(BaseModule, metaclass=ABCMeta):\n def __init__(self, init_cfg=None):\n super(BaseAlgorithm, self).__init__(init_cfg)\n\n @abstractmethod\n def forward_train(self, input, group, *... | import torch
import torch_scatter
from drugood.models.algorithms.base import BaseAlgorithm
from ..builder import MODELS, build_tasker | 970 | # Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
@MODELS.register_module()
class GroupDRO(BaseAlgorithm):
"""
Group distributionally robust optimization.
Original paper:
@inproceedings{sagawa2019distributionally,
title={Distributionally robust neural networks for group shifts: On the importance of regularization for worst-case generalization},
author={Sagawa, Shiori and Koh, Pang Wei and Hashimoto, Tatsunori B and Liang, Percy},
booktitle={International Conference on Learning Representations},
year={2019}
}
The GroupDRO implementation below is adapted from Wilds's implementation:
https://github.com/p-lambda/wilds/blob/a7a452c80cad311cf0aabfd59af8348cba1b9861/examples/algorithms/groupDRO.py
"""
def __init__(self,
tasker,
num_groups=44930,
group_dro_step_size=0.01,
):
super().__init__()
| # Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
@MODELS.register_module()
class GroupDRO(BaseAlgorithm):
"""
Group distributionally robust optimization.
Original paper:
@inproceedings{sagawa2019distributionally,
title={Distributionally robust neural networks for group shifts: On the importance of regularization for worst-case generalization},
author={Sagawa, Shiori and Koh, Pang Wei and Hashimoto, Tatsunori B and Liang, Percy},
booktitle={International Conference on Learning Representations},
year={2019}
}
The GroupDRO implementation below is adapted from Wilds's implementation:
https://github.com/p-lambda/wilds/blob/a7a452c80cad311cf0aabfd59af8348cba1b9861/examples/algorithms/groupDRO.py
"""
def __init__(self,
tasker,
num_groups=44930,
group_dro_step_size=0.01,
):
super().__init__() | self.tasker = build_tasker(tasker) | 2 | 2023-10-30 16:57:56+00:00 | 2k |
Graph-and-Geometric-Learning/D4Explainer | main.py | [
{
"identifier": "feature_dict",
"path": "constants.py",
"snippet": ""
},
{
"identifier": "get_datasets",
"path": "utils/dataset.py",
"snippet": "def get_datasets(name, root=\"data/\"):\n \"\"\"\n Get preloaded datasets by name\n :param name: name of the dataset\n :param root:... | import argparse
import torch
from torch_geometric.loader import DataLoader
from constants import feature_dict, task_type, dataset_choices
from explainers import *
from gnns import *
from utils.dataset import get_datasets | 1,234 |
def parse_args():
parser = argparse.ArgumentParser(description="Train explainers")
parser.add_argument("--cuda", type=int, default=0, help="GPU device.")
parser.add_argument("--root", type=str, default="results/", help="Result directory.")
parser.add_argument("--dataset", type=str, default="Tree_Cycle", choices=dataset_choices)
parser.add_argument("--verbose", type=int, default=10)
parser.add_argument("--gnn_type", type=str, default="gcn")
parser.add_argument("--task", type=str, default="nc")
parser.add_argument("--train_batchsize", type=int, default=32)
parser.add_argument("--test_batchsize", type=int, default=32)
parser.add_argument("--sigma_length", type=int, default=10)
parser.add_argument("--epoch", type=int, default=800)
parser.add_argument("--feature_in", type=int)
parser.add_argument("--data_size", type=int, default=-1)
parser.add_argument("--threshold", type=float, default=0.5)
parser.add_argument("--alpha_cf", type=float, default=0.5)
parser.add_argument("--dropout", type=float, default=0.001)
parser.add_argument("--learning_rate", type=float, default=1e-3)
parser.add_argument("--lr_decay", type=float, default=0.999)
parser.add_argument("--weight_decay", type=float, default=0)
parser.add_argument("--prob_low", type=float, default=0.0)
parser.add_argument("--prob_high", type=float, default=0.4)
parser.add_argument("--sparsity_level", type=float, default=2.5)
parser.add_argument("--normalization", type=str, default="instance")
parser.add_argument("--num_layers", type=int, default=6)
parser.add_argument("--layers_per_conv", type=int, default=1)
parser.add_argument("--n_hidden", type=int, default=64)
parser.add_argument("--cat_output", type=bool, default=True)
parser.add_argument("--residual", type=bool, default=False)
parser.add_argument("--noise_mlp", type=bool, default=True)
parser.add_argument("--simplified", type=bool, default=False)
return parser.parse_args()
args = parse_args()
args.noise_list = None
args.device = torch.device(f"cuda:{args.cuda}" if torch.cuda.is_available() else "cpu")
args.feature_in = feature_dict[args.dataset]
|
def parse_args():
parser = argparse.ArgumentParser(description="Train explainers")
parser.add_argument("--cuda", type=int, default=0, help="GPU device.")
parser.add_argument("--root", type=str, default="results/", help="Result directory.")
parser.add_argument("--dataset", type=str, default="Tree_Cycle", choices=dataset_choices)
parser.add_argument("--verbose", type=int, default=10)
parser.add_argument("--gnn_type", type=str, default="gcn")
parser.add_argument("--task", type=str, default="nc")
parser.add_argument("--train_batchsize", type=int, default=32)
parser.add_argument("--test_batchsize", type=int, default=32)
parser.add_argument("--sigma_length", type=int, default=10)
parser.add_argument("--epoch", type=int, default=800)
parser.add_argument("--feature_in", type=int)
parser.add_argument("--data_size", type=int, default=-1)
parser.add_argument("--threshold", type=float, default=0.5)
parser.add_argument("--alpha_cf", type=float, default=0.5)
parser.add_argument("--dropout", type=float, default=0.001)
parser.add_argument("--learning_rate", type=float, default=1e-3)
parser.add_argument("--lr_decay", type=float, default=0.999)
parser.add_argument("--weight_decay", type=float, default=0)
parser.add_argument("--prob_low", type=float, default=0.0)
parser.add_argument("--prob_high", type=float, default=0.4)
parser.add_argument("--sparsity_level", type=float, default=2.5)
parser.add_argument("--normalization", type=str, default="instance")
parser.add_argument("--num_layers", type=int, default=6)
parser.add_argument("--layers_per_conv", type=int, default=1)
parser.add_argument("--n_hidden", type=int, default=64)
parser.add_argument("--cat_output", type=bool, default=True)
parser.add_argument("--residual", type=bool, default=False)
parser.add_argument("--noise_mlp", type=bool, default=True)
parser.add_argument("--simplified", type=bool, default=False)
return parser.parse_args()
args = parse_args()
args.noise_list = None
args.device = torch.device(f"cuda:{args.cuda}" if torch.cuda.is_available() else "cpu")
args.feature_in = feature_dict[args.dataset] | args.task = task_type[args.dataset] | 0 | 2023-10-28 19:58:40+00:00 | 2k |
p4p1/havoc-reporter | reporter.py | [
{
"identifier": "html_panel_mitre",
"path": "html_source/mitre.py",
"snippet": ""
},
{
"identifier": "html_panel_vulns",
"path": "html_source/vulnerabilities.py",
"snippet": ""
},
{
"identifier": "network_vulns",
"path": "vulns/network_vulnerabilities.py",
"snippet": ""
... | import havocui
import webbrowser
import os, sys, html, json
from html_source.mitre import html_panel_mitre
from html_source.vulnerabilities import html_panel_vulns
from mitre.tactics import *
from vulns.network_vulnerabilities import network_vulns
from vulns.active_directory import active_directory_vulns
from vulns.windows_privesc import windows_privesc_vulns
| 1,298 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Made by papi
# Created on: Wen 25 Oct 2023
# reporter.py
# Description:
# A havoc extention to provide examples for different vulnerabilities that can
# be tested on the infected networks and on the infected machines.
# Usage:
# To use this script save it on your machine and add it to the script manager of Havoc
# inside of: Scripts > Scripts Manager > Load Script
config = {
"install_path": ""
}
# if no config file found create one
if not os.path.exists(os.path.expanduser("~/") + ".config/havoc-reporter/config.json"):
if not os.path.exists(os.path.expanduser("~/") + ".config/havoc-reporter/"):
os.mkdir(os.path.expanduser("~/") + ".config/havoc-reporter")
with open(os.path.expanduser("~/") + ".config/havoc-reporter/config.json", "w") as outfile:
json.dump(config, outfile)
else: # use config file
with open(os.path.expanduser("~/") + ".config/havoc-reporter/config.json") as outfile:
config = json.load(outfile)
# specify here the path of the install script...
while not os.path.exists(config["install_path"]):
new_path = havocui.inputdialog("specify the path of the install", "The path of where this script is installed is wrong please provide with the correct path:")
config["install_path"] = new_path.decode('utf-8')
with open(os.path.expanduser("~/") + ".config/havoc-reporter/config.json", "w") as outfile:
json.dump(config, outfile)
sys.path.append(config["install_path"])
tree_display_vulns = None
tree_display_mitre = None
settings_widget = None
net_titles = [item["title"] for item in network_vulns]
ad_titles = [item["title"] for item in active_directory_vulns]
winpriv_titles = [item["title"] for item in windows_privesc_vulns]
# MITRE ATT&CK techniques
reconnaissance_titles = [item["technique"] for item in reconnaissance]
resource_development_titles = [item["technique"] for item in resource_development]
initial_access_titles = [item["technique"] for item in initial_access]
execution_titles = [item["technique"] for item in execution]
persistence_titles = [item["technique"] for item in persistence]
privilege_escalation_titles = [item["technique"] for item in privilege_escalation]
defense_evasion_titles = [item["technique"] for item in defense_evasion]
credential_access_titles = [item["technique"] for item in credential_access]
discovery_titles = [item["technique"] for item in discovery]
lateral_movement_titles = [item["technique"] for item in lateral_movement]
collection_titles = [item["technique"] for item in collection]
command_and_control_titles = [item["technique"] for item in command_and_control]
exfiltration_titles = [item["technique"] for item in exfiltration]
impact_titles = [item["technique"] for item in impact]
# Function to set the HTML of the page
def select_tree_vulns(data):
global tree_display_vulns
title = ""
desc = ""
image = ""
mitre = ""
external = []
command = ""
if data in net_titles:
title = network_vulns[net_titles.index(data)]["title"]
desc = network_vulns[net_titles.index(data)]["desc"]
image = network_vulns[net_titles.index(data)]["image"]
mitre = network_vulns[net_titles.index(data)]["mitre"]
external = network_vulns[net_titles.index(data)]["external"]
command = network_vulns[net_titles.index(data)]["command"]
elif data in ad_titles:
title = active_directory_vulns[ad_titles.index(data)]["title"]
desc = active_directory_vulns[ad_titles.index(data)]["desc"]
image = active_directory_vulns[ad_titles.index(data)]["image"]
mitre = active_directory_vulns[ad_titles.index(data)]["mitre"]
external = active_directory_vulns[ad_titles.index(data)]["external"]
command = active_directory_vulns[ad_titles.index(data)]["command"]
elif data in winpriv_titles:
title = windows_privesc_vulns[winpriv_titles.index(data)]["title"]
desc = windows_privesc_vulns[winpriv_titles.index(data)]["desc"]
image = windows_privesc_vulns[winpriv_titles.index(data)]["image"]
mitre = windows_privesc_vulns[winpriv_titles.index(data)]["mitre"]
external = windows_privesc_vulns[winpriv_titles.index(data)]["external"]
command = windows_privesc_vulns[winpriv_titles.index(data)]["command"]
if title != "":
external_data = ""
for obj in external:
external_data = external_data + "<li><a style=\"color:#e100ff\" href=\"%s\">%s</a></li>" % (obj["link"], obj["title"])
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Made by papi
# Created on: Wen 25 Oct 2023
# reporter.py
# Description:
# A havoc extention to provide examples for different vulnerabilities that can
# be tested on the infected networks and on the infected machines.
# Usage:
# To use this script save it on your machine and add it to the script manager of Havoc
# inside of: Scripts > Scripts Manager > Load Script
config = {
"install_path": ""
}
# if no config file found create one
if not os.path.exists(os.path.expanduser("~/") + ".config/havoc-reporter/config.json"):
if not os.path.exists(os.path.expanduser("~/") + ".config/havoc-reporter/"):
os.mkdir(os.path.expanduser("~/") + ".config/havoc-reporter")
with open(os.path.expanduser("~/") + ".config/havoc-reporter/config.json", "w") as outfile:
json.dump(config, outfile)
else: # use config file
with open(os.path.expanduser("~/") + ".config/havoc-reporter/config.json") as outfile:
config = json.load(outfile)
# specify here the path of the install script...
while not os.path.exists(config["install_path"]):
new_path = havocui.inputdialog("specify the path of the install", "The path of where this script is installed is wrong please provide with the correct path:")
config["install_path"] = new_path.decode('utf-8')
with open(os.path.expanduser("~/") + ".config/havoc-reporter/config.json", "w") as outfile:
json.dump(config, outfile)
sys.path.append(config["install_path"])
tree_display_vulns = None
tree_display_mitre = None
settings_widget = None
net_titles = [item["title"] for item in network_vulns]
ad_titles = [item["title"] for item in active_directory_vulns]
winpriv_titles = [item["title"] for item in windows_privesc_vulns]
# MITRE ATT&CK techniques
reconnaissance_titles = [item["technique"] for item in reconnaissance]
resource_development_titles = [item["technique"] for item in resource_development]
initial_access_titles = [item["technique"] for item in initial_access]
execution_titles = [item["technique"] for item in execution]
persistence_titles = [item["technique"] for item in persistence]
privilege_escalation_titles = [item["technique"] for item in privilege_escalation]
defense_evasion_titles = [item["technique"] for item in defense_evasion]
credential_access_titles = [item["technique"] for item in credential_access]
discovery_titles = [item["technique"] for item in discovery]
lateral_movement_titles = [item["technique"] for item in lateral_movement]
collection_titles = [item["technique"] for item in collection]
command_and_control_titles = [item["technique"] for item in command_and_control]
exfiltration_titles = [item["technique"] for item in exfiltration]
impact_titles = [item["technique"] for item in impact]
# Function to set the HTML of the page
def select_tree_vulns(data):
global tree_display_vulns
title = ""
desc = ""
image = ""
mitre = ""
external = []
command = ""
if data in net_titles:
title = network_vulns[net_titles.index(data)]["title"]
desc = network_vulns[net_titles.index(data)]["desc"]
image = network_vulns[net_titles.index(data)]["image"]
mitre = network_vulns[net_titles.index(data)]["mitre"]
external = network_vulns[net_titles.index(data)]["external"]
command = network_vulns[net_titles.index(data)]["command"]
elif data in ad_titles:
title = active_directory_vulns[ad_titles.index(data)]["title"]
desc = active_directory_vulns[ad_titles.index(data)]["desc"]
image = active_directory_vulns[ad_titles.index(data)]["image"]
mitre = active_directory_vulns[ad_titles.index(data)]["mitre"]
external = active_directory_vulns[ad_titles.index(data)]["external"]
command = active_directory_vulns[ad_titles.index(data)]["command"]
elif data in winpriv_titles:
title = windows_privesc_vulns[winpriv_titles.index(data)]["title"]
desc = windows_privesc_vulns[winpriv_titles.index(data)]["desc"]
image = windows_privesc_vulns[winpriv_titles.index(data)]["image"]
mitre = windows_privesc_vulns[winpriv_titles.index(data)]["mitre"]
external = windows_privesc_vulns[winpriv_titles.index(data)]["external"]
command = windows_privesc_vulns[winpriv_titles.index(data)]["command"]
if title != "":
external_data = ""
for obj in external:
external_data = external_data + "<li><a style=\"color:#e100ff\" href=\"%s\">%s</a></li>" % (obj["link"], obj["title"])
| tree_display_vulns.setPanel(html_panel_vulns % (title, image, mitre, desc, html.escape(command), external_data))
| 1 | 2023-10-25 10:39:20+00:00 | 2k |
amazon-science/adaptive-in-context-learning | MetaICL/utils/download.py | [
{
"identifier": "all_settings",
"path": "MetaICL/utils/utils.py",
"snippet": "def get_checkpoint_id(key):\ndef download_file(_id, dest):"
},
{
"identifier": "download_file",
"path": "MetaICL/utils/utils.py",
"snippet": "def download_file(_id, dest):\n if os.path.exists(dest):\n ... | import os
import json
import argparse
import subprocess
from .utils import all_settings, all_methods
from .utils import download_file, get_checkpoint_id | 970 |
'''
script for downloading preprocessed data and trained checkpoints
'''
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoints", default=False, action="store_true")
parser.add_argument("--demo_data", default=False, action="store_true")
parser.add_argument("--target_only", default=False, action="store_true")
parser.add_argument("--inst", default=False, action="store_true")
parser.add_argument("--setting", default="all", type=str,
choices=["all"]+all_settings)
parser.add_argument("--method", default="all", type=str,
choices=["all"]+all_methods)
parser.add_argument("--data_dir", type=str, default="data")
parser.add_argument("--checkpoint_dir", type=str, default="checkpoints")
args = parser.parse_args()
return args
def main(args):
if args.demo_data:
download_file("15grQwt3B1tALtUCGtaDI_rwC28LL8wSj",
os.path.join(args.data_dir, "financial_phrasebank", "financial_phrasebank_16_100_train.jsonl"))
if args.checkpoints:
if args.setting=="all":
settings = all_settings
else:
settings = [args.setting]
if args.method=="all":
methods = all_methods
else:
methods = [args.method]
for method in methods:
for setting in settings:
|
'''
script for downloading preprocessed data and trained checkpoints
'''
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoints", default=False, action="store_true")
parser.add_argument("--demo_data", default=False, action="store_true")
parser.add_argument("--target_only", default=False, action="store_true")
parser.add_argument("--inst", default=False, action="store_true")
parser.add_argument("--setting", default="all", type=str,
choices=["all"]+all_settings)
parser.add_argument("--method", default="all", type=str,
choices=["all"]+all_methods)
parser.add_argument("--data_dir", type=str, default="data")
parser.add_argument("--checkpoint_dir", type=str, default="checkpoints")
args = parser.parse_args()
return args
def main(args):
if args.demo_data:
download_file("15grQwt3B1tALtUCGtaDI_rwC28LL8wSj",
os.path.join(args.data_dir, "financial_phrasebank", "financial_phrasebank_16_100_train.jsonl"))
if args.checkpoints:
if args.setting=="all":
settings = all_settings
else:
settings = [args.setting]
if args.method=="all":
methods = all_methods
else:
methods = [args.method]
for method in methods:
for setting in settings: | _, _, _id = get_checkpoint_id(method + "/" + setting) | 2 | 2023-10-30 16:34:21+00:00 | 2k |
endo-yuki-t/MAG | ldm/models/diffusion/ddim.py | [
{
"identifier": "make_ddim_sampling_parameters",
"path": "ldm/modules/diffusionmodules/util.py",
"snippet": "def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):\n # select alphas for computing the variance schedule\n alphas = alphacums[ddim_timesteps]\n alphas_prev ... | import torch
import cv2
import matplotlib.pyplot as plt
import numpy as np
import math
from tqdm import tqdm
from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
from ldm.diffusion_utils import denoising_step
from einops import rearrange, repeat | 1,445 | """SAMPLING ONLY."""
class DDIMSampler(object):
def __init__(self, model, schedule="linear", **kwargs):
super().__init__()
self.model = model
self.ddpm_num_timesteps = model.num_timesteps
self.schedule = schedule
def register_buffer(self, name, attr):
if type(attr) == torch.Tensor:
if attr.device != torch.device("cuda"):
attr = attr.to(torch.device("cuda"))
setattr(self, name, attr)
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
| """SAMPLING ONLY."""
class DDIMSampler(object):
def __init__(self, model, schedule="linear", **kwargs):
super().__init__()
self.model = model
self.ddpm_num_timesteps = model.num_timesteps
self.schedule = schedule
def register_buffer(self, name, attr):
if type(attr) == torch.Tensor:
if attr.device != torch.device("cuda"):
attr = attr.to(torch.device("cuda"))
setattr(self, name, attr)
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True): | self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps, | 1 | 2023-10-27 06:56:37+00:00 | 2k |
LibreTranslate/LexiLang | lexilang/utils.py | [
{
"identifier": "get_supported_languages",
"path": "lexilang/languages.py",
"snippet": "def get_supported_languages():\n return {\n 'afrikaans': 'af', \n 'albanian': 'sq', \n 'arabic': 'ar', \n 'bengali': 'bn', \n 'bulgarian': 'bg', \n 'catalan': 'ca', \n ... | import os
import pickle
from .languages import get_supported_languages, tokenize | 647 |
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
def compile_data():
print("Compiling database...")
words = {}
langs = get_supported_languages()
for name in langs:
code = langs[name]
with open(os.path.join(root_dir, "dictionaries", f"{name}.txt"), "r", encoding="utf-8") as f:
lines = [l.strip().lower() for l in f.read().split("\n")]
for l in lines:
|
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
def compile_data():
print("Compiling database...")
words = {}
langs = get_supported_languages()
for name in langs:
code = langs[name]
with open(os.path.join(root_dir, "dictionaries", f"{name}.txt"), "r", encoding="utf-8") as f:
lines = [l.strip().lower() for l in f.read().split("\n")]
for l in lines: | tokens = tokenize(code, l.strip()) | 1 | 2023-10-30 13:43:19+00:00 | 2k |
alexeichhorn/typegpt | typegpt/parser.py | [
{
"identifier": "LLMOutputFieldMissing",
"path": "typegpt/exceptions.py",
"snippet": "class LLMOutputFieldMissing(LLMParseException):\n ..."
},
{
"identifier": "LLMOutputFieldWrongType",
"path": "typegpt/exceptions.py",
"snippet": "class LLMOutputFieldWrongType(LLMParseException):\n ... | import re
from typing import TYPE_CHECKING, Generic, TypeVar
from .exceptions import LLMOutputFieldMissing, LLMOutputFieldWrongType
from .fields import LLMArrayOutputInfo, LLMFieldInfo, LLMOutputInfo, LLMArrayElementOutputInfo
from .utils.utils import symmetric_strip
from .utils.type_checker import if_response_type, is_response_type, is_array_element_list_type, if_array_element_list_type
from .utils.type_checker import if_response_type, if_array_element_list_type
from .base import BaseLLMResponse, BaseLLMArrayElement | 781 | from __future__ import annotations
_Output = TypeVar("_Output", bound="BaseLLMResponse | BaseLLMArrayElement")
class Parser(Generic[_Output]):
def __init__(self, output_type: type[_Output]):
self.output_type = output_type
self.fields = self.output_type.__fields__.values()
def _regex_for_field(self, field: LLMFieldInfo) -> str:
other_fields = [f for f in self.fields if f.key != field.key]
other_field_names = ["\n" + f.name for f in other_fields]
excluded_lookahead = other_field_names
if not field.info.multiline and not is_response_type(field.type_) and not is_array_element_list_type(field.type_):
excluded_lookahead.append("\n")
# also add current field if it's an array
if isinstance(field.info, LLMArrayOutputInfo) or is_response_type(field.type_):
excluded_lookahead.append("\n" + field.name)
exclusion_cases_regex = "|".join(excluded_lookahead)
if exclusion_cases_regex:
exclusion_cases_regex = f"(?!{exclusion_cases_regex})"
| from __future__ import annotations
_Output = TypeVar("_Output", bound="BaseLLMResponse | BaseLLMArrayElement")
class Parser(Generic[_Output]):
def __init__(self, output_type: type[_Output]):
self.output_type = output_type
self.fields = self.output_type.__fields__.values()
def _regex_for_field(self, field: LLMFieldInfo) -> str:
other_fields = [f for f in self.fields if f.key != field.key]
other_field_names = ["\n" + f.name for f in other_fields]
excluded_lookahead = other_field_names
if not field.info.multiline and not is_response_type(field.type_) and not is_array_element_list_type(field.type_):
excluded_lookahead.append("\n")
# also add current field if it's an array
if isinstance(field.info, LLMArrayOutputInfo) or is_response_type(field.type_):
excluded_lookahead.append("\n" + field.name)
exclusion_cases_regex = "|".join(excluded_lookahead)
if exclusion_cases_regex:
exclusion_cases_regex = f"(?!{exclusion_cases_regex})"
| if isinstance(field.info, LLMOutputInfo) or isinstance(field.info, LLMArrayElementOutputInfo): | 4 | 2023-10-25 22:17:27+00:00 | 2k |
andriioreshk1118/python-storage-main | tests/system/test_transfer_manager.py | [
{
"identifier": "transfer_manager",
"path": "google/cloud/storage/transfer_manager.py",
"snippet": "TM_DEFAULT_CHUNK_SIZE = 32 * 1024 * 1024\nDEFAULT_MAX_WORKERS = 8\nMAX_CRC32C_ZERO_ARRAY_SIZE = 4 * 1024 * 1024\nMETADATA_HEADER_TRANSLATION = {\n \"cacheControl\": \"Cache-Control\",\n \"contentDis... | import tempfile
import os
import pytest
import datetime
import gzip
from google.cloud.storage import transfer_manager
from google.cloud.storage._helpers import _base64_md5hash
from google.api_core import exceptions
from google.cloud._helpers import UTC | 1,412 | # coding=utf-8
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
DEADLINE = 30
encryption_key = "b23ff11bba187db8c37077e6af3b25b8"
def _check_blob_hash(blob, info):
md5_hash = blob.md5_hash
if not isinstance(md5_hash, bytes):
md5_hash = md5_hash.encode("utf-8")
assert md5_hash == info["hash"]
def test_upload_many(shared_bucket, file_data, blobs_to_delete):
FILE_BLOB_PAIRS = [
(file_data["simple"]["path"], shared_bucket.blob("simple1")),
(file_data["simple"]["path"], shared_bucket.blob("simple2")),
]
| # coding=utf-8
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
DEADLINE = 30
encryption_key = "b23ff11bba187db8c37077e6af3b25b8"
def _check_blob_hash(blob, info):
md5_hash = blob.md5_hash
if not isinstance(md5_hash, bytes):
md5_hash = md5_hash.encode("utf-8")
assert md5_hash == info["hash"]
def test_upload_many(shared_bucket, file_data, blobs_to_delete):
FILE_BLOB_PAIRS = [
(file_data["simple"]["path"], shared_bucket.blob("simple1")),
(file_data["simple"]["path"], shared_bucket.blob("simple2")),
]
| results = transfer_manager.upload_many( | 0 | 2023-10-31 10:36:21+00:00 | 2k |
TopGuru777/badsecrets | badsecrets/modules/aspnet_viewstate.py | [
{
"identifier": "unpad",
"path": "badsecrets/helpers.py",
"snippet": "def unpad(s):\n return s[: -ord(s[len(s) - 1 :])]"
},
{
"identifier": "sp800_108_derivekey",
"path": "badsecrets/helpers.py",
"snippet": "def sp800_108_derivekey(key, label, context, keyLengthInBits):\n lblcnt = ... | import re
import hmac
import struct
import base64
import hashlib
import binascii
from Crypto.Cipher import AES
from Crypto.Cipher import DES
from Crypto.Cipher import DES3
from viewstate import ViewState
from contextlib import suppress
from urllib.parse import urlsplit, urlparse
from badsecrets.helpers import unpad, sp800_108_derivekey, sp800_108_get_key_derivation_parameters
from viewstate.exceptions import ViewStateException
from badsecrets.base import BadsecretsBase, generic_base64_regex | 1,372 |
class ASPNET_Viewstate(BadsecretsBase):
check_secret_args = 3
identify_regex = generic_base64_regex
description = {"product": "ASP.NET Viewstate", "secret": "ASP.NET MachineKey", "severity": "CRITICAL"}
def carve_regex(self):
return re.compile(
r"<input.+__VIEWSTATE\"\svalue=\"(.+)\"[\S\s]+<input.+__VIEWSTATEGENERATOR\"\svalue=\"(\w+)\""
)
def carve_to_check_secret(self, s, url=None):
if len(s.groups()) == 2:
r = self.check_secret(s.groups()[0], s.groups()[1], url)
return r
@staticmethod
def valid_preamble(sourcebytes):
if sourcebytes[0:2] == b"\xff\x01":
return True
return False
def viewstate_decrypt(self, ekey_bytes, hash_alg, viewstate_B64, url, mode):
viewstate_bytes = base64.b64decode(viewstate_B64)
vs_size = len(viewstate_bytes)
dec_algos = set()
hash_size = self.hash_sizes[hash_alg]
if (vs_size - hash_size) % AES.block_size == 0:
dec_algos.add("AES")
if (vs_size - hash_size) % DES.block_size == 0:
dec_algos.add("DES")
dec_algos.add("3DES")
for dec_algo in list(dec_algos):
with suppress(ValueError):
if dec_algo == "AES":
block_size = AES.block_size
iv = viewstate_bytes[0:block_size]
if mode == "DOTNET45" and url:
s = Simulate_dotnet45_kdf_context_parameters(url)
label, context = sp800_108_get_key_derivation_parameters(
"WebForms.HiddenFieldPageStatePersister.ClientState", s.get_specific_purposes()
)
ekey_bytes = sp800_108_derivekey(ekey_bytes, label, context, (len(ekey_bytes) * 8))
cipher = AES.new(ekey_bytes, AES.MODE_CBC, iv)
blockpadlen_raw = len(ekey_bytes) % AES.block_size
if blockpadlen_raw == 0:
blockpadlen = block_size
else:
blockpadlen = blockpadlen_raw
elif dec_algo == "3DES":
block_size = DES3.block_size
iv = viewstate_bytes[0:block_size]
cipher = DES3.new(ekey_bytes[:24], DES3.MODE_CBC, iv)
blockpadlen = 16
elif dec_algo == "DES":
block_size = DES.block_size
iv = viewstate_bytes[0:block_size]
cipher = DES.new(ekey_bytes[:8], DES.MODE_CBC, iv)
blockpadlen = 0
encrypted_raw = viewstate_bytes[block_size:-hash_size]
decrypted_raw = cipher.decrypt(encrypted_raw)
with suppress(TypeError):
if mode == "DOTNET45":
|
class ASPNET_Viewstate(BadsecretsBase):
check_secret_args = 3
identify_regex = generic_base64_regex
description = {"product": "ASP.NET Viewstate", "secret": "ASP.NET MachineKey", "severity": "CRITICAL"}
def carve_regex(self):
return re.compile(
r"<input.+__VIEWSTATE\"\svalue=\"(.+)\"[\S\s]+<input.+__VIEWSTATEGENERATOR\"\svalue=\"(\w+)\""
)
def carve_to_check_secret(self, s, url=None):
if len(s.groups()) == 2:
r = self.check_secret(s.groups()[0], s.groups()[1], url)
return r
@staticmethod
def valid_preamble(sourcebytes):
if sourcebytes[0:2] == b"\xff\x01":
return True
return False
def viewstate_decrypt(self, ekey_bytes, hash_alg, viewstate_B64, url, mode):
viewstate_bytes = base64.b64decode(viewstate_B64)
vs_size = len(viewstate_bytes)
dec_algos = set()
hash_size = self.hash_sizes[hash_alg]
if (vs_size - hash_size) % AES.block_size == 0:
dec_algos.add("AES")
if (vs_size - hash_size) % DES.block_size == 0:
dec_algos.add("DES")
dec_algos.add("3DES")
for dec_algo in list(dec_algos):
with suppress(ValueError):
if dec_algo == "AES":
block_size = AES.block_size
iv = viewstate_bytes[0:block_size]
if mode == "DOTNET45" and url:
s = Simulate_dotnet45_kdf_context_parameters(url)
label, context = sp800_108_get_key_derivation_parameters(
"WebForms.HiddenFieldPageStatePersister.ClientState", s.get_specific_purposes()
)
ekey_bytes = sp800_108_derivekey(ekey_bytes, label, context, (len(ekey_bytes) * 8))
cipher = AES.new(ekey_bytes, AES.MODE_CBC, iv)
blockpadlen_raw = len(ekey_bytes) % AES.block_size
if blockpadlen_raw == 0:
blockpadlen = block_size
else:
blockpadlen = blockpadlen_raw
elif dec_algo == "3DES":
block_size = DES3.block_size
iv = viewstate_bytes[0:block_size]
cipher = DES3.new(ekey_bytes[:24], DES3.MODE_CBC, iv)
blockpadlen = 16
elif dec_algo == "DES":
block_size = DES.block_size
iv = viewstate_bytes[0:block_size]
cipher = DES.new(ekey_bytes[:8], DES.MODE_CBC, iv)
blockpadlen = 0
encrypted_raw = viewstate_bytes[block_size:-hash_size]
decrypted_raw = cipher.decrypt(encrypted_raw)
with suppress(TypeError):
if mode == "DOTNET45": | decrypt = unpad(decrypted_raw) | 0 | 2023-10-30 12:52:39+00:00 | 2k |
asprenger/ray_vllm_inference | tests/prompt_format_test.py | [
{
"identifier": "Message",
"path": "ray_vllm_inference/prompt_format.py",
"snippet": "class Message(BaseModel):\n role: Literal[\"system\", \"assistant\", \"user\"]\n content: str\n\n def __str__(self):\n return self.content"
},
{
"identifier": "Prompt",
"path": "ray_vllm_inf... | import unittest
import pytest
from pydantic import ValidationError
from ray_vllm_inference.prompt_format import Message, Prompt, PromptFormat | 1,231 | # Adapted from:
# https://github.com/ray-project/ray-llm/blob/master/rayllm/common/models.py
class PromptFormatCases(unittest.TestCase):
def test_prompt_format_with_prompt_obj(self):
prompt_format = PromptFormat(
system="[system] {instruction} [/system] ",
assistant="[assistant] {instruction} [/assistant] ",
trailing_assistant="[assistant]",
user="[user] {instruction} [/user] ",
default_system_message="",
)
prompt = prompt_format.generate_prompt(
Prompt(
prompt="hello1",
use_prompt_format=True,
)
)
assert prompt == "[user] hello1 [/user] [assistant]"
prompt = prompt_format.generate_prompt(
Prompt(
prompt="hello1",
use_prompt_format=False,
)
)
assert prompt == "hello1"
def test_prompt_format(self):
prompt_format = PromptFormat(
system="[system] {instruction} [/system] ",
assistant="[assistant] {instruction} [/assistant] ",
trailing_assistant="[assistant]",
user="[user] {instruction} [/user] ",
default_system_message="",
)
# Only user, no system
| # Adapted from:
# https://github.com/ray-project/ray-llm/blob/master/rayllm/common/models.py
class PromptFormatCases(unittest.TestCase):
def test_prompt_format_with_prompt_obj(self):
prompt_format = PromptFormat(
system="[system] {instruction} [/system] ",
assistant="[assistant] {instruction} [/assistant] ",
trailing_assistant="[assistant]",
user="[user] {instruction} [/user] ",
default_system_message="",
)
prompt = prompt_format.generate_prompt(
Prompt(
prompt="hello1",
use_prompt_format=True,
)
)
assert prompt == "[user] hello1 [/user] [assistant]"
prompt = prompt_format.generate_prompt(
Prompt(
prompt="hello1",
use_prompt_format=False,
)
)
assert prompt == "hello1"
def test_prompt_format(self):
prompt_format = PromptFormat(
system="[system] {instruction} [/system] ",
assistant="[assistant] {instruction} [/assistant] ",
trailing_assistant="[assistant]",
user="[user] {instruction} [/user] ",
default_system_message="",
)
# Only user, no system | messages = [Message(role="user", content="hello1")] | 0 | 2023-10-28 23:17:59+00:00 | 2k |
fu-feng/GRL | algos/ppo.py | [
{
"identifier": "Actor",
"path": "algos/network.py",
"snippet": "class Actor(Network):\n def __init__(self, layer_num, input_dim, output_dim, hidden_dim, activation_function = torch.tanh,last_activation_mu = None, last_activation_std = None, is_actor=True):\n super(Actor, self).__init__(layer_... | from algos.network import Actor, Critic
from utils.utils import ReplayBuffer, make_mini_batch, convert_to_tensor
import torch
import torch.nn as nn
import torch.optim as optim | 976 |
class PPO(nn.Module):
def __init__(self, device, state_dim, action_dim, args):
super(PPO,self).__init__()
self.args = args
|
class PPO(nn.Module):
def __init__(self, device, state_dim, action_dim, args):
super(PPO,self).__init__()
self.args = args
| self.data = ReplayBuffer(action_prob_exist = True, max_size = self.args.traj_length, state_dim = state_dim, num_action = action_dim) | 2 | 2023-10-27 07:39:01+00:00 | 2k |
CoderMungan/Otel | OtelIcerik/forms.py | [
{
"identifier": "OtelOda",
"path": "OtelIcerik/models.py",
"snippet": "class OtelOda(models.Model):\n otel = models.ForeignKey(OtelYonetim, verbose_name=(\"Otel Adı\"), on_delete=models.CASCADE)\n odaNumarasi = models.CharField((\"Oda Numarası\"), max_length=5)\n odaTipi = models.CharField((\"O... | from django import forms
from .models import OtelOda, KonukBilgileri, KonukCheckInveCheckOut | 957 |
class UpdateOtelOdaForm(forms.ModelForm):
class Meta:
model = OtelOda
fields = ["odaNumarasi","odaTipi","odaTemizMi","odaArizaliMi","odaBosMu","odaProblemi",]
class UpdateMusteriDetay(forms.ModelForm):
class Meta:
|
class UpdateOtelOdaForm(forms.ModelForm):
class Meta:
model = OtelOda
fields = ["odaNumarasi","odaTipi","odaTemizMi","odaArizaliMi","odaBosMu","odaProblemi",]
class UpdateMusteriDetay(forms.ModelForm):
class Meta: | model = KonukBilgileri | 1 | 2023-10-26 02:42:23+00:00 | 2k |
lukas-clarke/pyEight | pyeight/eight.py | [
{
"identifier": "Token",
"path": "pyeight/structs.py",
"snippet": "class Token:\n bearer_token: str\n expiration: float\n main_id: str"
},
{
"identifier": "User",
"path": "pyeight/structs.py",
"snippet": "class User:\n def __init__(self,\n user_name: str,\n ... | import asyncio
import time
import httpx
import atexit
import logging
from aiohttp.client import ClientError, ClientSession, ClientTimeout
from pyeight.constants import *
from pyeight.structs import Token, User | 793 |
_LOGGER = logging.getLogger(__name__)
CLIENT_TIMEOUT = ClientTimeout(total=DEFAULT_TIMEOUT)
class EightSleep():
def __init__(
self,
email: str,
password: str,
client_id: str,
client_secret: str):
self.email = email
self.password = password
self.client_id = client_id
self.client_secret = client_secret
self._api_session = None
self._token = None
self._users = []
# Stop on exit
atexit.register(self.at_exit)
def at_exit(self) -> None:
"""Run at exit."""
try:
loop = asyncio.get_running_loop()
asyncio.run_coroutine_threadsafe(self.stop(), loop).result()
except RuntimeError:
asyncio.run(self.stop())
async def set_heating_level(self, level: int, user_id: str):
""" set heating level from -100 to 100
``user_id`` can either be the name of the user or the side of the bed"""
await self.turn_on_side(user_id) # Turn on side before setting temperature
url = APP_API_URL + f"v1/users/{self.match_user(user_id)}/temperature"
data = {"currentLevel": level}
await self.api_request("PUT", url, data=data)
async def set_heating_and_duration_level(self, level: int, duration_seconds, user_id: str):
""" set heating level from -100 to 100 for a period of time
``user_id`` can either be the name of the user or the side of the bed"""
await self.set_heating_level(level, user_id) # Have to set temperature before duration
url = APP_API_URL + f"v1/users/{self.match_user(user_id)}/temperature"
data = {"timeBased": {"level": level, "durationSeconds": duration_seconds}}
await self.api_request("PUT", url, data=data)
async def turn_on_side(self, user_id: str):
""" Turns on the side of the user
``user_id`` can either be the name of the user or the side of the bed"""
url = APP_API_URL + f"v1/users/{self.match_user(user_id)}/temperature"
data = {"currentState": {"type": "smart"}}
await self.api_request("PUT", url, data=data)
async def turn_off_side(self, user_id: str):
""" Turns off the side of the user
``user_id`` can either be the name of the user or the side of the bed"""
url = APP_API_URL + f"v1/users/{self.match_user(user_id)}/temperature"
data = {"currentState": {"type": "off"}}
await self.api_request("PUT", url, data=data)
|
_LOGGER = logging.getLogger(__name__)
CLIENT_TIMEOUT = ClientTimeout(total=DEFAULT_TIMEOUT)
class EightSleep():
def __init__(
self,
email: str,
password: str,
client_id: str,
client_secret: str):
self.email = email
self.password = password
self.client_id = client_id
self.client_secret = client_secret
self._api_session = None
self._token = None
self._users = []
# Stop on exit
atexit.register(self.at_exit)
def at_exit(self) -> None:
"""Run at exit."""
try:
loop = asyncio.get_running_loop()
asyncio.run_coroutine_threadsafe(self.stop(), loop).result()
except RuntimeError:
asyncio.run(self.stop())
async def set_heating_level(self, level: int, user_id: str):
""" set heating level from -100 to 100
``user_id`` can either be the name of the user or the side of the bed"""
await self.turn_on_side(user_id) # Turn on side before setting temperature
url = APP_API_URL + f"v1/users/{self.match_user(user_id)}/temperature"
data = {"currentLevel": level}
await self.api_request("PUT", url, data=data)
async def set_heating_and_duration_level(self, level: int, duration_seconds, user_id: str):
""" set heating level from -100 to 100 for a period of time
``user_id`` can either be the name of the user or the side of the bed"""
await self.set_heating_level(level, user_id) # Have to set temperature before duration
url = APP_API_URL + f"v1/users/{self.match_user(user_id)}/temperature"
data = {"timeBased": {"level": level, "durationSeconds": duration_seconds}}
await self.api_request("PUT", url, data=data)
async def turn_on_side(self, user_id: str):
""" Turns on the side of the user
``user_id`` can either be the name of the user or the side of the bed"""
url = APP_API_URL + f"v1/users/{self.match_user(user_id)}/temperature"
data = {"currentState": {"type": "smart"}}
await self.api_request("PUT", url, data=data)
async def turn_off_side(self, user_id: str):
""" Turns off the side of the user
``user_id`` can either be the name of the user or the side of the bed"""
url = APP_API_URL + f"v1/users/{self.match_user(user_id)}/temperature"
data = {"currentState": {"type": "off"}}
await self.api_request("PUT", url, data=data)
| async def _get_auth(self) -> Token: | 0 | 2023-10-26 21:11:20+00:00 | 2k |
loliverhennigh/PhantomGaze | phantomgaze/render/camera.py | [
{
"identifier": "normalize",
"path": "phantomgaze/utils/math.py",
"snippet": "@cuda.jit(device=True)\ndef normalize(vector):\n \"\"\"Normalize a vector.\n\n Parameters\n ----------\n vector : tuple\n The vector to normalize.\n\n Returns\n -------\n tuple\n The normaliz... | import math
import numba
from numba import cuda
from phantomgaze.utils.math import normalize, dot, cross | 773 | # Render functions for volumes
@cuda.jit(device=True)
def calculate_ray_direction(
x,
y,
img_shape,
camera_position,
camera_focal,
camera_up):
"""
Calculate the direction of a ray from the camera to the image plane.
Parameters
----------
x : int
The x coordinate of the pixel.
y : int
The y coordinate of the pixel.
img_shape : tuple
The shape of the image.
camera_position : tuple
The position of the camera.
camera_focal : tuple
The focal point of the camera.
camera_up : tuple
The up vector of the camera.
Returns
-------
ray_direction : tuple
"""
# Compute base vectors
forward = (
camera_focal[0] - camera_position[0],
camera_focal[1] - camera_position[1],
camera_focal[2] - camera_position[2],
)
| # Render functions for volumes
@cuda.jit(device=True)
def calculate_ray_direction(
x,
y,
img_shape,
camera_position,
camera_focal,
camera_up):
"""
Calculate the direction of a ray from the camera to the image plane.
Parameters
----------
x : int
The x coordinate of the pixel.
y : int
The y coordinate of the pixel.
img_shape : tuple
The shape of the image.
camera_position : tuple
The position of the camera.
camera_focal : tuple
The focal point of the camera.
camera_up : tuple
The up vector of the camera.
Returns
-------
ray_direction : tuple
"""
# Compute base vectors
forward = (
camera_focal[0] - camera_position[0],
camera_focal[1] - camera_position[1],
camera_focal[2] - camera_position[2],
) | forward = normalize(forward) | 0 | 2023-10-26 23:53:16+00:00 | 2k |
Khushiyant/dockerpulse | dockerpulse/lgbert/bert_pytorch/trainer/pretrain.py | [
{
"identifier": "BERT",
"path": "dockerpulse/lgbert/bert_pytorch/model/bert.py",
"snippet": "class BERT(nn.Module):\r\n \"\"\"\r\n BERT model : Bidirectional Encoder Representations from Transformers.\r\n \"\"\"\r\n\r\n def __init__(self, vocab_size, max_len=512, hidden=768, n_layers=12,\r\n... | import torch
import torch.nn as nn
import time
import tqdm
import numpy as np
import pandas as pd
from torch.optim import Adam
from torch.utils.data import DataLoader
from ..model import BERTLog, BERT
from .optim_schedule import ScheduledOptim
| 1,287 |
class BERTTrainer:
"""
BERTTrainer make the pretrained BERT model with two LM training method.
1. Masked Language Model : 3.3.1 Task #1: Masked LM
2. Next Sentence prediction : 3.3.2 Task #2: Next Sentence Prediction
please check the details on README.md with simple example.
"""
|
class BERTTrainer:
"""
BERTTrainer make the pretrained BERT model with two LM training method.
1. Masked Language Model : 3.3.1 Task #1: Masked LM
2. Next Sentence prediction : 3.3.2 Task #2: Next Sentence Prediction
please check the details on README.md with simple example.
"""
| def __init__(self, bert: BERT, vocab_size: int,
| 0 | 2023-10-29 09:52:36+00:00 | 2k |
audiodude/rainfall | rainfall/blueprint/site.py | [
{
"identifier": "db",
"path": "rainfall/db.py",
"snippet": "class Base(DeclarativeBase):"
},
{
"identifier": "with_current_user",
"path": "rainfall/decorators.py",
"snippet": "def with_current_user(f):\n '''\n Retrieves the current user from the session, performs some checks, and then\... | from uuid import UUID
from rainfall.db import db
from rainfall.decorators import with_current_user, with_current_site
from rainfall.models.site import Site
import flask | 944 |
site = flask.Blueprint('site', __name__)
@site.route('/site', methods=['POST'])
@with_current_user
def create_site(user):
if not user.is_welcomed:
return flask.jsonify(status=400,
error='User has not yet been welcomed'), 400
data = flask.request.get_json()
if data is None:
return flask.jsonify(status=400, error='No JSON provided'), 400
site_data = data.get('site')
if site_data is None:
return flask.jsonify(status=400, error='Missing site data'), 400
if site_data.get('name') is None:
return flask.jsonify(status=400, error='Site name is required'), 400
user.sites.append(Site(**site_data))
db.session.add(user)
db.session.commit()
return '', 204
@site.route('/site/list')
@with_current_user
def list_sites(user):
return flask.jsonify({'sites': [site.serialize() for site in user.sites]})
@site.route('/site/<site_id>')
@with_current_user
|
site = flask.Blueprint('site', __name__)
@site.route('/site', methods=['POST'])
@with_current_user
def create_site(user):
if not user.is_welcomed:
return flask.jsonify(status=400,
error='User has not yet been welcomed'), 400
data = flask.request.get_json()
if data is None:
return flask.jsonify(status=400, error='No JSON provided'), 400
site_data = data.get('site')
if site_data is None:
return flask.jsonify(status=400, error='Missing site data'), 400
if site_data.get('name') is None:
return flask.jsonify(status=400, error='Site name is required'), 400
user.sites.append(Site(**site_data))
db.session.add(user)
db.session.commit()
return '', 204
@site.route('/site/list')
@with_current_user
def list_sites(user):
return flask.jsonify({'sites': [site.serialize() for site in user.sites]})
@site.route('/site/<site_id>')
@with_current_user | @with_current_site | 2 | 2023-10-30 04:43:03+00:00 | 2k |
LasticXYZ/price-simulation | tests/test_poly.py | [
{
"identifier": "Linear",
"path": "poly.py",
"snippet": "class Linear:\n @staticmethod\n def leadin_factor_at(when, factor = 1):\n \"\"\"\n Factor represents the slope of the linear function\n Factor is not a parameter that is originally used in the `broker pallet code`.\n\n ... | import unittest
from poly import Linear, Exponential | 653 |
class TestLinearNoPanic(unittest.TestCase):
def test_linear_no_panic(self):
for limit in range(10):
for target in range(1, 10):
for sold in range(limit + 1):
price = Linear.adapt_price(sold, target, limit)
if sold > target:
self.assertTrue(price > 1)
else:
self.assertTrue(price <= 1)
class TestExponentialNoPanic(unittest.TestCase):
def test_exponential_no_panic(self):
for limit in range(10):
for target in range(1, 10):
for sold in range(limit + 1):
|
class TestLinearNoPanic(unittest.TestCase):
def test_linear_no_panic(self):
for limit in range(10):
for target in range(1, 10):
for sold in range(limit + 1):
price = Linear.adapt_price(sold, target, limit)
if sold > target:
self.assertTrue(price > 1)
else:
self.assertTrue(price <= 1)
class TestExponentialNoPanic(unittest.TestCase):
def test_exponential_no_panic(self):
for limit in range(10):
for target in range(1, 10):
for sold in range(limit + 1): | price = Exponential.adapt_price(sold, target, limit) | 1 | 2023-10-30 12:49:00+00:00 | 2k |
dangeng/flowmag | test_time_adapt.py | [
{
"identifier": "TestTimeAdaptDataset",
"path": "dataset.py",
"snippet": "class TestTimeAdaptDataset(Dataset):\n def __init__(self, root, mode='first', length=None):\n '''\n args:\n root: (string) path to directory of frames\n mode: ['first', 'random'] how to sampl... | from tqdm import tqdm
from torch.optim import Adam
from torch.utils.data import DataLoader
from dataset import TestTimeAdaptDataset
from myutils import AverageMeter
import torch
import matplotlib.pyplot as plt | 1,430 |
def test_time_adapt(model, frames_dir, num_epochs=5, mode='first', device=0, inference_fn=None, inference_freq=1, alpha=None, save_dir=None, dataset_length=None):
'''
params:
model: (nn.Module) model with checkpoint already loaded
frames_dir: (string) path to directory of frames for test time adaptation (OPTIONAL NOW)
dataset: optional dataset to give, default is TestTimeAdaptDataset
num_epochs: (int) number of passes through the frames_dir
mode: ['first', 'random'] how to sample frames
device: device to put model and data on
inference_fn: function to call at the end of each epoch
output:
model: (nn.Module) finetuned input module
'''
model.train()
model = model.to(device)
# Get dataset from frames
# if dataset is None:
dataset = TestTimeAdaptDataset(frames_dir, mode=mode, length=dataset_length)
dataloader = DataLoader(dataset, batch_size=8, shuffle=True, num_workers=4, drop_last=False)
# Optimizer
optimizer = Adam(model.module.trainable_parameters(), lr=1e-4)
# Record losses
|
def test_time_adapt(model, frames_dir, num_epochs=5, mode='first', device=0, inference_fn=None, inference_freq=1, alpha=None, save_dir=None, dataset_length=None):
'''
params:
model: (nn.Module) model with checkpoint already loaded
frames_dir: (string) path to directory of frames for test time adaptation (OPTIONAL NOW)
dataset: optional dataset to give, default is TestTimeAdaptDataset
num_epochs: (int) number of passes through the frames_dir
mode: ['first', 'random'] how to sample frames
device: device to put model and data on
inference_fn: function to call at the end of each epoch
output:
model: (nn.Module) finetuned input module
'''
model.train()
model = model.to(device)
# Get dataset from frames
# if dataset is None:
dataset = TestTimeAdaptDataset(frames_dir, mode=mode, length=dataset_length)
dataloader = DataLoader(dataset, batch_size=8, shuffle=True, num_workers=4, drop_last=False)
# Optimizer
optimizer = Adam(model.module.trainable_parameters(), lr=1e-4)
# Record losses | meter_loss = AverageMeter('loss') | 1 | 2023-10-27 05:23:08+00:00 | 2k |
warner-benjamin/optimi | optimi/adam.py | [
{
"identifier": "MIN_TORCH_2_1",
"path": "optimi/utils.py",
"snippet": "MIN_TORCH_2_1 = parse(torch.__version__) >= parse(\"2.1\")"
},
{
"identifier": "debias_beta",
"path": "optimi/utils.py",
"snippet": "def debias_beta(beta: float, step: int) -> float:\n \"\"\"Applies the Adam-style... | from typing import Any, Callable, Iterable
from warnings import warn
from torch import Tensor
from torch.optim.optimizer import Optimizer, _default_to_fused_or_foreach
from torch.utils._foreach_utils import _group_tensors_by_device_and_dtype
from optimi.utils import MIN_TORCH_2_1, debias_beta
import torch | 1,021 | # Copyright (c) 2023 Benjamin Warner
# SPDX-License-Identifier: MIT
# Based on PyTorch Optimizers
# PyTorch - PyTorch BSD-style license - Copyright (c) 2013-present PyTorch contributors
# Kahan summation inspired by Torch Distributed Experimental's `AnyPrecisionAdamW`
# torchdistX - BSD 3-Clause License - Copyright (c) Meta Platforms, Inc. and affiliates
# Learning rate decoupled weight decay inspired by Composer's `DecoupledSGDW` & `DecoupledAdamW`
# Composer - Apache License 2.0 - Copyright (c) 2022 MosaicML Composer authors
from __future__ import annotations
__all__ = ["Adam", "adam"]
class Adam(Optimizer):
"""Adam optimizer. Optionally with decoupled weight decay (AdamW).
Args:
params: Iterable of parameters to optimize or dicts defining parameter groups
lr: Learning rate
betas: Coefficients for gradient and squared gradient moving averages (default: (0.9, 0.99))
weight_decay: Weight decay coefficient. If `decouple_wd` and `decouple_lr` are False,
applies L2 penalty (default: 0)
eps: Added to denominator to improve numerical stability (default: 1e-6)
decouple_wd: Apply decoupled weight decay instead of L2 penalty (default: False)
decouple_lr: Apply fully decoupled weight decay instead of L2 penalty (default: False)
max_lr: Maximum scheduled learning rate. Set if `lr` is not the maximum scheduled learning
rate and `decouple_lr` is True (default: None)
kahan_sum: Enables Kahan summation for more accurate parameter updates when training in low
precision (float16 or bfloat16). If unspecified, automatically applies for low precision
parameters (default: None)
foreach: Enables the foreach implementation. If unspecified, tries to use foreach over
for-loop implementation since it is significantly faster (default: None)
"""
def __init__(
self,
params: Iterable[Tensor] | Iterable[dict],
lr: float,
betas: tuple[float, float] = (0.9, 0.99),
weight_decay: float = 0,
eps: float = 1e-6,
decouple_wd: bool = False,
decouple_lr: bool = False,
max_lr: float | None = None,
kahan_sum: bool | None = None,
foreach: bool | None = None,
):
if not 0.0 <= lr:
raise ValueError(f"Invalid learning rate: {lr=}")
if not 0.0 <= betas[0] < 1.0:
raise ValueError(f"Invalid beta1 parameter: {betas[0]=}")
if not 0.0 <= betas[1] < 1.0:
raise ValueError(f"Invalid beta2 parameter: {betas[1]=}")
if not 0.0 <= weight_decay:
raise ValueError(f"Invalid weight decay: {weight_decay=}")
if not 0.0 <= eps:
raise ValueError(f"Invalid epsilon: {eps=}")
if decouple_lr and max_lr is None:
max_lr = lr
if max_lr is not None and not 0.0 <= max_lr:
raise ValueError(f"Invalid maximum learning rate: {max_lr=}")
if decouple_lr and weight_decay >= 1e-3:
warn(
f"You are using {weight_decay=} which is potentially high for {decouple_lr=}. Unlike decoupled weight "
f"decay, fully decoupled weight decay does not reduce weight decay by the learning rate.",
category=UserWarning,
)
| # Copyright (c) 2023 Benjamin Warner
# SPDX-License-Identifier: MIT
# Based on PyTorch Optimizers
# PyTorch - PyTorch BSD-style license - Copyright (c) 2013-present PyTorch contributors
# Kahan summation inspired by Torch Distributed Experimental's `AnyPrecisionAdamW`
# torchdistX - BSD 3-Clause License - Copyright (c) Meta Platforms, Inc. and affiliates
# Learning rate decoupled weight decay inspired by Composer's `DecoupledSGDW` & `DecoupledAdamW`
# Composer - Apache License 2.0 - Copyright (c) 2022 MosaicML Composer authors
from __future__ import annotations
__all__ = ["Adam", "adam"]
class Adam(Optimizer):
"""Adam optimizer. Optionally with decoupled weight decay (AdamW).
Args:
params: Iterable of parameters to optimize or dicts defining parameter groups
lr: Learning rate
betas: Coefficients for gradient and squared gradient moving averages (default: (0.9, 0.99))
weight_decay: Weight decay coefficient. If `decouple_wd` and `decouple_lr` are False,
applies L2 penalty (default: 0)
eps: Added to denominator to improve numerical stability (default: 1e-6)
decouple_wd: Apply decoupled weight decay instead of L2 penalty (default: False)
decouple_lr: Apply fully decoupled weight decay instead of L2 penalty (default: False)
max_lr: Maximum scheduled learning rate. Set if `lr` is not the maximum scheduled learning
rate and `decouple_lr` is True (default: None)
kahan_sum: Enables Kahan summation for more accurate parameter updates when training in low
precision (float16 or bfloat16). If unspecified, automatically applies for low precision
parameters (default: None)
foreach: Enables the foreach implementation. If unspecified, tries to use foreach over
for-loop implementation since it is significantly faster (default: None)
"""
def __init__(
self,
params: Iterable[Tensor] | Iterable[dict],
lr: float,
betas: tuple[float, float] = (0.9, 0.99),
weight_decay: float = 0,
eps: float = 1e-6,
decouple_wd: bool = False,
decouple_lr: bool = False,
max_lr: float | None = None,
kahan_sum: bool | None = None,
foreach: bool | None = None,
):
if not 0.0 <= lr:
raise ValueError(f"Invalid learning rate: {lr=}")
if not 0.0 <= betas[0] < 1.0:
raise ValueError(f"Invalid beta1 parameter: {betas[0]=}")
if not 0.0 <= betas[1] < 1.0:
raise ValueError(f"Invalid beta2 parameter: {betas[1]=}")
if not 0.0 <= weight_decay:
raise ValueError(f"Invalid weight decay: {weight_decay=}")
if not 0.0 <= eps:
raise ValueError(f"Invalid epsilon: {eps=}")
if decouple_lr and max_lr is None:
max_lr = lr
if max_lr is not None and not 0.0 <= max_lr:
raise ValueError(f"Invalid maximum learning rate: {max_lr=}")
if decouple_lr and weight_decay >= 1e-3:
warn(
f"You are using {weight_decay=} which is potentially high for {decouple_lr=}. Unlike decoupled weight "
f"decay, fully decoupled weight decay does not reduce weight decay by the learning rate.",
category=UserWarning,
) | if not MIN_TORCH_2_1: | 0 | 2023-10-25 00:51:05+00:00 | 2k |
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.