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
pchunduri6/rag-demystified
complex_qa.py
[ { "identifier": "generate_subquestions", "path": "subquestion_generator.py", "snippet": "def generate_subquestions(\n question,\n file_names: List[str] = None,\n system_prompt=DEFAULT_SUBQUESTION_GENERATOR_PROMPT,\n user_task=DEFAULT_USER_TASK,\n llm_model=\"gpt-4-0613\",\n):\n \"\"\"G...
import os import requests import warnings import evadb from dotenv import load_dotenv from pathlib import Path from subquestion_generator import generate_subquestions from openai_utils import llm_call
2,410
""" res_batch = cursor.query( f"""SELECT data FROM {doc_name}_features ORDER BY Similarity(SentenceFeatureExtractor('{question}'),features) LIMIT 3;""" ).df() context_list = [] for i in range(len(res_batch)): context_list.append(res_batch["data"][i]) context = "\n...
warnings.filterwarnings("ignore") if not load_dotenv(): print( "Could not load .env file or it is empty. Please check if it exists and is readable." ) exit(1) def generate_vector_stores(cursor, docs): """Generate a vector store for the docs using evadb. """ for doc in docs: ...
subquestions_bundle_list, cost = generate_subquestions(question=question,
0
2023-10-18 16:32:51+00:00
4k
predibase/lorax
server/lorax_server/utils/sources/hub.py
[ { "identifier": "BaseModelSource", "path": "server/lorax_server/utils/sources/source.py", "snippet": "class BaseModelSource:\n def remote_weight_files(self, extension: str = None):\n raise NotImplementedError\n\n def weight_files(self, extension: str = None):\n raise NotImplementedEr...
import time import os from datetime import timedelta from loguru import logger from pathlib import Path from typing import Optional, List from huggingface_hub import HfApi, hf_hub_download from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE from huggingface_hub.utils import ( LocalEntryNotFoundError, En...
1,689
and "arguments" not in s.rfilename and "args" not in s.rfilename and "training" not in s.rfilename ] if not filenames: raise EntryNotFoundError( f"No {extension} weights found for model {model_id} and revision {revision}.", None, ) return fil...
WEIGHTS_CACHE_OVERRIDE = os.getenv("WEIGHTS_CACHE_OVERRIDE", None) def get_hub_model_local_dir(model_id: str) -> Path: object_id = model_id.replace("/", "--") repo_cache = Path(HUGGINGFACE_HUB_CACHE) / f"models--{object_id}" return repo_cache def weight_hub_files( model_id: str, revision: Option...
class HubModelSource(BaseModelSource):
0
2023-10-20 18:19:49+00:00
4k
codefuse-ai/Test-Agent
chat/server/gradio_web_server.py
[ { "identifier": "SeparatorStyle", "path": "chat/conversation.py", "snippet": "class SeparatorStyle(IntEnum):\n \"\"\"Separator styles.\"\"\"\n\n ADD_COLON_SINGLE = auto()\n ADD_COLON_TWO = auto()\n ADD_COLON_SPACE_SINGLE = auto()\n NO_COLON_SINGLE = auto()\n NO_COLON_TWO = auto()\n ...
import argparse import datetime import json import os import random import time import uuid import gradio as gr import requests from collections import defaultdict from chat.conversation import SeparatorStyle from chat.constants import ( LOGDIR, WORKER_API_TIMEOUT, ErrorCode, MODERATION_MSG, CONVERS...
3,567
openai_compatible_models_info = json.load( open(register_openai_compatible_models) ) models += list(openai_compatible_models_info.keys()) if add_chatgpt: models += ["gpt-3.5-turbo", "gpt-4"] if add_claude: models += ["claude-2", "claude-instant-1"] if add...
""" The gradio demo server for chatting with a single model. """ logger = build_logger("gradio_web_server", "gradio_web_server.log") headers = {"User-Agent": "FastChat Client"} no_change_btn = gr.Button.update() enable_btn = gr.Button.update(interactive=True) disable_btn = gr.Button.update(interactive=False) co...
flagged = violates_moderation(text)
17
2023-10-20 08:56:20+00:00
4k
thuml/iTransformer
model/iInformer.py
[ { "identifier": "Encoder", "path": "layers/Transformer_EncDec.py", "snippet": "class Encoder(nn.Module):\n def __init__(self, attn_layers, conv_layers=None, norm_layer=None):\n super(Encoder, self).__init__()\n self.attn_layers = nn.ModuleList(attn_layers)\n self.conv_layers = nn...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from layers.Transformer_EncDec import Encoder, EncoderLayer from layers.SelfAttention_Family import ProbAttention, AttentionLayer from layers.Embed import DataEmbedding_inverted
2,602
class Model(nn.Module): """ Vanilla Transformer with O(L^2) complexity Paper link: https://proceedings.neurips.cc/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf """ def __init__(self, configs): super(Model, self).__init__() self.seq_len = configs.seq_len se...
class Model(nn.Module): """ Vanilla Transformer with O(L^2) complexity Paper link: https://proceedings.neurips.cc/paper/2017/file/3f5ee243547dee91fbd053c1c4a845aa-Paper.pdf """ def __init__(self, configs): super(Model, self).__init__() self.seq_len = configs.seq_len se...
EncoderLayer(
1
2023-10-19 03:23:15+00:00
4k
kylesargent/ZeroNVS
threestudio/models/prompt_processors/base.py
[ { "identifier": "BaseObject", "path": "threestudio/utils/base.py", "snippet": "class BaseObject(Updateable):\n @dataclass\n class Config:\n pass\n\n cfg: Config # add this to every subclass of BaseObject to enable static type checking\n\n def __init__(\n self, cfg: Optional[Un...
import json import os import torch import torch.multiprocessing as mp import torch.nn as nn import torch.nn.functional as F import threestudio import hashlib from dataclasses import dataclass, field from pytorch_lightning.utilities.rank_zero import rank_zero_only from transformers import AutoTokenizer, BertForMaske...
1,611
def hash_prompt(model: str, prompt: str) -> str: identifier = f"{model}-{prompt}" return hashlib.md5(identifier.encode()).hexdigest() @dataclass class DirectionConfig: name: str prompt: Callable[[str], str] negative_prompt: Callable[[str], str] condition: Callable[ [Float[Tensor, "B...
def hash_prompt(model: str, prompt: str) -> str: identifier = f"{model}-{prompt}" return hashlib.md5(identifier.encode()).hexdigest() @dataclass class DirectionConfig: name: str prompt: Callable[[str], str] negative_prompt: Callable[[str], str] condition: Callable[ [Float[Tensor, ...
-shifted_expotional_decay(*self.perp_neg_f_fs, r_inter),
5
2023-10-24 19:02:44+00:00
4k
princeton-nlp/LLM-Shearing
llmshearing/utils/post_pruning_processing.py
[ { "identifier": "ComposerMosaicLlama", "path": "llmshearing/models/composer_llama.py", "snippet": "class ComposerMosaicLlama(ComposerModel):\n \"\"\" Llama model with the Composer model interface. \"\"\"\n def __init__(self, cfg):\n super().__init__()\n self.model = LlamaModel(cfg)\n...
import glob import os import torch import fire from llmshearing.models.composer_llama import ComposerMosaicLlama from llmshearing.utils.utils import load_weights
1,703
def prune_and_save_model(path): """ prune and save the model after pruning """ outpath = os.path.dirname(path) + f"/pruned-{os.path.basename(path)}" config_file = os.path.join(os.path.dirname(path), "config.pt") assert os.path.exists(config_file), f"Config file {config_file} does not exist" ...
def prune_and_save_model(path): """ prune and save the model after pruning """ outpath = os.path.dirname(path) + f"/pruned-{os.path.basename(path)}" config_file = os.path.join(os.path.dirname(path), "config.pt") assert os.path.exists(config_file), f"Config file {config_file} does not exist" ...
model = ComposerMosaicLlama(cfg)
0
2023-10-16 12:26:08+00:00
4k
hugoycj/Instant-angelo
models/nerf.py
[ { "identifier": "BaseModel", "path": "models/base.py", "snippet": "class BaseModel(nn.Module):\n def __init__(self, config):\n super().__init__()\n self.config = config\n self.rank = get_rank()\n self.setup()\n if self.config.get('weights', None):\n self....
import math import torch import torch.nn as nn import torch.nn.functional as F import models from models.base import BaseModel from models.utils import chunk_batch from systems.utils import update_module_step from nerfacc import ContractionType, OccupancyGrid, ray_marching, render_weight_from_density, accumulate_along_...
1,891
@models.register('nerf') class NeRFModel(BaseModel): def setup(self): self.geometry = models.make(self.config.geometry.name, self.config.geometry) self.texture = models.make(self.config.texture.name, self.config.texture) self.register_buffer('scene_aabb', torch.as_tensor([-self.config.radiu...
@models.register('nerf') class NeRFModel(BaseModel): def setup(self): self.geometry = models.make(self.config.geometry.name, self.config.geometry) self.texture = models.make(self.config.texture.name, self.config.texture) self.register_buffer('scene_aabb', torch.as_tensor([-self.config.ra...
out = chunk_batch(self.forward_, self.config.ray_chunk, True, rays)
1
2023-10-22 02:53:17+00:00
4k
HKUDS/GraphGPT
graphgpt/serve/model_worker_graph.py
[ { "identifier": "WORKER_HEART_BEAT_INTERVAL", "path": "graphgpt/constants.py", "snippet": "WORKER_HEART_BEAT_INTERVAL = int(os.getenv(\"FASTCHAT_WORKER_HEART_BEAT_INTERVAL\", 30))" }, { "identifier": "build_logger", "path": "graphgpt/utils.py", "snippet": "def build_logger(logger_name, l...
import argparse import asyncio import json import time import threading import uuid import requests import torch import uvicorn from fastapi import FastAPI, Request, BackgroundTasks from fastapi.responses import StreamingResponse from functools import partial from graphgpt.constants import WORKER_HEART_BEAT_INTERVAL fr...
3,374
GB = 1 << 30 worker_id = str(uuid.uuid4())[:6] logger = build_logger("model_worker", f"model_worker_{worker_id}.log") global_counter = 0 model_semaphore = None def heart_beat_worker(controller): while True: time.sleep(WORKER_HEART_BEAT_INTERVAL) controller.send_heart_beat() class ModelWork...
""" A model worker executes the model. """ GB = 1 << 30 worker_id = str(uuid.uuid4())[:6] logger = build_logger("model_worker", f"model_worker_{worker_id}.log") global_counter = 0 model_semaphore = None def heart_beat_worker(controller): while True: time.sleep(WORKER_HEART_BEAT_INTERVAL) co...
replace_token = DEFAULT_IM_START_TOKEN + replace_token + DEFAULT_IM_END_TOKEN
3
2023-10-15 05:13:24+00:00
4k
hkchengrex/Cutie
cutie/model/cutie.py
[ { "identifier": "AuxComputer", "path": "cutie/model/aux_modules.py", "snippet": "class AuxComputer(nn.Module):\n def __init__(self, cfg: DictConfig):\n super().__init__()\n\n use_sensory_aux = cfg.model.aux_loss.sensory.enabled\n self.use_query_aux = cfg.model.aux_loss.query.enab...
from typing import List, Dict from omegaconf import DictConfig from cutie.model.modules import * from cutie.model.big_modules import * from cutie.model.aux_modules import AuxComputer from cutie.model.utils.memory_utils import * from cutie.model.transformer.object_transformer import QueryTransformer from cutie.model.tra...
3,036
log = logging.getLogger() class CUTIE(nn.Module): def __init__(self, cfg: DictConfig, *, single_object=False): super().__init__() model_cfg = cfg.model self.ms_dims = model_cfg.pixel_encoder.ms_dims self.key_dim = model_cfg.key_dim self.value_dim = model_cfg.value_dim ...
log = logging.getLogger() class CUTIE(nn.Module): def __init__(self, cfg: DictConfig, *, single_object=False): super().__init__() model_cfg = cfg.model self.ms_dims = model_cfg.pixel_encoder.ms_dims self.key_dim = model_cfg.key_dim self.value_dim = model_cfg.value_dim ...
self.aux_computer = AuxComputer(cfg)
0
2023-10-19 17:49:24+00:00
4k
DeepGraphLearning/ULTRA
ultra/util.py
[ { "identifier": "models", "path": "ultra/models.py", "snippet": "class Ultra(nn.Module):\nclass RelNBFNet(BaseNBFNet):\nclass EntityNBFNet(BaseNBFNet):\n def __init__(self, rel_model_cfg, entity_model_cfg):\n def forward(self, data, batch):\n def __init__(self, input_dim, hidden_dims, num_relat...
import os import sys import ast import copy import time import logging import argparse import yaml import jinja2 import easydict import torch from jinja2 import meta from torch import distributed as dist from torch_geometric.data import Data from torch_geometric.datasets import RelLinkPredDataset, WordNet18RR from ultr...
2,154
env = jinja2.Environment() tree = env.parse(raw) vars = meta.find_undeclared_variables(tree) return vars def load_config(cfg_file, context=None): with open(cfg_file, "r") as fin: raw = fin.read() template = jinja2.Template(raw) instance = template.render(context) cfg = yaml.saf...
logger = logging.getLogger(__file__) def detect_variables(cfg_file): with open(cfg_file, "r") as fin: raw = fin.read() env = jinja2.Environment() tree = env.parse(raw) vars = meta.find_undeclared_variables(tree) return vars def load_config(cfg_file, context=None): with open(cfg_...
ds_cls = getattr(datasets, cls)
1
2023-10-23 17:06:10+00:00
4k
ZhengyiLuo/PerpetualHumanoidControl
phc/learning/im_amp.py
[ { "identifier": "RunningMeanStd", "path": "phc/utils/running_mean_std.py", "snippet": "class RunningMeanStd(nn.Module):\n\n def __init__(self,\n insize,\n epsilon=1e-05,\n per_channel=False,\n norm_only=False):\n super(RunningMean...
import glob import os import sys import pdb import os.path as osp import time import numpy as np import torch import learning.replay_buffer as replay_buffer import phc.learning.amp_agent as amp_agent import joblib import gc from phc.utils.running_mean_std import RunningMeanStd from rl_games.algos_torch import torch_ext...
3,162
sys.path.append(os.getcwd()) class IMAmpAgent(amp_agent.AMPAgent): def __init__(self, base_name, config): super().__init__(base_name, config) def get_action(self, obs_dict, is_determenistic=False): obs = obs_dict["obs"] if self.has_batch_dimension == False: ...
sys.path.append(os.getcwd()) class IMAmpAgent(amp_agent.AMPAgent): def __init__(self, base_name, config): super().__init__(base_name, config) def get_action(self, obs_dict, is_determenistic=False): obs = obs_dict["obs"] if self.has_batch_dimension == False: ...
if not flags.has_eval:
2
2023-10-15 19:05:47+00:00
4k
laike9m/Python-Type-Challenges
tests/test_challenge.py
[ { "identifier": "ChallengeKey", "path": "views/challenge.py", "snippet": "class ChallengeKey:\n level: Level\n name: ChallengeName\n\n @classmethod\n def from_str(cls, key: str):\n \"\"\"Create a key object from a string like \"basic-foo\".\"\"\"\n level, name = key.split(\"-\"...
from pathlib import Path from views.challenge import ChallengeKey, ChallengeManager import pytest
1,788
class TestLoadChallenges: def test_load_empty_dir(self, tmpdir): assert ChallengeManager(Path(tmpdir)).challenge_count == 0 def test_defaults(self): assert ChallengeManager().challenge_count > 0 def test_load_tests_assets(self, assets_dir): mgr = ChallengeManager(assets_dir / "c...
class TestLoadChallenges: def test_load_empty_dir(self, tmpdir): assert ChallengeManager(Path(tmpdir)).challenge_count == 0 def test_defaults(self): assert ChallengeManager().challenge_count > 0 def test_load_tests_assets(self, assets_dir): mgr = ChallengeManager(assets_dir / "c...
c_foo = challenge_mgr.get_challenge(ChallengeKey.from_str("basic-foo"))
0
2023-10-23 05:11:41+00:00
4k
uni-medical/SAM-Med3D
train.py
[ { "identifier": "sam_model_registry3D", "path": "segment_anything/build_sam3D.py", "snippet": "def build_sam3D_vit_h(checkpoint=None):\ndef build_sam3D_vit_l(checkpoint=None):\ndef build_sam3D_vit_b(checkpoint=None):\ndef build_sam3D_vit_b_ori(checkpoint=None):\ndef _build_sam3D(\n encoder_embed_dim,...
import numpy as np import random import datetime import logging import matplotlib.pyplot as plt import os import torch import torch.distributed as dist import torch.nn.functional as F import torchio as tio import argparse import torch.multiprocessing as mp from tqdm import tqdm from torch.backends import cudnn from to...
1,960
# set up environment join = os.path.join # %% set up parser parser = argparse.ArgumentParser() parser.add_argument('--task_name', type=str, default='union_train') parser.add_argument('--click_type', type=str, default='random') parser.add_argument('--multi_click', action='store_true', default=False) parser.add_argumen...
# set up environment join = os.path.join # %% set up parser parser = argparse.ArgumentParser() parser.add_argument('--task_name', type=str, default='union_train') parser.add_argument('--click_type', type=str, default='random') parser.add_argument('--multi_click', action='store_true', default=False) parser.add_argumen...
sam_model = sam_model_registry3D[args.model_type](checkpoint=None).to(device)
0
2023-10-23 15:41:07+00:00
4k
VikParuchuri/libgen_to_txt
download_and_clean.py
[ { "identifier": "get_file_path", "path": "libgen_to_txt/files.py", "snippet": "def get_file_path(num, client, parent_id):\n files = client.File.list(parent_id=parent_id)\n try:\n sel_file = [f for f in files if get_leading_digits(f.name) == num][0]\n except IndexError:\n return\n ...
import argparse import multiprocessing import putiopy import os from concurrent.futures import ProcessPoolExecutor from itertools import repeat from tqdm import tqdm from libgen_to_txt.files import get_file_path, download_folder, download_folder_locally, delete_file_locally, \ get_parent_id from libgen_to_txt.marke...
1,814
def process_single_libgen_chunk(torrent_info, conversion_lock, no_download, no_delete, max_workers=settings.CONVERSION_WORKERS): num, url = torrent_info client = putiopy.Client(settings.PUTIO_TOKEN, timeout=15, use_retry=True) parent_folder_id = get_parent_id(client) sel_file = get_file_path(num, c...
def process_single_libgen_chunk(torrent_info, conversion_lock, no_download, no_delete, max_workers=settings.CONVERSION_WORKERS): num, url = torrent_info client = putiopy.Client(settings.PUTIO_TOKEN, timeout=15, use_retry=True) parent_folder_id = get_parent_id(client) sel_file = get_file_path(num, c...
delete_file_locally(sel_file.name)
3
2023-10-16 17:56:36+00:00
4k
NVIDIA/GenerativeAIExamples
RetrievalAugmentedGeneration/examples/developer_rag/chains.py
[ { "identifier": "LimitRetrievedNodesLength", "path": "RetrievalAugmentedGeneration/common/utils.py", "snippet": "class LimitRetrievedNodesLength(BaseNodePostprocessor):\n \"\"\"Llama Index chain filter to limit token lengths.\"\"\"\n\n def _postprocess_nodes(\n self, nodes: List[\"NodeWithS...
import base64 import os import logging from pathlib import Path from typing import Generator from llama_index import Prompt, download_loader from llama_index.query_engine import RetrieverQueryEngine from llama_index.response.schema import StreamingResponse from llama_index.node_parser import LangchainNodeParser from Re...
1,951
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ht...
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ht...
index = get_vector_index()
5
2023-10-19 13:46:31+00:00
4k
MolecularAI/REINVENT4
reinvent/runmodes/TL/linkinvent.py
[ { "identifier": "Learning", "path": "reinvent/runmodes/TL/learning.py", "snippet": "class Learning(ABC):\n \"\"\"Trains a given model with new data from SMILES.\"\"\"\n\n def __init__(\n self,\n model: ModelAdapter,\n tb_logdir: str,\n configuration: Configuration,\n ...
import logging from .learning import Learning from reinvent.models.linkinvent.dataset.paired_dataset import PairedDataset
3,182
"""LinkInvent transfer learning Train a given model with new data. The data comes from a file with SMILES strings. The file is assumed to be in multi-column format separated by commas (CSV) or spaces. The SMILES strings are taken from the first two columns. The two SMILES in each row correspond to two pipe-symbol ...
"""LinkInvent transfer learning Train a given model with new data. The data comes from a file with SMILES strings. The file is assumed to be in multi-column format separated by commas (CSV) or spaces. The SMILES strings are taken from the first two columns. The two SMILES in each row correspond to two pipe-symbol ...
class Linkinvent(Learning):
0
2023-10-20 06:43:16+00:00
4k
lion-agi/lionagi
lionagi/loaders/chunker.py
[ { "identifier": "lcall", "path": "lionagi/utils/call_util.py", "snippet": "def lcall(\n input_: Any, func_: Callable, flatten: bool = False, \n dropna: bool = False, **kwargs\n ) -> List[Any]:\n \"\"\"\n Applies a function to each element of `input`, after converting it to a list.\n\n ...
from typing import Union, Callable from lionagi.utils import lcall from lionagi.schema import DataNode from lionagi.bridge import langchain_text_splitter, from_langchain, llama_index_node_parser, from_llama_index from .load_util import ChunkerType, file_to_chunks
2,973
Returns: List[DataNode]: The list of converted DataNode instances. """ for i in range(len(documents)): if type(documents[i]) == DataNode: if chunker_type == ChunkerType.LLAMAINDEX: documents[i] = documents[i].to_llama_index() elif chunker_type == ...
# use utils, schema and bridge # Function to convert documents to a specific format based on the chunker type def datanodes_convert(documents, chunker_type): """ Converts a lionagi DataNode documents to a specific format based on the chunker type. Parameters: documents (List[DataNode]): A li...
nodes = llama_index_node_parser(documents, chunker, chunker_args, chunker_kwargs, chunking_kwargs)
5
2023-10-17 03:10:02+00:00
4k
ziqipang/LM4VisualEncoding
pointcloud_classification/models/Point_BERT.py
[ { "identifier": "Group", "path": "pointcloud_classification/models/dvae.py", "snippet": "class Group(nn.Module):\n def __init__(self, num_group, group_size):\n super().__init__()\n self.num_group = num_group\n self.group_size = group_size\n # self.knn = KNN(k=self.group_si...
import torch import torch.nn as nn import torch.nn.functional as F import timm import numpy as np import random from pathlib import Path from timm.models.layers import DropPath, trunc_normal_ from .dvae import Group from .dvae import DiscreteVAE, Encoder from .llama import LLaMATransformer from .build import MODELS fro...
3,370
class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_fea...
class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_features = out_features or in_features hidden_features = hidden_features or in_features self.fc1 = nn.Linear(in_features, hidden_fea...
@MODELS.register_module()
4
2023-10-19 15:40:57+00:00
4k
stanford-oval/WikiChat
benchmark/scripts/automatic_eval.py
[ { "identifier": "DialogueTurn", "path": "pipelines/dialog_turn.py", "snippet": "class DialogueTurn:\n def __init__(\n self,\n agent_utterance: str = None,\n user_utterance: str = None,\n pipeline: str = None,\n engine: str = None,\n generate_engine: str = Non...
from concurrent.futures import ThreadPoolExecutor from typing import List from tqdm import tqdm from scipy.stats import ttest_ind from pipelines.dialog_turn import DialogueTurn from llm.llm_generate import llm_generate from llm.global_variables import get_total_cost import json import argparse import numpy as np import...
2,596
sys.path.insert(0, "./") logger = logging.getLogger(__name__) def get_feedback(object_dlg_history: List[DialogueTurn], new_dlg_turn: DialogueTurn):
sys.path.insert(0, "./") logger = logging.getLogger(__name__) def get_feedback(object_dlg_history: List[DialogueTurn], new_dlg_turn: DialogueTurn):
feedback = llm_generate(
1
2023-10-19 18:17:25+00:00
4k
TonicAI/tvalmetrics
tonic_validate/metrics/answer_consistency_metric.py
[ { "identifier": "LLMResponse", "path": "tonic_validate/classes/llm_response.py", "snippet": "class LLMResponse(BaseModel):\n llm_answer: str\n llm_context_list: list[str]\n benchmark_item: BenchmarkItem" }, { "identifier": "Metric", "path": "tonic_validate/metrics/metric.py", "s...
import logging from tonic_validate.classes.llm_response import LLMResponse from tonic_validate.metrics.metric import Metric from tonic_validate.utils.metrics_util import ( parse_boolean_response, parse_bullet_list_response, ) from tonic_validate.services.openai_service import OpenAIService from tonic_validate.u...
1,742
logger = logging.getLogger() class AnswerConsistencyMetric(Metric): name = "answer_consistency" def score(self, llm_response: LLMResponse, openai_service: OpenAIService) -> float:
logger = logging.getLogger() class AnswerConsistencyMetric(Metric): name = "answer_consistency" def score(self, llm_response: LLMResponse, openai_service: OpenAIService) -> float:
main_points_response = main_points_call(llm_response.llm_answer, openai_service)
5
2023-10-23 21:38:11+00:00
4k
jhejna/cpl
research/datasets/replay_buffer/sampling.py
[ { "identifier": "utils", "path": "research/utils/utils.py", "snippet": "def to_device(batch: Any, device: torch.device) -> Any:\ndef to_tensor(batch: Any) -> Any:\ndef to_np(batch: Any) -> Any:\ndef remove_float64(batch: Any):\ndef unsqueeze(batch: Any, dim: int) -> Any:\ndef squeeze(batch: Any, dim: in...
import copy import numpy as np from typing import Callable, Optional, Tuple from research.utils import utils from .storage import Storage
1,743
""" This file defines a number of sampling functions used by the replay buffer. Each sample function returns tensors of the following shape: (Batch, Time, dims...) and requires `storage` and `discount` arguments. Many of these functions have large blocks of repeated code, but are implemented separately for readab...
""" This file defines a number of sampling functions used by the replay buffer. Each sample function returns tensors of the following shape: (Batch, Time, dims...) and requires `storage` and `discount` arguments. Many of these functions have large blocks of repeated code, but are implemented separately for readab...
batch[k] = discount * utils.get_from_batch(storage[k], sample_idxs)
0
2023-10-19 17:25:45+00:00
4k
nbasyl/LLM-FP4
lm_eval/tasks/triviaqa.py
[ { "identifier": "Task", "path": "lm_eval/base.py", "snippet": "class LM(abc.ABC):\nclass BaseLM(LM):\nclass Task(abc.ABC):\nclass MultipleChoiceTask(Task):\nclass PerplexityTask(Task, abc.ABC):\nclass CacheHook:\nclass CachingLM:\nclass Request:\nclass RequestFactory:\n def __init__(self):\n def l...
import inspect import string from lm_eval.base import Task, rf from lm_eval.metrics import mean
1,617
""" TriviaQA: A Large Scale Distantly Supervised Challenge Dataset for Reading Comprehension https://arxiv.org/pdf/1705.03551.pdf TriviaQA is a reading comprehension dataset containing over 650K question-answer-evidence triples. TriviaQA includes 95K question-answer pairs authored by trivia enthusiasts and independent...
""" TriviaQA: A Large Scale Distantly Supervised Challenge Dataset for Reading Comprehension https://arxiv.org/pdf/1705.03551.pdf TriviaQA is a reading comprehension dataset containing over 650K question-answer-evidence triples. TriviaQA includes 95K question-answer pairs authored by trivia enthusiasts and independent...
continuation = rf.greedy_until(ctx, {"until": ["\n", ".", ","]})
0
2023-10-15 06:05:13+00:00
4k
alextamkin/generative-elicitation
run_human_evaluation.py
[ { "identifier": "FromSavedFileAgent", "path": "from_saved_file_agent.py", "snippet": "class FromSavedFileAgent(BaseActiveLearningAgent):\n \"\"\"Agent that loads generated interactions (queries and answers) from a saved file.\"\"\"\n\n def __init__(self, target_specification_file, engine, openai_c...
import glob import sys import json import os import random import pandas as pd from tap import Tap from from_saved_file_agent import FromSavedFileAgent from run_model_evaluation import run_problem_instance from tqdm import tqdm
3,013
task_specific_directives = { "website_preferences": '\nFor this task, "yes" means the user would like the website, and "no" means the user would not like the website', "moral_reasoning": '\nFor this task, "yes" means the user would believe it is ethical to steal a loaf of bread, and "no" means the user wou...
task_specific_directives = { "website_preferences": '\nFor this task, "yes" means the user would like the website, and "no" means the user would not like the website', "moral_reasoning": '\nFor this task, "yes" means the user would believe it is ethical to steal a loaf of bread, and "no" means the user wou...
agent_class=FromSavedFileAgent,
0
2023-10-16 18:43:47+00:00
4k
bcmi/libcom
libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/openaimodel.py
[ { "identifier": "checkpoint", "path": "libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/util.py", "snippet": "def checkpoint(func, inputs, params, flag):\n \"\"\"\n Evaluate a function without caching intermediate activations, allowing for\n reduced memory at...
from abc import abstractmethod from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.modules.diffusionmodules.util import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_module, normalization, timestep_embedding, ) from libcom.painterly_image_harmonization.source.PHDiffusion.ldm....
3,221
# dummy replace def convert_module_to_f16(x): pass def convert_module_to_f32(x): pass ## go class AttentionPool2d(nn.Module): """ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py """ def __init__( self, spacial_dim: int, embed_dim: int, ...
# dummy replace def convert_module_to_f16(x): pass def convert_module_to_f32(x): pass ## go class AttentionPool2d(nn.Module): """ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py """ def __init__( self, spacial_dim: int, embed_dim: int, ...
elif isinstance(layer, SpatialTransformer):
7
2023-10-19 05:08:12+00:00
4k
facebookresearch/motif
rlaif/annotators.py
[ { "identifier": "BlstatsTransform", "path": "rlaif/annotators_transforms.py", "snippet": "class BlstatsTransform:\n def __init__(self, blstats_keys: List[str]):\n self.blstats_keys = blstats_keys\n self.hunger_num_to_str = {\n 0: \"Satiated\", 1: \"\", 2: \"Hungry\", 3: \"Weak\...
from abc import ABC, abstractmethod from typing import Dict, List, Callable, Optional, Tuple, Sequence from rlaif.annotators_transforms import BlstatsTransform, MessageTransform from rlaif.prompts import system_prompts, prompt_templates, goal_strings, regexes, retry_prompts from rlaif.llms import LocalLanguageModel, An...
2,345
class Annotator(ABC): def __init__(self, batch_size: int): self.batch_size = batch_size @abstractmethod def __call__(self, batch: Dict[str, np.ndarray], logging_indices: Sequence[int]) -> np.array: """General method which takes two sequences and returns whether the second element ...
class Annotator(ABC): def __init__(self, batch_size: int): self.batch_size = batch_size @abstractmethod def __call__(self, batch: Dict[str, np.ndarray], logging_indices: Sequence[int]) -> np.array: """General method which takes two sequences and returns whether the second element ...
self.llm = LocalLanguageModel(system_prompt=system_prompts[prompt_version],
2
2023-10-24 17:45:26+00:00
4k
kyegomez/PALI3
pali3/main.py
[ { "identifier": "UL2", "path": "pali3/ul2.py", "snippet": "class UL2(nn.Module):\n def __init__(\n self,\n *,\n dim,\n tie_token_emb=False,\n ignore_index=-100,\n pad_value=0,\n cross_attn_tokens_dropout=0.0,\n **kwargs,\n ):\n super()...
import torch from torch import nn from pali3.ul2 import UL2, ViTransformerWrapper, Encoder
2,051
class PrependTokens(nn.Module): """ # Initialize models vit_model = ViTModel() text_embedding = TextEmbedding("bert-base-uncased") # Initialize PrependVisualTokens prepend_visual_tokens = PrependVisualTokens(vit_model, text_embedding) # Process image and text img = torch.randn(1, 3,...
class PrependTokens(nn.Module): """ # Initialize models vit_model = ViTModel() text_embedding = TextEmbedding("bert-base-uncased") # Initialize PrependVisualTokens prepend_visual_tokens = PrependVisualTokens(vit_model, text_embedding) # Process image and text img = torch.randn(1, 3,...
self.vit = ViTransformerWrapper(
1
2023-10-16 15:36:54+00:00
4k
pgorecki/lato
tests/test_application_example_from_readme.py
[ { "identifier": "Application", "path": "lato/application.py", "snippet": "class Application(ApplicationModule):\n dependency_provider_class = SimpleDependencyProvider\n\n def __init__(self, name=__name__, dependency_provider=None, **kwargs):\n super().__init__(name)\n self.dependency...
from uuid import uuid4 from lato import Application, Event, Task, TransactionContext
1,973
class UserService: def create_user(self, email, password): ... class EmailService: def send_welcome_email(self, email): ... def test_application_example_from_readme():
class UserService: def create_user(self, email, password): ... class EmailService: def send_welcome_email(self, email): ... def test_application_example_from_readme():
app = Application(
0
2023-10-21 11:33:05+00:00
4k
NVIDIA/trt-llm-rag-windows
app.py
[ { "identifier": "TrtLlmAPI", "path": "trt_llama_api.py", "snippet": "class TrtLlmAPI(CustomLLM):\n model_path: Optional[str] = Field(\n description=\"The path to the trt engine.\"\n )\n temperature: float = Field(description=\"The temperature to use for sampling.\")\n max_new_tokens: ...
import time import gradio as gr import argparse from trt_llama_api import TrtLlmAPI #llama_index does not currently support TRT-LLM. The trt_llama_api.py file defines a llama_index compatible interface for TRT-LLM. from langchain.embeddings.huggingface import HuggingFaceEmbeddings from llama_index import LangchainEmbed...
3,532
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: MIT # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without res...
# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: MIT # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without res...
llm = TrtLlmAPI(
0
2023-10-18 12:57:53+00:00
4k
instadeepai/flashbax
flashbax/buffers/prioritised_flat_buffer.py
[ { "identifier": "ExperiencePair", "path": "flashbax/buffers/flat_buffer.py", "snippet": "class ExperiencePair(NamedTuple, Generic[Experience]):\n first: Experience\n second: Experience" }, { "identifier": "TransitionSample", "path": "flashbax/buffers/flat_buffer.py", "snippet": "cl...
import warnings import jax from typing import TYPE_CHECKING, Optional from chex import PRNGKey from flashbax.buffers.flat_buffer import ( ExperiencePair, TransitionSample, validate_flat_buffer_args, ) from flashbax.buffers.prioritised_trajectory_buffer import ( Indices, PrioritisedTrajectoryBuffer, ...
1,917
# Copyright 2023 InstaDeep Ltd. 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 o...
# Copyright 2023 InstaDeep Ltd. 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 o...
) -> PrioritisedTrajectoryBuffer:
3
2023-10-17 10:57:14+00:00
4k
TheDuckAI/DuckTrack
ducktrack/app.py
[ { "identifier": "close_obs", "path": "ducktrack/obs_client.py", "snippet": "def close_obs(obs_process: subprocess.Popen):\n if obs_process:\n obs_process.terminate()\n try:\n obs_process.wait(timeout=5)\n except subprocess.TimeoutExpired:\n obs_process.kill(...
import os import sys from platform import system from PyQt6.QtCore import QTimer, pyqtSlot from PyQt6.QtGui import QAction, QIcon from PyQt6.QtWidgets import (QApplication, QCheckBox, QDialog, QFileDialog, QFormLayout, QLabel, QLineEdit, QMenu, QMessageBox, QPus...
3,316
class TitleDescriptionDialog(QDialog): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Recording Details") layout = QVBoxLayout(self) self.form_layout = QFormLayout() self.title_label = QLabel("Title:") self.title_input = QLineEd...
class TitleDescriptionDialog(QDialog): def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Recording Details") layout = QVBoxLayout(self) self.form_layout = QFormLayout() self.title_label = QLabel("Title:") self.title_input = QLineEd...
self.show_recordings_button.clicked.connect(lambda: open_file(get_recordings_dir()))
6
2023-10-18 19:34:19+00:00
4k
e4s2023/E4S2023
swap_face_fine/Blender/model_center/blener.py
[ { "identifier": "Referencer", "path": "swap_face_fine/Blender/model_center/referencer.py", "snippet": "class Referencer(nn.Module):\n def __init__(self, args):\n super(Referencer, self).__init__()\n self.args = args\n if args.small_FPN:\n self.FPN = SmallFPN()\n ...
import torch import torch.nn as nn from .referencer import Referencer from .res_u_net import ResUNet
1,705
class Blender(nn.Module): def __init__(self, args): super(Blender, self).__init__() self.referencer = Referencer(args)
class Blender(nn.Module): def __init__(self, args): super(Blender, self).__init__() self.referencer = Referencer(args)
self.unet = ResUNet(args)
1
2023-10-15 12:15:01+00:00
4k
riverscn/epghub
epg/plugin/weibo_cctv9.py
[ { "identifier": "search", "path": "epg/plugin/__weibo_search.py", "snippet": "def search(keyword: str, page: int = 1) -> list:\n \"\"\"\n Search weibo by keyword.\n\n Args:\n keyword (str): The keyword to search.\n page (int): The page number to search.\n\n Returns:\n ...
from .__weibo_search import search as weibo_search from .__weibo_search import headers from datetime import date, datetime, timedelta from epg.model import Channel, Program import re import requests import json
1,739
keyword = "#每日央视纪录片精选#" def update_programs(programs: list[Program], programs_new: list[Program]) -> int: """ Update programs with new programs. Args: programs (list[Program]): The programs to update. programs_new (list[Program]): The new programs. Returns: int: The number ...
keyword = "#每日央视纪录片精选#" def update_programs(programs: list[Program], programs_new: list[Program]) -> int: """ Update programs with new programs. Args: programs (list[Program]): The programs to update. programs_new (list[Program]): The new programs. Returns: int: The number ...
def update(channel: Channel, date: date) -> int:
2
2023-10-20 04:35:12+00:00
4k
Aggify/aggify
tests/test_aggify.py
[ { "identifier": "Aggify", "path": "aggify/aggify.py", "snippet": "def last_out_stage_check(method: AggifyType) -> AggifyType:\n def decorator(*args, **kwargs):\n def __init__(self, base_model: Type[Document]):\n def __iter__(self):\n def project(self, **kwargs: QueryParams) -> \"Aggify\":\n ...
import pytest from mongoengine import Document, IntField, StringField from aggify import Aggify, Cond, F, Q from aggify.exceptions import ( AggifyValueError, AnnotationError, OutStageError, InvalidArgument, InvalidField, InvalidOperator, AlreadyExistsField, InvalidEmbeddedField, Mong...
2,565
class BaseModel(Document): # Define your fields here name = StringField(max_length=100) age = IntField() meta = {"allow_inheritance": True, "abstract": True} # This defines a base document model for MongoDB using MongoEngine, with 'name' and 'age' fields. # The 'allow_inheritance' and 'abstract' o...
class BaseModel(Document): # Define your fields here name = StringField(max_length=100) age = IntField() meta = {"allow_inheritance": True, "abstract": True} # This defines a base document model for MongoDB using MongoEngine, with 'name' and 'age' fields. # The 'allow_inheritance' and 'abstract' o...
aggify.filter(Q(name="John") | Q(name="Alice")).project(
0
2023-10-22 07:53:28+00:00
4k
sotopia-lab/sotopia
lmlib/serve/lm_inference.py
[ { "identifier": "SeparatorStyle", "path": "lmlib/utils/conversation.py", "snippet": "class SeparatorStyle(Enum):\nclass Conversation:\n SINGLE = auto()\n TWO = auto()\n DOLLY = auto()\n OASST_PYTHIA = auto()\n BAIZE = auto()\n def get_prompt(self) -> str:\n def append_message(self, ...
import abc import os import os.path as osp import warnings import torch import pdb from typing import Any, Dict, List, Optional, Tuple, Union from logzero import logger from peft import PeftModel, set_peft_model_state_dict from transformers import LlamaForCausalLM # type: ignore[attr-defined] from transfor...
2,307
out = model( input_ids=torch.as_tensor([input_ids], device=device), use_cache=True, encoder_outputs=encoder_outputs, decoder_input_ids=torch.as_tensor( [[token]], device=device ), ...
"""Inference for FastChat models.""" # try: # from transformers import ( # AutoModel, # AutoModelForCausalLM, # AutoModelForSeq2SeqLM, # LlamaForCausalLM, # LlamaTokenizer, # ) # except ImportError: # from transformers import ( # AutoModelForCausalLM, # ...
skip_echo_len = compute_skip_echo_len(conv, prompt)
0
2023-10-23 19:47:26+00:00
4k
Zai-Kun/reverse-engineered-chatgpt
re_gpt/async_chatgpt.py
[ { "identifier": "BackendError", "path": "re_gpt/errors.py", "snippet": "class BackendError(Exception):\n def __init__(self, error_code):\n self.error_code = error_code\n self.message = (\n f\"An error occurred on the backend. Error code: {self.error_code}\"\n )\n ...
import asyncio import ctypes import inspect import json import uuid from typing import AsyncGenerator, Callable, Optional from curl_cffi.requests import AsyncSession from .errors import ( BackendError, InvalidSessionToken, RetryError, TokenNotProvided, UnexpectedResponseError, InvalidModelName, ...
2,643
payload (dict): Payload containing message information. Yields: bytes: Chunk of data received as a response. """ response_queue = asyncio.Queue() async def perform_request(): def content_callback(chunk): response_queue.put_nowait(chun...
# Constants USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36" CHATGPT_API = "https://chat.openai.com/backend-api/{}" BACKUP_ARKOSE_TOKEN_GENERATOR = "https://arkose-token-generator.zaieem.repl.co/token" MODELS = { "gpt-4": {"slug": "gpt-...
raise RetryError(website=BACKUP_ARKOSE_TOKEN_GENERATOR)
2
2023-10-17 08:34:04+00:00
4k
qualabs/video-headline
utils/cloudfront.py
[ { "identifier": "cloudfront_deleted", "path": "video/signals.py", "snippet": "" }, { "identifier": "Configuration", "path": "configuration/models.py", "snippet": "class Configuration(SingletonModel):\n slack_notifications_url = models.URLField(blank=True, null=True)\n cloud_front_c...
import boto3 from botocore.exceptions import ClientError from celery import shared_task from django.utils import timezone from video.signals import cloudfront_deleted from configuration.models import Configuration from organization.models import AWSAccount from video.models import LiveVideo from organizatio...
2,395
# skip operation on distribution not exists operation if ex.response['Error']['Code'] == 'NoSuchDistribution': pass else: raise ex def update_distribution(organization, dist_id, status = False): """ If Organization is deleted the associated AWS CloudFront distr...
def get_cloudfront_client(aws_account): if aws_account: cloudfront = boto3.client('cloudfront', aws_access_key_id=aws_account.access_key, aws_secret_access_key=aws_account.secret_access_key, region_name=aws_account.region) else: ...
for account in AWSAccount.objects.all():
2
2023-10-17 19:44:32+00:00
4k
Qualcomm-AI-research/geometric-algebra-transformer
tests/gatr/interface/test_translation.py
[ { "identifier": "embed_oriented_plane", "path": "gatr/interface/plane.py", "snippet": "def embed_oriented_plane(\n normal: torch.Tensor, position: Optional[torch.Tensor] = None\n) -> torch.Tensor:\n \"\"\"Embeds an (oriented plane) in the PGA.\n\n Following L. Dorst, the plane is represent as P...
import pytest import torch from gatr.interface import ( embed_oriented_plane, embed_point, embed_pseudoscalar, embed_scalar, embed_translation, extract_oriented_plane, extract_point, extract_point_embedding_reg, extract_pseudoscalar, extract_scalar, extract_translation, ) fro...
3,574
# Copyright (c) 2023 Qualcomm Technologies, Inc. # All rights reserved. @pytest.mark.parametrize("batch_dims", BATCH_DIMS) def test_translation_embedding_consistency(batch_dims): """Tests whether translation embeddings into multivectors are cycle consistent.""" translations = torch.randn(*batch_dims, 3) ...
# Copyright (c) 2023 Qualcomm Technologies, Inc. # All rights reserved. @pytest.mark.parametrize("batch_dims", BATCH_DIMS) def test_translation_embedding_consistency(batch_dims): """Tests whether translation embeddings into multivectors are cycle consistent.""" translations = torch.randn(*batch_dims, 3) ...
torch.testing.assert_close(translations, translations_reencoded, **TOLERANCES)
14
2023-10-23 15:58:36+00:00
4k
StanislavPetrovV/Wolfenstein-3D-Clone
game_objects/npc.py
[ { "identifier": "GameObject", "path": "game_objects/game_object.py", "snippet": "class GameObject:\n def __init__(self, level_map, tex_id, x, z):\n self.eng = level_map.eng\n self.app = self.eng.app\n self.tex_id = tex_id\n #\n self.pos = glm.vec3(x + H_WALL_SIZE, 0...
from settings import * from game_objects.game_object import GameObject from game_objects.item import Item import random
1,613
# self.animate() # set current texture self.tex_id = self.state_tex_id + self.frame def get_damage(self): self.health -= WEAPON_SETTINGS[self.player.weapon_id]['damage'] self.is_hurt = True # if not self.is_player_spotted: self.is_player_s...
class NPC(GameObject): def __init__(self, level_map, tex_id, x, z): super().__init__(level_map, tex_id, x, z) self.level_map = level_map self.player = self.eng.player self.npc_id = tex_id # self.scale = NPC_SETTINGS[self.npc_id]['scale'] self.speed = NPC_SET...
self.level_map.item_map[self.tile_pos] = Item(
1
2023-10-22 08:41:55+00:00
4k
tomguluson92/cloth2tex
renderer/cloth_renderer.py
[ { "identifier": "PerspectiveCamera", "path": "renderer/landmark_renderer.py", "snippet": "class PerspectiveCamera(nn.Module):\n\n FOCAL_LENGTH = 50*128\n\n def __init__(self, rotation=None, translation=None,\n focal_length_x=None, focal_length_y=None,\n batch_size=1...
import datetime import os import cv2 import torch import numpy as np import matplotlib.pyplot as plt import pytorch3d import torchvision.transforms as transforms import random from PIL import Image from pytorch3d.structures import Meshes from pytorch3d.renderer.mesh import Textures from pytorch3d.renderer import ( ...
1,758
# coding: UTF-8 """ clothrenderer """ # Data structures and functions for rendering DEG_TO_RAD = np.pi / 180 class ClothRenderer(object): def __init__(self, objfile, resolution=512, focal_distance=1.6, scale_factor=1): self.device = torch.device("cuda:0") self.img_size = resoluti...
# coding: UTF-8 """ clothrenderer """ # Data structures and functions for rendering DEG_TO_RAD = np.pi / 180 class ClothRenderer(object): def __init__(self, objfile, resolution=512, focal_distance=1.6, scale_factor=1): self.device = torch.device("cuda:0") self.img_size = resoluti...
self.landmark_cam = OrthogonalCamera(rotation=self.cameras.R.cuda(), translation=self.cameras.T.cuda()).to(self.device)
1
2023-10-17 11:30:53+00:00
4k
amazon-science/cceval
eval.py
[ { "identifier": "compute_metric_stmt", "path": "eval_metric.py", "snippet": "def compute_metric_stmt(args):\n with open(f\"{args.output_dir}/prediction.jsonl\", \"r\") as f_pred:\n samples = []\n for l in f_pred.readlines():\n samples.append(json.loads(l))\n\n examples = {...
import argparse import json import logging import os import numpy as np import torch import custom_generate from accelerate import Accelerator from accelerate.utils import set_seed from datasets import load_dataset from torch.utils.data import DataLoader, SequentialSampler from tqdm import tqdm from transformers import...
3,574
crossfile_context, truncation=True, max_length=args.cfc_seq_length ) features = {"input_ids": [], "attention_mask": []} tokenizer.truncation_side = "left" for idx, prompt in enumerate(examples["prompt"]): allowed_prompt_length = max_prompt...
# Copyright Amazon.com, Inc. or its affiliates. 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 ap...
mean_logp = compute_mean_logp(batch_scores, batch_pred, tokenizer.pad_token_id)
1
2023-10-16 04:23:03+00:00
4k
uukuguy/multi_loras
multi_loras/dare.py
[ { "identifier": "DeltaWeights", "path": "multi_loras/delta_weights.py", "snippet": "class DeltaWeights:\n \"\"\"\n Functions to compute the delta weights between two models \n \"\"\"\n\n def __init__(\n self,\n base_model: nn.Module = None,\n tuned_model: nn.Module = Non...
from tqdm import tqdm from transformers import AutoModelForCausalLM, AutoTokenizer from .delta_weights import DeltaWeights, copy_params_to_model import torch import torch.nn as nn
2,118
# DARE (Drop And REscale) # Language Models are Super Mario: Absorbing Abilities from Homologous Models as a Free Lunch # https://arxiv.org/abs/2311.03099 def drop_and_rescale_tensor( input_tensor: torch.Tensor, mask_rate: float, use_rescale: bool, mask_strategy: str ): """ mask the input with mask rate ...
#!/usr/bon/env python """ This script is used to do drop and rescale for the tuned model """ default_dare_kwargs = { "weight_mask_rate": 0.85, "use_weight_rescale": True, "mask_strategy": "random", "scaling_coefficient": 1.0, } # DARE (Drop And REscale) # Language Models are Super Mario: Absorbing Ab...
copy_params_to_model(model_weights, base_model)
1
2023-10-16 02:39:47+00:00
4k
aws/res
tasks/build.py
[ { "identifier": "BuildTool", "path": "tasks/tools/build_tool.py", "snippet": "class BuildTool:\n \"\"\"\n IDEA Project Build Tool\n Handles building of individual projects under <PROJECT_ROOT>/source/idea/*\n\n Works based on standard idea directory structure:\n <PROJECT_ROOT>/\n + sou...
import tasks.idea as idea import os import shutil from tasks.tools.build_tool import BuildTool from tasks.apispec import ( cluster_manager as apispec_cluster_manager, virtual_desktop_controller as apispec_virtual_desktop_controller ) from invoke import task, Context
3,258
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the 'license' ...
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the 'license' ...
apispec_virtual_desktop_controller(c, output_file=os.path.join(tool.output_dir, 'resources', 'api', 'openapi.yml'))
0
2023-10-20 17:11:30+00:00
4k
cvlab-yonsei/ACLS
tools/train.py
[ { "identifier": "Trainer", "path": "calibrate/engine/trainer.py", "snippet": "class Trainer:\n def __init__(self, cfg: DictConfig) -> None:\n self.cfg = cfg\n self.work_dir = self.cfg.work_dir\n self.device = torch.device(self.cfg.device)\n self.build_data_loader()\n ...
import os import sys import logging import hydra from omegaconf import DictConfig, OmegaConf from omegaconf.omegaconf import open_dict from calibrate.engine import Trainer from calibrate.utils import set_random_seed
2,739
logger = logging.getLogger(__name__) TRAINERS = { "cv": Trainer } @hydra.main(config_path="../configs", config_name="defaults") def main(cfg: DictConfig): logger.info("Launch command : ") logger.info(" ".join(sys.argv)) with open_dict(cfg): cfg.work_dir = os.getcwd() logger.info("\n" + ...
logger = logging.getLogger(__name__) TRAINERS = { "cv": Trainer } @hydra.main(config_path="../configs", config_name="defaults") def main(cfg: DictConfig): logger.info("Launch command : ") logger.info(" ".join(sys.argv)) with open_dict(cfg): cfg.work_dir = os.getcwd() logger.info("\n" + ...
set_random_seed(
1
2023-10-23 09:55:13+00:00
4k
myshell-ai/AIlice
ailice/core/AProcessor.py
[ { "identifier": "config", "path": "ailice/common/AConfig.py", "snippet": "class AConfig():\n def __init__(self):\n def Initialize(self, needOpenaiGPTKey = False):\n def Load(self, configFile: str) -> dict:\n def Store(self, configFile: str):" }, { "identifier": "llmPool", "path":...
import time from functools import partial from ailice.common.AConfig import config from ailice.core.llm.ALLMPool import llmPool from ailice.common.APrompts import promptsManager from ailice.common.ARemoteAccessors import clientPool from ailice.core.AConversation import AConversations from ailice.core.AInterpreter impor...
1,666
class AProcessor(): def __init__(self, name, modelID, promptName, outputCB, collection = None): self.name = name self.modelID = modelID
class AProcessor(): def __init__(self, name, modelID, promptName, outputCB, collection = None): self.name = name self.modelID = modelID
self.llm = llmPool.GetModel(modelID)
1
2023-10-16 01:51:14+00:00
4k
Agora-X/Bing-Chat-API
src/bing_chat/chathub.py
[ { "identifier": "DELIMITER", "path": "src/bing_chat/constants.py", "snippet": "DELIMITER = \"\\x1e\"" }, { "identifier": "HEADERS", "path": "src/bing_chat/constants.py", "snippet": "HEADERS = {\n \"accept\": \"application/json\",\n \"accept-language\": \"en-US;q=0.9\",\n \"accep...
import asyncio import json import os import ssl import sys import aiohttp import certifi import httpx import urllib.parse from time import time from typing import Generator from typing import List from typing import Union from BingImageCreator import ImageGenAsync from .constants import DELIMITER from .constants import...
3,459
ssl_context = ssl.create_default_context() ssl_context.load_verify_locations(certifi.where()) class ChatHub: def __init__( self,
ssl_context = ssl.create_default_context() ssl_context.load_verify_locations(certifi.where()) class ChatHub: def __init__( self,
conversation: Conversation,
3
2023-10-19 19:17:05+00:00
4k
city96/ComfyUI_ExtraModels
PixArt/models/PixArt.py
[ { "identifier": "auto_grad_checkpoint", "path": "PixArt/models/utils.py", "snippet": "def _ntuple(n):\n def parse(x):\ndef set_grad_checkpoint(model, use_fp32_attention=False, gc_step=1):\n def set_attr(module):\ndef auto_grad_checkpoint(module, *args, **kwargs):\ndef checkpoint_sequential(functio...
import math import torch import torch.nn as nn import os import numpy as np from timm.models.layers import DropPath from timm.models.vision_transformer import PatchEmbed, Mlp from .utils import auto_grad_checkpoint, to_2tuple from .PixArt_blocks import t2i_modulate, CaptionEmbedder, WindowAttention, MultiHeadCrossAtten...
3,572
# 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. # -------------------------------------------------------- # References: # GLIDE: https://github.com/openai/glide-text2im #...
# 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. # -------------------------------------------------------- # References: # GLIDE: https://github.com/openai/glide-text2im #...
self.attn = WindowAttention(hidden_size, num_heads=num_heads, qkv_bias=True,
3
2023-10-20 21:19:44+00:00
4k
aszc-dev/ComfyUI-CoreMLSuite
coreml_suite/models.py
[ { "identifier": "get_model_config", "path": "coreml_suite/config.py", "snippet": "def get_model_config(model_version: ModelVersion):\n unet_config = convert_config(config_map[model_version])\n config = supported_models_base.BASE(unet_config)\n config.latent_format = latent_format_map[model_vers...
import numpy as np import torch from comfy import model_base from comfy.model_management import get_torch_device from comfy.model_patcher import ModelPatcher from coreml_suite.config import get_model_config, ModelVersion from coreml_suite.controlnet import extract_residual_kwargs, chunk_control from coreml_suite.latent...
1,666
class CoreMLModelWrapper: def __init__(self, coreml_model): self.coreml_model = coreml_model self.dtype = torch.float16 def __call__(self, x, t, context, control, transformer_options=None, **kwargs): inputs = CoreMLInputs(x, t, context, control, **kwargs) input_list = inputs....
class CoreMLModelWrapper: def __init__(self, coreml_model): self.coreml_model = coreml_model self.dtype = torch.float16 def __call__(self, x, t, context, control, transformer_options=None, **kwargs): inputs = CoreMLInputs(x, t, context, control, **kwargs) input_list = inputs....
chunked_control = chunk_control(self.control, sample_shape[0])
3
2023-10-23 13:08:00+00:00
4k
aikunyi/FreTS
exp/exp_main.py
[ { "identifier": "data_provider", "path": "data_provider/data_factory.py", "snippet": "def data_provider(args, flag):\n Data = data_dict[args.data]\n timeenc = 0 if args.embed != 'timeF' else 1\n train_only = args.train_only\n\n if flag == 'test':\n shuffle_flag = False\n drop_l...
from data_provider.data_factory import data_provider from exp.exp_basic import Exp_Basic from models import DLinear, NLinear, FreTS from utils.tools import EarlyStopping, adjust_learning_rate, visual, test_params_flop from utils.metrics import metric from torch import optim import numpy as np import pandas as pd import...
2,036
warnings.filterwarnings('ignore') class Exp_Main(Exp_Basic): def __init__(self, args): super(Exp_Main, self).__init__(args) def _build_model(self): model_dict = { 'DLinear': DLinear,
warnings.filterwarnings('ignore') class Exp_Main(Exp_Basic): def __init__(self, args): super(Exp_Main, self).__init__(args) def _build_model(self): model_dict = { 'DLinear': DLinear,
'NLinear': NLinear,
3
2023-10-23 13:15:14+00:00
4k
amitfin/oref_alert
custom_components/oref_alert/binary_sensor.py
[ { "identifier": "expand_areas_and_groups", "path": "custom_components/oref_alert/area_utils.py", "snippet": "def expand_areas_and_groups(areas_and_groups: list[str]) -> list[str]:\n \"\"\"Expand groups (if exists) to areas.\"\"\"\n areas = []\n for area_or_group in areas_and_groups:\n if...
from typing import Any from collections.abc import Mapping from homeassistant.components import binary_sensor from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.updat...
2,580
"""Support for representing daily schedule as binary sensors.""" from __future__ import annotations async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Initialize config entry.""" coordinator = hass.data[DOMAIN][co...
"""Support for representing daily schedule as binary sensors.""" from __future__ import annotations async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Initialize config entry.""" coordinator = hass.data[DOMAIN][co...
self._attr_name = TITLE
3
2023-10-18 11:16:41+00:00
4k
apple/ml-nvas3d
demo/generate_demo_data.py
[ { "identifier": "render_ir_parallel_room_idx", "path": "soundspaces_nvas3d/utils/ss_utils.py", "snippet": "def render_ir_parallel_room_idx(room: str,\n source_idx_list: T.List[int],\n receiver_idx_list: T.List[int],\n ...
import os import json import random import argparse import subprocess import typing as T import torch import torchaudio from soundspaces_nvas3d.utils.ss_utils import render_ir_parallel_room_idx, create_scene from soundspaces_nvas3d.utils.aihabitat_utils import load_room_grid from soundspaces_nvas3d.utils.audio_utils im...
2,813
# # For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. # def generate_rir( args: argparse.Namespace, room: str, source_idx_list: T.List[int], receiver_idx_list: T.List[int] ): """ Generates and saves Room Impulse Response (RIR) data for pairs o...
# # For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. # def generate_rir( args: argparse.Namespace, room: str, source_idx_list: T.List[int], receiver_idx_list: T.List[int] ): """ Generates and saves Room Impulse Response (RIR) data for pairs o...
render_ir_parallel_room_idx(room, source_idx_list, receiver_idx_list, filename_ir, args.grid_distance)
0
2023-10-19 05:35:54+00:00
4k
virevolai/logos-shift-client
logos_shift_client/logos_shift.py
[ { "identifier": "BohitaClient", "path": "logos_shift_client/bohita.py", "snippet": "class BohitaClient:\n def __init__(self, api_key: str):\n if api_key is None:\n logging.warning(\n \"No API KEY provided. No data will be sent to Bohita and automatic routing will not ...
import asyncio import logging import threading import time import uuid from pathlib import Path from collections import deque from typing import Optional, Union from tenacity import retry, wait_fixed from .bohita import BohitaClient from .router import APIRouter
2,308
logger = logging.getLogger(__name__) MAX_ENTRIES = 10 CHECK_SECONDS = 5 class SingletonMeta(type): _instances = {} _lock = threading.Lock() def __call__(cls, *args, **kwargs): with cls._lock: if cls not in cls._instances: instance = super().__call__(*args, **kwargs)...
logger = logging.getLogger(__name__) MAX_ENTRIES = 10 CHECK_SECONDS = 5 class SingletonMeta(type): _instances = {} _lock = threading.Lock() def __call__(cls, *args, **kwargs): with cls._lock: if cls not in cls._instances: instance = super().__call__(*args, **kwargs)...
bohita_client: BohitaClient,
0
2023-10-20 00:00:38+00:00
4k
kwonathan/language-models-trajectory-generators
env.py
[ { "identifier": "Robot", "path": "robot.py", "snippet": "class Robot:\n\n def __init__(self, args):\n\n if args.robot == \"sawyer\":\n self.base_start_position = config.base_start_position_sawyer\n self.base_start_orientation_q = p.getQuaternionFromEuler(config.base_start...
import pybullet as p import numpy as np import pybullet_data import time import config from robot import Robot from config import OK, PROGRESS, FAIL, ENDC from config import CAPTURE_IMAGES, ADD_BOUNDING_CUBES, ADD_TRAJECTORY_POINTS, EXECUTE_TRAJECTORY, OPEN_GRIPPER, CLOSE_GRIPPER, TASK_COMPLETED, RESET_ENVIRONMENT
3,151
class Environment: def __init__(self, args): self.mode = args.mode def load(self): p.resetDebugVisualizerCamera(config.camera_distance, config.camera_yaw, config.camera_pitch, config.camera_target_position) object_start_position = config.object_start_position object_start_o...
class Environment: def __init__(self, args): self.mode = args.mode def load(self): p.resetDebugVisualizerCamera(config.camera_distance, config.camera_yaw, config.camera_pitch, config.camera_target_position) object_start_position = config.object_start_position object_start_o...
env_connection_message = OK + "Finished setting up environment!" + ENDC
1
2023-10-18 16:38:09+00:00
4k
kvablack/susie
susie/model.py
[ { "identifier": "sampling", "path": "susie/sampling.py", "snippet": "def q_sample(x_0, log_snr, noise):\ndef model_predict(state, x, y, prompt_embeds, t, use_ema=True):\ndef sample_step(\n rng,\n state,\n x,\n y,\n prompt_embeds,\n uncond_y,\n uncond_prompt_embeds,\n t,\n t_ne...
import os import time import einops as eo import jax import jax.numpy as jnp import ml_collections import numpy as np import orbax.checkpoint import wandb from functools import partial from typing import Any, Callable, List, Optional, Tuple from absl import logging from diffusers.models import FlaxAutoencoderKL, FlaxUN...
2,490
scale, lambda: latents / vae.config.scaling_factor, lambda: latents ) sample = vae.apply({"params": vae_params}, latents, method=vae.decode) sample = eo.rearrange(sample, "(n x) h w c -> n h w (x c)", n=batch_size) return sample return partial(vae_encode, vae_params), pa...
class EmaTrainState(TrainState): params_ema: FrozenDict[str, Any] @partial(jax.jit, donate_argnums=0) def apply_ema_decay(self, ema_decay): params_ema = jax.tree_map( lambda p_ema, p: p_ema * ema_decay + p * (1.0 - ema_decay), self.params_ema, self.params, ...
sample_loop = partial(sampling.sample_loop, log_snr_fn=log_snr_fn)
0
2023-10-17 05:05:57+00:00
4k
skywalker023/fantom
eval_fantom.py
[ { "identifier": "GPT3BaseAgent", "path": "agents/gpt.py", "snippet": "class GPT3BaseAgent():\n def __init__(self, kwargs: dict):\n openai.api_key = os.getenv('OPENAI_API_KEY')\n self.args = SimpleNamespace(**kwargs)\n self._set_default_args()\n\n def _set_default_args(self):\n...
import os import json import argparse import random import evaluate import torch import pandas as pd import colorful as cf import task.dataset_loader as loader from pathlib import Path from collections import Counter from torch.utils.data import DataLoader, Dataset from tqdm import tqdm from sentence_transformers impor...
2,586
tqdm.pandas() cf.use_true_colors() cf.use_style('monokai') PROJECT_HOME = Path(__file__).parent.resolve() DATA_DIR = 'data' DATA_DIR_PATH = os.path.join(PROJECT_HOME, DATA_DIR) EVAL_DIR_PATH = os.path.join(DATA_DIR_PATH, 'results') RANDOM_SEED = 99 random.seed(RANDOM_SEED) class FantomDataset(Dataset): def __...
tqdm.pandas() cf.use_true_colors() cf.use_style('monokai') PROJECT_HOME = Path(__file__).parent.resolve() DATA_DIR = 'data' DATA_DIR_PATH = os.path.join(PROJECT_HOME, DATA_DIR) EVAL_DIR_PATH = os.path.join(DATA_DIR_PATH, 'results') RANDOM_SEED = 99 random.seed(RANDOM_SEED) class FantomDataset(Dataset): def __...
model = TogetherAIAgent(self.args.__dict__)
6
2023-10-21 22:49:56+00:00
4k
turingmotors/openlenda
yolox/models/darknet.py
[ { "identifier": "BaseConv", "path": "yolox/models/network_blocks.py", "snippet": "class BaseConv(nn.Module):\n \"\"\"A Conv2d -> Batchnorm -> silu/leaky relu block\"\"\"\n\n def __init__(\n self, in_channels, out_channels, ksize, stride, groups=1, bias=False, act=\"silu\"\n ):\n s...
from torch import nn from .network_blocks import BaseConv, CSPLayer, DWConv, Focus, ResLayer, SPPBottleneck
1,738
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) Megvii Inc. All rights reserved. class Darknet(nn.Module): # number of blocks from dark2 to dark5. depth2blocks = {21: [1, 2, 2, 1], 53: [2, 8, 8, 4]} def __init__( self, depth, in_channels=3, stem_out_chann...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) Megvii Inc. All rights reserved. class Darknet(nn.Module): # number of blocks from dark2 to dark5. depth2blocks = {21: [1, 2, 2, 1], 53: [2, 8, 8, 4]} def __init__( self, depth, in_channels=3, stem_out_chann...
BaseConv(in_channels, stem_out_channels, ksize=3, stride=1, act="lrelu"),
0
2023-10-20 08:12:26+00:00
4k
tiejundong/FlexPose
FlexPose/preprocess/aug_pseudo_apo.py
[ { "identifier": "delmkdir", "path": "FlexPose/utils/common.py", "snippet": "def delmkdir(path, remove_old=True):\n isexist = os.path.exists(path)\n if not isexist:\n os.makedirs(path)\n if isexist == True and remove_old:\n shutil.rmtree(path)\n os.makedirs(path)" }, { ...
import os import shutil import sys import argparse import numpy as np import scipy.spatial import random import pickle import pyrosetta from ray.util.multiprocessing import Pool from einops import rearrange from pyrosetta import rosetta from pyrosetta.rosetta import core from modeller import environ from modeller.scrip...
2,120
tf.push_back(core.pack.task.operation.RestrictToRepacking()) restrict_to_focus = core.pack.task.operation.OperateOnResidueSubset(core.pack.task.operation.PreventRepackingRLT(), res_selector, ...
sys.path.append('/'.join(os.path.abspath(__file__).split('/')[:-2])) def random_sc(pose, res_list=None, pert=180): # random chi if isinstance(res_list, type(None)): res_list = range(1, pose.size() + 1) for i in res_list: res = pose.residue(i) for chino, chi in enumerate(res.ch...
ligand_coor = get_true_posi(ligand_mol)
2
2023-10-19 22:03:51+00:00
4k
openvpi/SingingVocoders
train.py
[ { "identifier": "read_full_config", "path": "utils/config_utils.py", "snippet": "def read_full_config(config_path: pathlib.Path) -> dict:\n config_path = config_path.resolve()\n config_path_str = config_path.as_posix()\n if config_path in loaded_config_files:\n return loaded_config_files...
import importlib import logging import os import pathlib import sys import click import lightning.pytorch as pl import torch.utils.data import yaml from lightning.pytorch.loggers import TensorBoardLogger from utils.config_utils import read_full_config, print_config from utils.training_utils import ( DsModelCheckpoi...
2,764
torch.multiprocessing.set_sharing_strategy(os.getenv('TORCH_SHARE_STRATEGY', 'file_system')) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') @click.command(help='') @click.option('--config', requ...
torch.multiprocessing.set_sharing_strategy(os.getenv('TORCH_SHARE_STRATEGY', 'file_system')) log_format = '%(asctime)s %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') @click.command(help='') @click.option('--config', requ...
trainer.fit(task, ckpt_path=get_latest_checkpoint_path(work_dir))
4
2023-10-17 13:45:09+00:00
4k
RobertCsordas/moe
models/transformer_language_model.py
[ { "identifier": "LoggingLayer", "path": "layers/logging_layer.py", "snippet": "class LoggingLayer:\n def __init__(self) -> None:\n super().__init__()\n self._logs = {}\n self._log_counts = {}\n self._custom_reductions = {}\n\n def custom_reduction(self, name: str, reduc...
import torch import torch.nn import torch.nn.functional as F import framework import math from typing import Optional, Tuple, Any, List from layers import LoggingLayer from layers.transformer.multi_head_attention import AttentionMask from layers.transformer.transformer import Transformer
2,064
self.shared_layers = all([la is layers[0] for la in layers]) if embedding_size is None: self.embedding_adapter = lambda x: x else: self.embedding_adapter = torch.nn.Linear(embedding_size, state_size) self.dropout = torch.nn.Dropout(dropout) self.layers =...
class TransformerLanguageModel(LoggingLayer, torch.nn.Module): def __init__(self, voc_size: int, embedding_size: Optional[int], state_size: int, dropout: float, tied_embedding: bool, layers: List[torch.nn.Module], n_prev_states: int, n_prev_states_test: Optional[int] = None, adap...
net_o = l(net, mask=AttentionMask(None, causality_mask), attend_to=attend_to,
1
2023-10-16 11:26:45+00:00
4k
yk/llmvm
parsing.py
[ { "identifier": "Arg", "path": "interface.py", "snippet": "class Arg(pydantic.BaseModel):\n vtype: str\n value: str" }, { "identifier": "Load", "path": "interface.py", "snippet": "class Load(Expr):\n kind: str = \"load\"\n vtype: str\n ptr: str" }, { "identifier": ...
import re from loguru import logger from interface import Arg, Load, Icmp, Srem, Add, Mul, Call, Assign, Store, Branch, BranchCond, Return, Program, to_vtype, GetElementPtr, Copy, Switch, AllocArray, Alloc
2,119
def parse_arg(arg): logger.debug(f"parse_arg({arg})") if m := re.match(r"ptr noundef (\S+)", arg): return Arg(vtype="str", value=m.group(1)) if m := re.match(r"i32 noundef (\S+)", arg): return Arg(vtype="i32", value=m.group(1)) raise NotImplementedError(arg) def parse_call(expr): lo...
def _line_stripper(in_f): for line in in_f: line = line.rstrip() if not line: continue yield line def parse_arg(arg): logger.debug(f"parse_arg({arg})") if m := re.match(r"ptr noundef (\S+)", arg): return Arg(vtype="str", value=m.group(1)) if m := re.match(r"...
constants[name] = to_vtype(value=value, vtype="str")
13
2023-10-23 21:29:14+00:00
4k
w-e-w/sd-webui-nudenet-nsfw-censor
scripts/nudenet_nsfw_censor_scripts/post_processing_script.py
[ { "identifier": "pil_nude_detector", "path": "scripts/nudenet_nsfw_censor_scripts/pil_nude_detector.py", "snippet": "def draw_ellipse(draw, left_expanded, top_expanded, right_expanded, down_expanded, *args, **kwargs):\ndef draw_rectangle(draw, left_expanded, top_expanded, right_expanded, down_expanded, ...
from scripts.nudenet_nsfw_censor_scripts.pil_nude_detector import pil_nude_detector, mask_shapes_func_dict from scripts.nudenet_nsfw_censor_scripts.censor_image_filters import apply_filter, filter_dict from modules import shared, images, scripts_postprocessing from PIL import Image, ImageFilter from math import sqrt ...
2,843
mask_brush_color.change( fn=update_mask_brush_color, inputs=[mask_brush_color], outputs=[input_mask] ) def get_current_image(image): # ToDo if possible make this a client side operation ...
if hasattr(scripts_postprocessing.ScriptPostprocessing, 'process_firstpass'): # webui >= 1.7 else: InputAccordion = None filter_opt_ui_show_dict = { # [blur_radius, blur_strength_curve, pixelation_factor, fill_color, mask_blend_radius, mask_blend_radius_variable_blur] 'Variable blur': [True, True, False...
pp.image = apply_filter(pp.image, censor_mask, filter_type, **filter_settings)
1
2023-10-16 16:44:07+00:00
4k
enkeejunior1/Diffusion-Pullback
src/models/guided_diffusion/unet.py
[ { "identifier": "convert_module_to_f16", "path": "src/models/guided_diffusion/fp16_util.py", "snippet": "def convert_module_to_f16(l):\n \"\"\"\n Convert primitive modules to float16.\n \"\"\"\n if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):\n l.weight.data = l.weight.data.half(...
from abc import abstractmethod from einops import rearrange, reduce, repeat, einsum from .fp16_util import convert_module_to_f16, convert_module_to_f32 from .nn import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_module, normalization, timestep_embedding, ) import math import time import...
3,468
) self.input_blocks.append(TimestepEmbedSequential(*layers)) self._feature_size += ch input_block_chans.append(ch) if level != len(channel_mult) - 1: out_ch = ch self.input_blocks.append( ...
class AttentionPool2d(nn.Module): """ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py """ def __init__( self, spacial_dim: int, embed_dim: int, num_heads_channels: int, output_dim: int = None, ): super().__init__() ...
self.input_blocks.apply(convert_module_to_f32)
1
2023-10-21 04:08:44+00:00
4k
NVIDIA-Omniverse/IsaacSim-Automator
src/python/deployer.py
[ { "identifier": "colorize_error", "path": "src/python/utils.py", "snippet": "def colorize_error(text):\n return click.style(text, fg=\"bright_red\", italic=True)" }, { "identifier": "colorize_info", "path": "src/python/utils.py", "snippet": "def colorize_info(text):\n return click....
import json import os import re import shlex import sys import click from pathlib import Path from src.python.utils import ( colorize_error, colorize_info, colorize_prompt, colorize_result, read_meta, shell_command, ) from src.python.debug import debug_break # noqa from src.python.ngc import ch...
2,107
self.params["debug"], ) def recreate_command_line(self, separator=" \\\n"): """ Recreate command line """ command_line = sys.argv[0] for k, v in self.input_params.items(): k = k.replace("_", "-") if isinstance(v, bool): ...
# region copyright # Copyright 2023 NVIDIA Corporation # # 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...
r = check_ngc_access(
7
2023-10-18 17:25:44+00:00
4k
blackgold3/SemanticBoost
mdm/sample.py
[ { "identifier": "recover_from_ric", "path": "mdm/dataset/recover_joints.py", "snippet": "def recover_from_ric(data, joints_num):\n if isinstance(data, np.ndarray):\n data = torch.from_numpy(data).float()\n dtype = \"numpy\"\n else:\n data = data.float()\n dtype = \"tens...
from argparse import Namespace from mdm.dataset.recover_joints import recover_from_ric from mdm.model.cfg_sampler import ClassifierFreeSampleModel from mdm.model_util import create_model_and_diffusion, load_model_wo_clip, create_trt_model from mdm.dataset.recover_smr import * from mdm.double_take import double_take imp...
2,862
class Predictor(object): def __init__(self, **kargs): self.path = kargs["path"] self.handshake_size = 20 self.blend_size = 10 self.speedup = kargs.get("speedup", 1) args = Namespace() with open(self.path["config"], 'r') as f: params1 = json.load(f) ...
class Predictor(object): def __init__(self, **kargs): self.path = kargs["path"] self.handshake_size = 20 self.blend_size = 10 self.speedup = kargs.get("speedup", 1) args = Namespace() with open(self.path["config"], 'r') as f: params1 = json.load(f) ...
self.model = ClassifierFreeSampleModel(self.model) # wrapping model with the classifier-free sampler
1
2023-10-20 14:53:26+00:00
4k
justchenhao/SILI_CD
datasets/base_dataset.py
[ { "identifier": "get_transforms", "path": "datasets/transforms.py", "snippet": "def get_transforms(norm=False, img_size=256):\n basic_transform = []\n basic_transform.append(T.ToTensor()) # ndarray转为 torch.FloatTensor, 范围[0,1]\n if norm:\n basic_transform.append(T.Normalize(mean=[0.5, 0...
import os import numpy as np import torch from typing import Dict, Sequence, Tuple, Optional, Union from PIL import Image from torch.utils import data from datasets.transforms import get_transforms, get_mask_transforms from datasets.transforms import get_seg_augs from misc.imutils import pil_rescale, pil_re...
2,067
list_folder_name: str = 'list', scale_ratios: Union[int, list] = 1): super(ImageDataset, self).__init__() self.root_dir = root_dir self.split = split # train | train_aug | val self.list_path = os.path.join(self.root_dir, list_folder_name, self.split+'.t...
""" some basic data loader for example: Image loader, Segmentation loader, data root ├─A ├─label └─list """ def load_img_name_list(dataset_path): img_name_list = np.loadtxt(dataset_path, dtype=str) if img_name_list.ndim == 2: return img_name_list[:, 0] return img_name_list class ImageDatas...
augs = get_seg_augs(imgz_size=256)
2
2023-10-21 09:09:57+00:00
4k
pythonlessons/FinRock
finrock/trading_env.py
[ { "identifier": "State", "path": "finrock/state.py", "snippet": "class State:\n def __init__(\n self, \n timestamp: str, \n open: float, \n high: float, \n low: float, \n close: float, \n volume: float=0.0,\n indi...
import typing import numpy as np from .state import State, Observations from .data_feeder import PdDataFeeder from .reward import simpleReward
2,050
class TradingEnv: def __init__( self, data_feeder: PdDataFeeder, output_transformer: typing.Callable = None, initial_balance: float = 1000.0, max_episode_steps: int = None, window_size: int = 50, reward_function: typing.Callable ...
class TradingEnv: def __init__( self, data_feeder: PdDataFeeder, output_transformer: typing.Callable = None, initial_balance: float = 1000.0, max_episode_steps: int = None, window_size: int = 50, reward_function: typing.Callable ...
def _get_obs(self, index: int, balance: float=None) -> State:
0
2023-10-23 07:44:54+00:00
4k
hitlic/deepepochs
examples/10-multi-optimizers.py
[ { "identifier": "Trainer", "path": "deepepochs/trainer.py", "snippet": "class Trainer(TrainerBase):\r\n def train_step(self,\r\n batch_x:[torch.Tensor, List[torch.Tensor]],\r\n batch_y:[torch.Tensor, List[torch.Tensor]],\r\n **step_args\r\n ...
import torch from torch import nn from torch.nn import functional as F from torchvision.datasets import MNIST from torchvision import transforms from torch.utils.data import DataLoader, random_split from deepepochs import Trainer, Optimizer
1,703
""" 使用多个优化器 """ data_dir = './datasets' transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) mnist_full = MNIST(data_dir, train=True, transform=transform, download=True) train_ds, val_ds = random_split(mnist_full, [55000, 5000]) test_ds = MNIST(data_dir, train=False, tra...
""" 使用多个优化器 """ data_dir = './datasets' transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) mnist_full = MNIST(data_dir, train=True, transform=transform, download=True) train_ds, val_ds = random_split(mnist_full, [55000, 5000]) test_ds = MNIST(data_dir, train=False, tra...
opts = [Optimizer(opt1), Optimizer(opt2)] # 第二种方式,这种方式可为每个优化器指定高度器
1
2023-10-19 05:41:48+00:00
4k
yukara-ikemiya/minimal-sqvae
models/sqvae.py
[ { "identifier": "Encoder", "path": "models/encdec.py", "snippet": "class Encoder(nn.Module):\n def __init__(self, in_ch, width, depth, num_down, stride, **kwargs):\n super().__init__()\n\n blocks = []\n for ii in range(num_down):\n # Down-sampling\n down = n...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from .encdec import Encoder, Decoder from .stochastic_quantizer import SQuantizer
2,202
""" Copyright (C) 2023 Yukara Ikemiya """ class SQVAE(nn.Module): def __init__(self, kwargs_encdec: dict, kwargs_quantizer: dict): super().__init__() assert (kwargs_encdec['width'] == kwargs_quantizer['dim_dict']) self.encoder = Encoder(**kwargs_encdec)
""" Copyright (C) 2023 Yukara Ikemiya """ class SQVAE(nn.Module): def __init__(self, kwargs_encdec: dict, kwargs_quantizer: dict): super().__init__() assert (kwargs_encdec['width'] == kwargs_quantizer['dim_dict']) self.encoder = Encoder(**kwargs_encdec)
self.decoder = Decoder(**kwargs_encdec)
1
2023-10-15 14:48:55+00:00
4k
colour-science/colour-visuals
colour_visuals/planckian_locus.py
[ { "identifier": "DEFAULT_FLOAT_DTYPE_WGPU", "path": "colour_visuals/common.py", "snippet": "DEFAULT_FLOAT_DTYPE_WGPU = np.float32" }, { "identifier": "append_channel", "path": "colour_visuals/common.py", "snippet": "def append_channel(a: ArrayLike, value: float = 1) -> NDArray:\n \"\"...
import numpy as np import pygfx as gfx from colour.hints import ( ArrayLike, Literal, Sequence, cast, ) from colour.plotting import ( CONSTANTS_COLOUR_STYLE, LABELS_PLANCKIAN_LOCUS_DEFAULT, lines_planckian_locus, ) from colour.utilities import ( as_int_scalar, optional, ) from colour...
3,181
colour: ArrayLike | None = None, opacity: float = 1, thickness: float = 1, ): super().__init__() self._planckian_locus = None self._iso_temperature_lines = [] self._texts = [] self._labels = None self._mireds = False with self.block_...
# !/usr/bin/env python """ Planckian Locus Visuals ======================= Defines the *Planckian Locus* visuals: - :class:`colour_visuals.VisualPlanckianLocus` """ from __future__ import annotations __author__ = "Colour Developers" __copyright__ = "Copyright 2023 Colour Developers" __license__ = "BSD-3-Clause ...
append_channel(colour_sl, self._opacity)
1
2023-10-15 04:30:47+00:00
4k
JiahuiLei/NAP
core/models/utils/occnet_utils/utils/voxels.py
[ { "identifier": "check_mesh_contains", "path": "core/models/utils/occnet_utils/utils/libmesh/inside_mesh.py", "snippet": "def check_mesh_contains(mesh, points, hash_resolution=512):\n intersector = MeshIntersector(mesh, hash_resolution)\n contains = intersector.query(points)\n return contains" ...
import numpy as np import trimesh from scipy import ndimage from skimage.measure import block_reduce from .libvoxelize.voxelize import voxelize_mesh_ from .libmesh import check_mesh_contains from .common import make_3d_grid
2,850
v_idx[f1_l_x, f1_l_y, f1_l_z + 1], v_idx[f1_l_x, f1_l_y + 1, f1_l_z + 1], v_idx[f1_l_x, f1_l_y + 1, f1_l_z], ], axis=1) faces_1_r = np.stack([ v_idx[f1_r_x, f1_r_y, f1_r_z], v_idx[f1_r_x, f1_r_y + 1, f1_r_z], v_idx[f1_r_x, f1_r_y +...
class VoxelGrid: def __init__(self, data, loc=(0., 0., 0.), scale=1): assert (data.shape[0] == data.shape[1] == data.shape[2]) data = np.asarray(data, dtype=np.bool) loc = np.asarray(loc) self.data = data self.loc = loc self.scale = scale @classmethod def f...
points = make_3d_grid(bb_min, bb_max, shape=shape).numpy()
1
2023-10-22 03:46:35+00:00
4k
Th3Tr1ckst3r/GReverse
greverse.py
[ { "identifier": "requestData", "path": "utils/imageSearch.py", "snippet": "def requestData(image_input, max_results=10, titles_to_urls=None):\n client = vision_v1.ImageAnnotatorClient()\n if image_input.startswith('http') or image_input.startswith('https'):\n response = requests.get(image_i...
import sys import argparse from utils.imageSearch import requestData as imageSearch from utils.querySearch import requestData as querySearch from utils.dataUtils import * from api_creds.creds import googleCreds
1,654
""" GReverse - A tool for OSINT(Open Source Intelligence) gathering & facial recognition via Google Custom Search & Google Vision API's. Created by Adrian Tarver(Th3Tr1ckst3r) @ https://github.com/Th3Tr1ckst3r/ //////////////////////////////////////////////////////////////////////////////////////// IMPORTAN...
""" GReverse - A tool for OSINT(Open Source Intelligence) gathering & facial recognition via Google Custom Search & Google Vision API's. Created by Adrian Tarver(Th3Tr1ckst3r) @ https://github.com/Th3Tr1ckst3r/ //////////////////////////////////////////////////////////////////////////////////////// IMPORTAN...
from utils.imageSearch import requestData as imageSearch
0
2023-10-20 03:48:16+00:00
4k
yongliang-wu/ExploreCfg
open_flamingo/src/factory.py
[ { "identifier": "Flamingo", "path": "open_flamingo/src/flamingo.py", "snippet": "class Flamingo(nn.Module):\n def __init__(\n self,\n vision_encoder: nn.Module,\n lang_encoder: nn.Module,\n eoc_token_id: int,\n media_token_id: int,\n vis_dim: int,\n cr...
from transformers import AutoModelForCausalLM, AutoTokenizer from typing import Literal, Optional from .flamingo import Flamingo from .flamingo_lm import FlamingoLMMixin from .utils import extend_instance from open_clip import transformer from torch.nn import functional as F import open_clip import torch
3,579
def LNormforward(self, x: torch.Tensor): #x = F.layer_norm(x.to(torch.float32), self.normalized_shape, self.weight, self.bias, self.eps) return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) transformer.LayerNormFp32.forward = LNormforward def create_model_and_transforms( clip_...
def LNormforward(self, x: torch.Tensor): #x = F.layer_norm(x.to(torch.float32), self.normalized_shape, self.weight, self.bias, self.eps) return F.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps) transformer.LayerNormFp32.forward = LNormforward def create_model_and_transforms( clip_...
extend_instance(lang_encoder, FlamingoLMMixin)
1
2023-10-18 02:38:00+00:00
4k
mimo-x/Code-Review-GPT-Gitlab
app/gitlab_webhook.py
[ { "identifier": "WEBHOOK_VERIFY_TOKEN", "path": "config/config.py", "snippet": "" }, { "identifier": "review_code", "path": "service/chat_review.py", "snippet": "@retry(stop_max_attempt_number=3, wait_fixed=2000)\ndef review_code(project_id, project_commit_id, merge_id, context):\n re...
import json import threading from os import abort from flask import Blueprint, request, jsonify from config.config import WEBHOOK_VERIFY_TOKEN from service.chat_review import review_code, review_code_for_mr, review_code_for_add_commit from utils.logger import log from app.gitlab_utils import get_commit_list, get_merge_...
2,757
git = Blueprint('git', __name__) @git.route('/api') def question(): return 'hello world' @git.route('/webhook', methods=['GET', 'POST']) def webhook(): if request.method == 'GET': # 获取gitlab的webhook的token verify_token = request.headers.get('X-Gitlab-Token') # gitlab的webhook的token验证...
git = Blueprint('git', __name__) @git.route('/api') def question(): return 'hello world' @git.route('/webhook', methods=['GET', 'POST']) def webhook(): if request.method == 'GET': # 获取gitlab的webhook的token verify_token = request.headers.get('X-Gitlab-Token') # gitlab的webhook的token验证
if verify_token == WEBHOOK_VERIFY_TOKEN:
0
2023-10-19 14:10:10+00:00
4k
vorausrobotik/voraus-ad-dataset
tests/test_normalizing_flow.py
[ { "identifier": "Configuration", "path": "configuration.py", "snippet": "class Configuration(BaseModel):\n \"\"\"Describes the configuration parameters.\"\"\"\n\n seed: int\n epochs: int\n batchsize: int\n n_hidden_layers: int = Field(alias=\"nHiddenLayers\")\n n_coupling_blocks: int =...
from typing import List from configuration import Configuration from normalizing_flow import InternalNetwork, NormalizingFlow, get_loss, get_loss_per_sample import pytest import torch
2,602
"""Contains tests for the normalizing flow module.""" @pytest.mark.parametrize( ("z_tensor", "jacobian", "expected_loss"), ( ([[0, 1, 2, 3], [2, 3, 4, 5]], [[1, 3], [1, 3]], 8.0), ([[1, 2, 3, 0], [4, 3, 2, 5]], [[1, 3], [1, 3]], 8.0), ([[6, 0, 1, 2], [7, 0, 0, 1]], [[1, 3], [1, 3]]...
"""Contains tests for the normalizing flow module.""" @pytest.mark.parametrize( ("z_tensor", "jacobian", "expected_loss"), ( ([[0, 1, 2, 3], [2, 3, 4, 5]], [[1, 3], [1, 3]], 8.0), ([[1, 2, 3, 0], [4, 3, 2, 5]], [[1, 3], [1, 3]], 8.0), ([[6, 0, 1, 2], [7, 0, 0, 1]], [[1, 3], [1, 3]]...
internal_network_factory = InternalNetwork.setup(
1
2023-10-18 15:09:24+00:00
4k
invictus717/UniDG
domainbed/algorithms.py
[ { "identifier": "networks", "path": "domainbed/networks.py", "snippet": "def remove_batch_norm_from_resnet(model):\n def __init__(self):\n def forward(self, x):\n def __init__(self):\n def forward(self, x):\n def __init__(self, n_inputs, n_outputs, hparams):\n def forward(self, x):\n ...
import torch import torch.nn as nn import torch.nn.functional as F import torch.autograd as autograd import copy import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from domainbed import networks from domainbed.lib.misc import random_pairs_of_minibatches from domainbed.optimizers impor...
1,944
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved ALGORITHMS = [ 'ERM', 'IRM', 'GroupDRO', 'Mixup', 'MLDG', 'CORAL', 'MMD', 'DANN', 'CDANN', 'MTL', 'SagNet', 'ARM', 'VREx', 'RSC', 'SD', 'MIRO' ] def get_algorithm_class(algorithm_...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved ALGORITHMS = [ 'ERM', 'IRM', 'GroupDRO', 'Mixup', 'MLDG', 'CORAL', 'MMD', 'DANN', 'CDANN', 'MTL', 'SagNet', 'ARM', 'VREx', 'RSC', 'SD', 'MIRO' ] def get_algorithm_class(algorithm_...
self.featurizer = networks.Featurizer(input_shape, self.hparams)
0
2023-10-15 14:26:12+00:00
4k
AI-Application-and-Integration-Lab/DGUA_FAS
util/evaluate.py
[ { "identifier": "AverageMeter", "path": "util/utils.py", "snippet": "class AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n ...
from util.utils import AverageMeter, accuracy from util.statistic import get_EER_states, get_HTER_at_thr, calculate, calculate_threshold from sklearn.metrics import roc_auc_score from torch.autograd import Variable from torch.nn import functional as F import torch import torch.nn as nn import numpy as np
1,771
def eval(valid_dataloader, model): criterion = nn.CrossEntropyLoss() valid_losses = AverageMeter() valid_top1 = AverageMeter() prob_dict = {} label_dict = {} model.eval() output_dict_tmp = {} target_dict_tmp = {} with torch.no_grad(): for iter, (input, target, videoID) ...
def eval(valid_dataloader, model): criterion = nn.CrossEntropyLoss() valid_losses = AverageMeter() valid_top1 = AverageMeter() prob_dict = {} label_dict = {} model.eval() output_dict_tmp = {} target_dict_tmp = {} with torch.no_grad(): for iter, (input, target, videoID) ...
ACC_threshold = calculate_threshold(prob_list, label_list, threshold)
5
2023-10-17 15:35:33+00:00
4k
jianlanluo/SAQ
vqn/vqiql.py
[ { "identifier": "FullyConnectedNetwork", "path": "vqn/model.py", "snippet": "class FullyConnectedNetwork(nn.Module):\n output_dim: int\n arch: str = '256-256'\n orthogonal_init: bool = False\n\n @nn.compact\n def __call__(self, input_tensor):\n x = input_tensor\n hidden_size...
import copy import collections import distrax import jax import jax.numpy as jnp import numpy as np import optax import flax from typing import Any, Callable, Dict, Iterable, Optional, Sequence, Tuple, Union from functools import partial from gym.utils import seeding from jax import random from flax import linen as nn ...
2,839
def squared_euclidean_distance(a, b, b2=None, precision=None): if b2 is None: b2 = jnp.sum(b.T**2, axis=0, keepdims=True) a2 = jnp.sum(a**2, axis=1, keepdims=True) ab = jnp.matmul(a, b.T, precision=precision) d = a2 - 2 * ab + b2 return d def entropy_loss_fn(affinity, loss_type="softmax", t...
"""Implementations of algorithms for continuous control.""" Batch = collections.namedtuple( 'Batch', ['observations', 'actions', 'rewards', 'masks', 'next_observations']) def default_init(scale: Optional[float] = jnp.sqrt(2)): return nn.initializers.orthogonal(scale) Shape = Sequence[int] Dtype =...
self.encoder = FullyConnectedNetwork(
0
2023-10-18 06:31:20+00:00
4k
naver-ai/dual-teacher
tools/test.py
[ { "identifier": "multi_gpu_test", "path": "mmseg/apis/test.py", "snippet": "def multi_gpu_test(model,\n data_loader,\n tmpdir=None,\n gpu_collect=False,\n efficient_test=False):\n \"\"\"Test model with multiple gpus.\n\n This ...
import argparse import os import mmcv import torch from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import get_dist_info, init_dist, load_checkpoint from mmcv.utils import DictAction from mmseg.apis import multi_gpu_test, single_gpu_test from mmseg.datasets import build_dataloader, b...
3,326
parser.add_argument('--out', default='work_dirs/res.pkl', help='output result file in pickle format') parser.add_argument( '--format-only', action='store_true', help='Format the output results without perform evaluation. It is' 'useful when you want to format the result to a...
def parse_args(): parser = argparse.ArgumentParser( description='mmseg test (and eval) a model') parser.add_argument('config', help='test config file path') parser.add_argument('checkpoint', help='checkpoint file') parser.add_argument( '--aug-test', action='store_true', help='Use Fli...
outputs = single_gpu_test(model, data_loader, args.show, args.show_dir, efficient_test)
1
2023-10-19 04:04:31+00:00
4k
Azure/azure-openai-benchmark
tests/oairequester.py
[ { "identifier": "OAIRequester", "path": "benchmark/oairequester.py", "snippet": "class OAIRequester:\n \"\"\"\n A simple AOAI requester that makes a streaming call and collect corresponding\n statistics.\n :param api_key: Azure OpenAI resource endpoint key.\n :param url: Full deployment U...
import unittest import time import httpretty from benchmark.oairequester import OAIRequester, UTILIZATION_HEADER, RETRY_AFTER_MS_HEADER
1,716
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. TEST_URL = "https://testresource.openai.azure.com/openai/deployments/depl/chat/completion?api-version=2023-05-15" class TokenIterator: def __init__(self, delay: float): self.done = False self.delay = delay self.token...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. TEST_URL = "https://testresource.openai.azure.com/openai/deployments/depl/chat/completion?api-version=2023-05-15" class TokenIterator: def __init__(self, delay: float): self.done = False self.delay = delay self.token...
adding_headers={RETRY_AFTER_MS_HEADER: 100},
2
2023-10-19 00:52:26+00:00
4k
pytest-visual/pytest-visual
examples/end_to_end/test_main.py
[ { "identifier": "ClockCoordinateDataset", "path": "examples/end_to_end/main.py", "snippet": "def main() -> None:\n def __init__(self, data_dir: Path, normalize: bool = True):\n def __getitem__(self, index: int) -> Tuple[Tensor, \"Time\"]:\n def __len__(self) -> int:\n def __init__(self, data...
from pathlib import Path from typing import List from PIL import Image from torch import Tensor from examples.end_to_end.main import ( ClockCoordinateDataset, ClockDataset, Time, get_label, get_model, get_model_head, mean_norm, std_norm, ) from visual.interface import VisualFixture, fix_...
2,571
test_data_path = Path("examples/end_to_end/test_data") def test_original_labels(visual: VisualFixture, fix_seeds): dataset = ClockDataset(test_data_path / "train") images, labels = [], [] for image, label in dataset: # Convert to numpy, denormalize, and standardize layout to HWC
test_data_path = Path("examples/end_to_end/test_data") def test_original_labels(visual: VisualFixture, fix_seeds): dataset = ClockDataset(test_data_path / "train") images, labels = [], [] for image, label in dataset: # Convert to numpy, denormalize, and standardize layout to HWC
images.append(standardize(image.numpy(), mean_denorm=mean_norm, std_denorm=std_norm))
0
2023-10-18 07:13:37+00:00
4k
SLDGroup/G-CASCADE
trainer.py
[ { "identifier": "Synapse_dataset", "path": "utils/dataset_synapse.py", "snippet": "class Synapse_dataset(Dataset):\n def __init__(self, base_dir, list_dir, split, nclass=9, transform=None):\n self.transform = transform # using transform in torch!\n self.split = split\n self.samp...
import argparse import logging import os import random import sys import time import numpy as np import torch import torch.nn as nn import torch.optim as optim from tqdm import tqdm from tensorboardX import SummaryWriter from torch.nn.modules.loss import CrossEntropyLoss from torch.utils.data import DataLoader from tor...
2,578
def inference(args, model, best_performance): db_test = Synapse_dataset(base_dir=args.volume_path, split="test_vol", list_dir=args.list_dir, nclass=args.num_classes) testloader = DataLoader(db_test, batch_size=1, shuffle=False, num_workers=1) logging.info("{} test iterations per epoch"....
def inference(args, model, best_performance): db_test = Synapse_dataset(base_dir=args.volume_path, split="test_vol", list_dir=args.list_dir, nclass=args.num_classes) testloader = DataLoader(db_test, batch_size=1, shuffle=False, num_workers=1) logging.info("{} test iterations per epoch"....
dice_loss = DiceLoss(num_classes)
4
2023-10-24 17:49:10+00:00
4k
StackTipsLab/bloggy
bloggy/views/edit_profile_view.py
[ { "identifier": "settings", "path": "bloggy/settings.py", "snippet": "BASE_DIR = Path(__file__).resolve().parent.parent\nSECRET_KEY = os.getenv(\"SECRET_KEY\", get_random_secret_key())\nDEBUG = os.getenv(\"DEBUG\", \"False\") == \"True\"\nALLOWED_HOSTS = os.getenv(\"ALLOWED_HOSTS\", \"127.0.0.1, localho...
import os from django.shortcuts import get_object_or_404 from django.template.context_processors import static from django.views.generic import FormView from bloggy import settings from bloggy.forms.edit_profile_form import EditProfileForm from bloggy.models import User from bloggy.templatetags.custom_widgets import sa...
3,185
class EditProfileView(FormView): template_name = "profile/edit_profile.html" model = User
class EditProfileView(FormView): template_name = "profile/edit_profile.html" model = User
form_class = EditProfileForm
1
2023-10-17 14:50:39+00:00
4k
openvinotoolkit/openvino.genai
llm_bench/python/utils/conversion_utils/better_transformer_patch.py
[ { "identifier": "_make_causal_mask", "path": "llm_bench/python/utils/conversion_utils/convert_patch.py", "snippet": "def _make_causal_mask(\n input_ids_shape: torch.Size,\n device: torch.device,\n past_key_values_length: int,\n dtype: torch.dtype = torch.bool,\n) -> torch.BoolTensor:\n \"...
import math import torch from torch import nn from typing import Optional, Tuple, Union from transformers import PretrainedConfig from optimum.bettertransformer.models.attention import ( codegen_wrapped_scaled_dot_product, ) from .convert_patch import _make_causal_mask, _expand_mask from optimum.bettertransform...
3,332
self.rotary_emb = RotaryEmbedding( self.rotary_ndims, max_position_embeddings=self.config.max_position_embeddings, base=self.config.rope_theta, ) def forward( self, hidden_states: torch.FloatTensor, attention_mask: torch.FloatTensor, ...
# -*- coding: utf-8 -*- # Copyright (C) 2018-2023 Intel Corporation # SPDX-License-Identifier: Apache-2.0 def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value...
expanded_attn_mask = _expand_mask(
1
2023-10-16 13:38:16+00:00
4k
Iniquitatis/sd-webui-temporal
scripts/main.py
[ { "identifier": "get_first_element", "path": "temporal/collection_utils.py", "snippet": "def get_first_element(coll, fallback = None):\n return next(iter(coll)) if coll else fallback" }, { "identifier": "load_text", "path": "temporal/fs.py", "snippet": "def load_text(path, fallback = ...
from pathlib import Path from types import SimpleNamespace from modules import scripts from modules.sd_samplers import visible_sampler_names from modules.ui_components import InputAccordion, ToolButton from temporal.collection_utils import get_first_element from temporal.fs import load_text from temporal.image_blending...
2,778
class UI: def __init__(self, id_formatter): self._id_formatter = id_formatter self._elems = {} self._ids = [] self._groups = {} self._callbacks = {} self._existing_labels = set() def parse_ids(self, ids): result = [] for id in ids: ...
class UI: def __init__(self, id_formatter): self._id_formatter = id_formatter self._elems = {} self._ids = [] self._groups = {} self._callbacks = {} self._existing_labels = set() def parse_ids(self, ids): result = [] for id in ids: ...
save_preset(preset, ext_params)
7
2023-10-15 18:49:12+00:00
4k
zabbix/python-zabbix-utils
zabbix_utils/api.py
[ { "identifier": "ModuleUtils", "path": "zabbix_utils/common.py", "snippet": "class ModuleUtils():\n\n # Hidding mask for sensitive data\n HIDING_MASK = \"*\" * 8\n\n # The main php-file of Zabbix API\n JSONRPC_FILE = 'api_jsonrpc.php'\n\n # Methods working without auth token\n UNAUTH_M...
import re import ssl import json import base64 import logging import urllib.request as ul from textwrap import shorten from uuid import uuid4 from os import environ as env from urllib.error import URLError from typing import Callable, Union, Any, List from typing import Self # type: ignore from typing_extensio...
1,938
# zabbix_utils # # Copyright (C) 2001-2023 Zabbix SIA # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, # ...
# zabbix_utils # # Copyright (C) 2001-2023 Zabbix SIA # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, # ...
log.addHandler(EmptyHandler())
1
2023-10-16 12:49:35+00:00
4k
miccunifi/TAPE
models/mrsff.py
[ { "identifier": "compute_mask_2D", "path": "utils/utils_models.py", "snippet": "def compute_mask_2D(H: int, W: int, window_size: Tuple[int], shift_size: Tuple[int], device: torch.device) -> torch.Tensor:\n \"\"\"\n Compute 2D mask for window-based multi-head self-attention\n \"\"\"\n img_mas...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from typing import Tuple from einops import rearrange from utils.utils_models import (compute_mask_2D, window_partition_2D, window_reverse_2D, get_window_size, DropPath, Mlp, trunc_normal_)
2,950
class AttentionPooling1d(nn.Module): """ Inspired by https://amaarora.github.io/posts/2023-03-11_Understanding_CLIP_part_2.html and https://github.com/openai/CLIP/blob/a1d071733d7111c9c014f024669f959182114e33/clip/model.py#L58 Args: dim (int): Input dimension. num_heads (int): Number...
class AttentionPooling1d(nn.Module): """ Inspired by https://amaarora.github.io/posts/2023-03-11_Understanding_CLIP_part_2.html and https://github.com/openai/CLIP/blob/a1d071733d7111c9c014f024669f959182114e33/clip/model.py#L58 Args: dim (int): Input dimension. num_heads (int): Number...
trunc_normal_(self.relative_position_bias_table, std=.02)
6
2023-10-19 09:14:40+00:00
4k
boppreh/hello_tls
src/hello_tls/__main__.py
[ { "identifier": "scan_server", "path": "src/hello_tls/scan.py", "snippet": "def scan_server(\n connection_settings: Union[ConnectionSettings, str],\n client_hello: Optional[ClientHello] = None,\n do_enumerate_cipher_suites: bool = True,\n do_enumerate_groups: bool = True,\n fetch_cert_cha...
from .scan import scan_server, DEFAULT_TIMEOUT, DEFAULT_MAX_WORKERS, parse_target, ConnectionSettings, to_json_obj from .protocol import ClientHello from .names_and_numbers import Protocol import os import sys import json import logging import argparse
2,604
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("target", help="server to scan, in the form of 'example.com', 'example.com:443', or even a full URL") parser.add_argument("--timeout", "-t", dest="timeout", type=float, default=DEFAULT_TIMEOUT, help="socket con...
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("target", help="server to scan, in the form of 'example.com', 'example.com:443', or even a full URL") parser.add_argument("--timeout", "-t", dest="timeout", type=float, default=DEFAULT_TIMEOUT, help="socket con...
json.dump(to_json_obj(results), sys.stdout, indent=2)
5
2023-10-21 02:00:13+00:00
4k
OPTML-Group/Diffusion-MU-Attack
src/tasks/classifier_.py
[ { "identifier": "calculate_clip_score", "path": "src/tasks/utils/metrics/clip_score.py", "snippet": "def calculate_clip_score(images, prompts,device):\n clip_score = clip_score_fn(torch.from_numpy(images).to(device), prompts).detach()\n return round(float(clip_score), 4)" }, { "identifier"...
import os import torch import torch.nn.functional as F from copy import deepcopy from diffusers import AutoencoderKL, UNet2DConditionModel, LMSDiscreteScheduler from transformers import CLIPTextModel, CLIPTokenizer from PIL import Image from uuid import uuid4 from .utils.metrics.clip_score import calculate_clip_score f...
2,359
class ClassifierTask: def __init__( self, concept, sld, sld_concept, negative_prompt, model_name_or_path, target_ckpt, cache_path, dataset_path, criterion,...
class ClassifierTask: def __init__( self, concept, sld, sld_concept, negative_prompt, model_name_or_path, target_ckpt, cache_path, dataset_path, criterion,...
self.clip_model, self.classifier = q16_binary_classifier(self.device)
3
2023-10-17 13:54:37+00:00
4k
YefanZhou/TempBalance
object_detection/src/YOLOv8/ultralytics/yolo/utils/tal.py
[ { "identifier": "check_version", "path": "object_detection/src/YOLOv8/ultralytics/yolo/utils/checks.py", "snippet": "def check_version(current: str = '0.0.0',\n minimum: str = '0.0.0',\n name: str = 'version ',\n pinned: bool = False,\n ...
import torch import torch.nn as nn from .checks import check_version from .metrics import bbox_iou
3,543
target_gt_idx (Tensor): shape(b, h*w) fg_mask (Tensor): shape(b, h*w) mask_pos (Tensor): shape(b, n_max_boxes, h*w) """ # (b, n_max_boxes, h*w) -> (b, h*w) fg_mask = mask_pos.sum(-2) if fg_mask.max() > 1: # one anchor is assigned to multiple gt_bboxes mask_multi_gts = (f...
# Ultralytics YOLO 🚀, AGPL-3.0 license TORCH_1_10 = check_version(torch.__version__, '1.10.0') def select_candidates_in_gts(xy_centers, gt_bboxes, eps=1e-9): """select the positive anchor center in gt Args: xy_centers (Tensor): shape(h*w, 4) gt_bboxes (Tensor): shape(b, n_boxes, 4) Re...
overlaps[mask_gt] = bbox_iou(gt_boxes, pd_boxes, xywh=False, CIoU=True).squeeze(-1).clamp(0)
1
2023-10-24 00:45:55+00:00
4k
zhaojw1998/AccoMontage-3
orchestrator/prior_model.py
[ { "identifier": "Query_and_reArrange", "path": "orchestrator/QA_model.py", "snippet": "class Query_and_reArrange(nn.Module):\n \"\"\"Q&A model for multi-track rearrangement\"\"\"\n def __init__(self, name, device, trf_layers=2):\n super(Query_and_reArrange, self).__init__()\n\n self....
import math import random import torch import torch.nn.functional as F import numpy as np import os from torch import nn from .QA_model import Query_and_reArrange from .TransformerEncoderLayer import TransformerEncoderLayer as TransformerEncoderLayerRPE from .prior_dataset import NUM_INSTR_CLASS, NUM_TIME_CODE,...
3,558
class Prior(nn.Module): def __init__(self, mixture_encoder=None, function_encoder=None, context_enc_layer=12, function_dec_layer=12, d_model=256, nhead=8, dim_feedforward=10...
class Prior(nn.Module): def __init__(self, mixture_encoder=None, function_encoder=None, context_enc_layer=12, function_dec_layer=12, d_model=256, nhead=8, dim_feedforward=10...
self.rel_pos_embedding = nn.Embedding(num_embeddings=len(REL_POS_BIN)+1, embedding_dim=d_model, padding_idx=len(REL_POS_BIN))
6
2023-10-23 12:36:57+00:00
4k
zcczhang/UVD
uvd/utils/video_utils.py
[ { "identifier": "any_stack", "path": "uvd/utils/array_tensor_utils.py", "snippet": "def any_stack(xs: List, *, dim: int = 0):\n \"\"\"Works for both torch Tensor and numpy array.\"\"\"\n\n def _any_stack_helper(*xs):\n x = xs[0]\n if isinstance(x, np.ndarray):\n return np....
import subprocess import numpy as np import torch import torchvision.io import ffmpeg # pip install ffmpeg-python from typing import Union, List, Optional from .array_tensor_utils import any_stack, any_to_torch_tensor, any_to_numpy from .file_utils import f_mkdir, f_join, f_remove from einops import rearra...
1,608
__all__ = ["save_video", "ffmpeg_save_video", "compress_video", "VideoTensorWriter"] def save_video( video: Union[np.ndarray, torch.Tensor], fname: str, fps: Optional[int] = None, compress: bool = False, ): fname = f_join(fname) video = any_to_torch_tensor(video) assert video.ndim == 4...
__all__ = ["save_video", "ffmpeg_save_video", "compress_video", "VideoTensorWriter"] def save_video( video: Union[np.ndarray, torch.Tensor], fname: str, fps: Optional[int] = None, compress: bool = False, ): fname = f_join(fname) video = any_to_torch_tensor(video) assert video.ndim == 4...
video = any_to_numpy(video)
2
2023-10-17 19:08:14+00:00
4k
skywalker023/confaide
eval.py
[ { "identifier": "GPT3BaseAgent", "path": "agents/gpt.py", "snippet": "class GPT3BaseAgent():\n def __init__(self, kwargs: dict):\n openai.api_key = os.getenv('OPENAI_API_KEY')\n self.args = SimpleNamespace(**kwargs)\n self._set_default_args()\n\n def _set_default_args(self):\n...
import os import json import argparse import random import torch import numpy as np import pandas as pd import colorful as cf import agents.huggingface as hfa from pathlib import Path from collections import Counter from torch.utils.data import DataLoader, Dataset from tqdm import tqdm from agents.gpt import GPT3BaseAg...
1,783
tqdm.pandas() cf.use_true_colors() cf.use_style('monokai') PROJECT_HOME = Path(__file__).parent.resolve() EVAL_DIR_PATH = os.path.join(PROJECT_HOME, 'eval_results') RANDOM_SEED = 99 random.seed(RANDOM_SEED) class PrivacyTierDataset(Dataset): def __init__(self, data, meta_data=None): if 'tier' in meta_d...
tqdm.pandas() cf.use_true_colors() cf.use_style('monokai') PROJECT_HOME = Path(__file__).parent.resolve() EVAL_DIR_PATH = os.path.join(PROJECT_HOME, 'eval_results') RANDOM_SEED = 99 random.seed(RANDOM_SEED) class PrivacyTierDataset(Dataset): def __init__(self, data, meta_data=None): if 'tier' in meta_d...
model = ConversationalGPTBaseAgent({'model': self.args.model, 'temperature': 1, 'top_p': 1, 'frequency_penalty': 0.0, 'presence_penalty': 0.0})
1
2023-10-24 22:37:09+00:00
4k
bytedance/ColTrack
models/dino/backbone.py
[ { "identifier": "NestedTensor", "path": "util/misc.py", "snippet": "class NestedTensor(object):\n def __init__(self, tensors, mask: Optional[Tensor]):\n self.tensors = tensors\n self.mask = mask\n if mask == 'auto':\n self.mask = torch.zeros_like(tensors).to(tensors.de...
from collections import OrderedDict from torch import nn from torchvision.models._utils import IntermediateLayerGetter from typing import Dict, List from util.misc import NestedTensor, clean_state_dict, is_main_process from .position_encoding import build_position_encoding from .convnext import build_convnext from .swi...
2,437
# ------------------------------------------------------------------------ # DINO # Copyright (c) 2022 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Conditional DETR # Copyright (c) 2021 ...
# ------------------------------------------------------------------------ # DINO # Copyright (c) 2022 IDEA. All Rights Reserved. # Licensed under the Apache License, Version 2.0 [see LICENSE for details] # ------------------------------------------------------------------------ # Conditional DETR # Copyright (c) 2021 ...
def forward(self, tensor_list: NestedTensor):
0
2023-10-16 02:18:33+00:00
4k
alm0ra/mockafka-py
mockafka/producer.py
[ { "identifier": "ClusterMetadata", "path": "mockafka/cluster_metadata.py", "snippet": "class ClusterMetadata(object):\n \"\"\"\n Provides information about the Kafka cluster, brokers, and topics.\n Returned by list_topics().\n\n This class is typically not user instantiated.\n \"\"\"\n\n ...
from mockafka.cluster_metadata import ClusterMetadata from mockafka.kafka_store import KafkaStore from mockafka.message import Message
2,245
__all__ = ["FakeProducer"] class FakeProducer(object): def __init__(self, config: dict = None): self.kafka = KafkaStore() def produce(self, topic, value=None, *args, **kwargs): # create a message and call produce kafka message = Message(value=value, topic=topic, *args, **kwargs) ...
__all__ = ["FakeProducer"] class FakeProducer(object): def __init__(self, config: dict = None): self.kafka = KafkaStore() def produce(self, topic, value=None, *args, **kwargs): # create a message and call produce kafka message = Message(value=value, topic=topic, *args, **kwargs) ...
return ClusterMetadata(topic)
0
2023-10-24 13:27:12+00:00
4k
CuriseJia/FreeStyleRet
imagenet_test/freeblip_test.py
[ { "identifier": "BLIP_Retrieval", "path": "src/models/blip_retrieval.py", "snippet": "class BLIP_Retrieval(nn.Module):\n def __init__(self, model_args):\n super(BLIP_Retrieval, self).__init__()\n self.args = model_args\n self.blip = blip_retrieval(pretrained=self.args.origin_resu...
import argparse import sys import torch from tqdm import tqdm from torch.utils.data import DataLoader from tqdm import tqdm from data import S2ITestDataset, T2ITestDataset, M2ITestDataset from src.models import BLIP_Retrieval from src.utils import setup_seed, getR1Accuary, getR5Accuary
2,361
def parse_args(): parser = argparse.ArgumentParser(description='Parse args for FreeStyleRet-CLIP test on ImageNet-X Dataset.') # project settings parser.add_argument('--resume', default='', type=str, help='load model checkpoint from given path') parser.add_argument('--origin_resume', default='', typ...
def parse_args(): parser = argparse.ArgumentParser(description='Parse args for FreeStyleRet-CLIP test on ImageNet-X Dataset.') # project settings parser.add_argument('--resume', default='', type=str, help='load model checkpoint from given path') parser.add_argument('--origin_resume', default='', typ...
model = BLIP_Retrieval(args)
0
2023-10-17 09:32:57+00:00
4k
liuqidong07/MOELoRA-peft
src/MLoRA/peft/tuners/lora.py
[ { "identifier": "is_bnb_available", "path": "src/MLoRA/peft/import_utils.py", "snippet": "def is_bnb_available():\n return importlib.util.find_spec(\"bitsandbytes\") is not None" }, { "identifier": "PeftConfig", "path": "src/MLoRA/peft/utils/config.py", "snippet": "class PeftConfig(Pe...
import math import re import warnings import torch import torch.nn as nn import torch.nn.functional as F import bitsandbytes as bnb from dataclasses import asdict, dataclass, field from enum import Enum from typing import List, Optional, Union from transformers.pytorch_utils import Conv1D from ..import_utils import...
2,423
# 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...
# 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 ap...
_freeze_adapter(self.model, adapter_name)
6
2023-10-19 10:55:50+00:00
4k
voyage-ai/voyageai-python
voyageai/api_resources/voyage_object.py
[ { "identifier": "util", "path": "voyageai/util.py", "snippet": "VOYAGE_LOG = os.environ.get(\"VOYAGE_LOG\")\n VOYAGE = 1\nclass ApiType(Enum):\n def from_str(label):\ndef _console_log_level():\ndef log_debug(message, **params):\ndef log_info(message, **params):\ndef log_warn(message, **params):\nd...
import json from copy import deepcopy from typing import Optional, Tuple, Union from voyageai import util from voyageai.api_resources import api_requestor from voyageai.api_resources.voyage_response import VoyageResponse
2,858
class VoyageObject(dict): def __init__( self, **params, ): super(VoyageObject, self).__init__() self._retrieve_params = params def __setattr__(self, k, v): if k[0] == "_" or k in self.__dict__: return super(VoyageObject, self).__setattr__(k, v) ...
class VoyageObject(dict): def __init__( self, **params, ): super(VoyageObject, self).__init__() self._retrieve_params = params def __setattr__(self, k, v): if k[0] == "_" or k in self.__dict__: return super(VoyageObject, self).__setattr__(k, v) ...
assert not isinstance(response, VoyageResponse) # must be an iterator
2
2023-10-17 22:11:18+00:00
4k
YuroFR/freqtrade-modded-crypto-trading-bot
tests/data/test_download_data.py
[ { "identifier": "setup_utils_configuration", "path": "freqtrade/configuration/config_setup.py", "snippet": "def setup_utils_configuration(args: Dict[str, Any], method: RunMode) -> Dict[str, Any]:\n \"\"\"\n Prepare the configuration for utils subcommands\n :param args: Cli args from Arguments()...
from unittest.mock import MagicMock, PropertyMock from freqtrade.configuration.config_setup import setup_utils_configuration from freqtrade.data.history.history_utils import download_data_main from freqtrade.enums import RunMode from freqtrade.exceptions import OperationalException from tests.conftest import EXMS, log_...
1,793
def test_download_data_main_no_markets(mocker, caplog): dl_mock = mocker.patch('freqtrade.data.history.history_utils.refresh_backtest_ohlcv_data', MagicMock(return_value=["ETH/BTC", "XRP/BTC"])) patch_exchange(mocker, id='binance') mocker.patch(f'{EXMS}.get_markets', return_va...
def test_download_data_main_no_markets(mocker, caplog): dl_mock = mocker.patch('freqtrade.data.history.history_utils.refresh_backtest_ohlcv_data', MagicMock(return_value=["ETH/BTC", "XRP/BTC"])) patch_exchange(mocker, id='binance') mocker.patch(f'{EXMS}.get_markets', return_va...
download_data_main(config)
1
2023-10-21 10:02:05+00:00
4k
yanzhh/HGERE
transformers/src/transformers/modeling_albert.py
[ { "identifier": "add_start_docstrings", "path": "transformers/src/transformers/file_utils.py", "snippet": "def add_start_docstrings(*docstr):\n def docstring_decorator(fn):\n fn.__doc__ = \"\".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else \"\")\n return fn\n\n return docs...
import logging import math import os import torch import torch.nn as nn import pdb import re import numpy as np import tensorflow as tf from torch.nn import CrossEntropyLoss, MSELoss, BCEWithLogitsLoss from torch.nn.utils.rnn import pad_sequence from transformers.configuration_albert import AlbertConfig from tran...
3,534
config_class = AlbertConfig pretrained_model_archive_map = ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP base_model_prefix = "albert" def _init_weights(self, module): """ Initialize the weights. """ if isinstance(module, (nn.Linear, nn.Embedding)): # Slightly different from the TF version which uses truncated_norma...
# coding=utf-8 # Copyright 2018 Google AI, Google Brain and 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 # # U...
@add_start_docstrings_to_callable(ALBERT_INPUTS_DOCSTRING)
1
2023-10-15 02:31:09+00:00
4k
explosion/prodigy-hf
tests/test_train_basics.py
[ { "identifier": "hf_train_ner", "path": "prodigy_hf/ner.py", "snippet": "@recipe(\n \"hf.train.ner\",\n # fmt: off\n datasets=Arg(help=\"Datasets with NER annotations to train model for\"),\n out_dir=Arg(help=\"Folder to save trained model into\"),\n epochs=Arg(\"--epochs\", \"-e\", help=...
import pytest from prodigy_hf import hf_train_ner, hf_train_textcat, hf_ner_correct, hf_textcat_correct
2,386
""" These tests assume some datasets are available in the Prodigy database. Check the `.github/workflows/tests.yml` file for more details. """ def test_smoke_ner(tmpdir): # Make sure we can train without errors
""" These tests assume some datasets are available in the Prodigy database. Check the `.github/workflows/tests.yml` file for more details. """ def test_smoke_ner(tmpdir): # Make sure we can train without errors
hf_train_ner("fashion,eval:fashion", tmpdir, epochs=1, model_name="hf-internal-testing/tiny-random-DistilBertModel")
0
2023-10-19 15:34:07+00:00
4k
johnyang101/pmpnndiff
models/diffusion_lms.py
[ { "identifier": "Generic_LM", "path": "models/pmpnn_lms.py", "snippet": "class Generic_LM(pl.LightningModule):\n def __init__(self, cfg):\n super().__init__()\n self.cfg = cfg\n self.learning_rate = self.cfg.learning_rate\n \n def training_step(self, batch, batch_idx):\n ...
import math import torch import torch.nn.functional as F import torch.distributions as dists import models.diffusion_utils as du from torchtyping import TensorType from models.pmpnn_lms import Generic_LM from data.data_objs import PMPNNBatch from models.pmpnn import PMPNN_Baseline_Diff
1,638
class Generic_Diff_LM(Generic_LM): def __init__(self, cfg, debug=False): super().__init__(cfg) self.debug = debug self.num_classes = cfg.num_classes self.non_abs_classes = self.num_classes - 1 if self.cfg.model.absorbing else self.num_classes self._denoise_fn = self._init_...
class Generic_Diff_LM(Generic_LM): def __init__(self, cfg, debug=False): super().__init__(cfg) self.debug = debug self.num_classes = cfg.num_classes self.non_abs_classes = self.num_classes - 1 if self.cfg.model.absorbing else self.num_classes self._denoise_fn = self._init_...
return PMPNN_Baseline_Diff(**model_conf)
2
2023-10-16 08:47:43+00:00
4k