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
thuml/iTransformer
experiments/exp_basic.py
[ { "identifier": "Transformer", "path": "model/Transformer.py", "snippet": "class Model(nn.Module):\n def __init__(self, configs):\n def forecast(self, x_enc, x_mark_enc, x_dec, x_mark_dec):\n def forward(self, x_enc, x_mark_enc, x_dec, x_mark_dec, mask=None):" }, { "identifier": "Inform...
import os import torch from model import Transformer, Informer, Reformer, Flowformer, Flashformer, \ iTransformer, iInformer, iReformer, iFlowformer, iFlashformer
901
class Exp_Basic(object): def __init__(self, args): self.args = args self.model_dict = { 'Transformer': Transformer, 'Informer': Informer, 'Reformer': Reformer, 'Flowformer': Flowformer, 'Flashformer': Flashformer, 'iTransforme...
class Exp_Basic(object): def __init__(self, args): self.args = args self.model_dict = { 'Transformer': Transformer, 'Informer': Informer, 'Reformer': Reformer, 'Flowformer': Flowformer, 'Flashformer': Flashformer, 'iTransforme...
'iFlashformer': iFlashformer,
9
2023-10-19 03:23:15+00:00
2k
kylesargent/ZeroNVS
threestudio/utils/GAN/vae.py
[ { "identifier": "LinearAttention", "path": "threestudio/utils/GAN/attention.py", "snippet": "class LinearAttention(nn.Module):\n def __init__(self, dim, heads=4, dim_head=32):\n super().__init__()\n self.heads = heads\n hidden_dim = dim_head * heads\n self.to_qkv = nn.Conv...
import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from threestudio.utils.GAN.attention import LinearAttention from threestudio.utils.GAN.util import instantiate_from_config
1,458
from the description in Section 3.5 of "Attention Is All You Need". """ assert len(timesteps.shape) == 1 half_dim = embedding_dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb) emb = emb.to(device=timesteps.device) emb = t...
# pytorch_diffusion + derived encoder decoder def get_timestep_embedding(timesteps, embedding_dim): """ This matches the implementation in Denoising Diffusion Probabilistic Models: From Fairseq. Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly ...
class LinAttnBlock(LinearAttention):
0
2023-10-24 19:02:44+00:00
2k
princeton-nlp/LLM-Shearing
llmshearing/datasets/load_text_dataloader.py
[ { "identifier": "TextDynamicStreamingDataset", "path": "llmshearing/datasets/streaming_dataset.py", "snippet": "class TextDynamicStreamingDataset(DynamicStreamingDataset):\n \"\"\" \n A dataset to load data dynamically from different domains\n Adapted from https://github.com/mosaicml/ll...
from collections import defaultdict from collections.abc import Mapping from dataclasses import dataclass from typing import Any, Dict, List, Optional, Union from omegaconf import DictConfig from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.data.data_collator import _torch...
1,359
""" Load text dataloader for training and evaluation. """ def build_text_dataloader(cfg: DictConfig, device_batch_size: int, dynamic: bool = False, set_names: str = None, proportion: List[float] = None) -> DataLoader: """Builds a text dataloader. Args: cfg (DictConfig): C...
""" Load text dataloader for training and evaluation. """ def build_text_dataloader(cfg: DictConfig, device_batch_size: int, dynamic: bool = False, set_names: str = None, proportion: List[float] = None) -> DataLoader: """Builds a text dataloader. Args: cfg (DictConfig): C...
dataset = TextStreamingDataset(
1
2023-10-16 12:26:08+00:00
2k
hugoycj/Instant-angelo
models/neus.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, render_weight_fro...
1,393
class VarianceNetwork(nn.Module): def __init__(self, config): super(VarianceNetwork, self).__init__() self.config = config self.init_val = self.config.init_val self.register_parameter('variance', nn.Parameter(torch.tensor(self.config.init_val))) self.modulate = self.confi...
class VarianceNetwork(nn.Module): def __init__(self, config): super(VarianceNetwork, self).__init__() self.config = config self.init_val = self.config.init_val self.register_parameter('variance', nn.Parameter(torch.tensor(self.config.init_val))) self.modulate = self.confi...
update_module_step(self.geometry, epoch, global_step)
2
2023-10-22 02:53:17+00:00
2k
HKUDS/GraphGPT
graphgpt/serve/gradio_web_server_graph.py
[ { "identifier": "default_conversation", "path": "graphgpt/conversation.py", "snippet": "class SeparatorStyle(Enum):\nclass Conversation:\n SINGLE = auto()\n TWO = auto()\n MPT = auto()\n W, H = image.size\n H, W = longest_edge, shortest_edge\n ...
import argparse import datetime import json import os import time import gradio as gr import requests import hashlib from graphgpt.conversation import (default_conversation, conv_templates, SeparatorStyle) from graphgpt.constants import LOGDIR from graphgpt.utils import (build_logger,...
772
logger = build_logger("gradio_web_server", "gradio_web_server.log") headers = {"User-Agent": "GraphGPT Client"} no_change_btn = gr.Button.update() enable_btn = gr.Button.update(interactive=True) disable_btn = gr.Button.update(interactive=False) priority = { "vicuna-13b": "aaaaaaa", "koala-13b": "aaaaaab"...
logger = build_logger("gradio_web_server", "gradio_web_server.log") headers = {"User-Agent": "GraphGPT Client"} no_change_btn = gr.Button.update() enable_btn = gr.Button.update(interactive=True) disable_btn = gr.Button.update(interactive=False) priority = { "vicuna-13b": "aaaaaaa", "koala-13b": "aaaaaab"...
state = default_conversation.copy()
0
2023-10-15 05:13:24+00:00
2k
hkchengrex/Cutie
gui/ritm/inference/predictors/brs_functors.py
[ { "identifier": "_compute_iou", "path": "gui/ritm/model/metrics.py", "snippet": "def _compute_iou(pred_mask, gt_mask, ignore_mask=None, keep_ignore=False):\n if ignore_mask is not None:\n pred_mask = torch.where(ignore_mask, torch.zeros_like(pred_mask), pred_mask)\n\n reduction_dims = misc....
import torch import numpy as np from ...model.metrics import _compute_iou from .brs_losses import BRSMaskLoss
1,041
class BaseOptimizer: def __init__(self, optimizer_params, prob_thresh=0.49, reg_weight=1e-3, min_iou_diff=0.01, brs_loss=BRSMaskLoss(), with_flip=False, flip_average=False, **kwargs): se...
class BaseOptimizer: def __init__(self, optimizer_params, prob_thresh=0.49, reg_weight=1e-3, min_iou_diff=0.01, brs_loss=BRSMaskLoss(), with_flip=False, flip_average=False, **kwargs): se...
diff_iou = _compute_iou(current_mask, self._last_mask)
0
2023-10-19 17:49:24+00:00
2k
DeepGraphLearning/ULTRA
script/pretrain.py
[ { "identifier": "tasks", "path": "ultra/tasks.py", "snippet": "def edge_match(edge_index, query_index):\ndef negative_sampling(data, batch, num_negative, strict=True):\ndef all_negative(data, batch):\ndef strict_negative_mask(data, batch):\ndef compute_ranking(pred, target, mask=None):\ndef build_relati...
import os import sys import copy import math import pprint import torch from itertools import islice from functools import partial from torch import optim from torch import nn from torch.nn import functional as F from torch import distributed as dist from torch.utils import data as torch_data from torch_geometric.data ...
1,017
sys.path.append(os.path.dirname(os.path.dirname(__file__))) separator = ">" * 30 line = "-" * 30 def multigraph_collator(batch, train_graphs): num_graphs = len(train_graphs) probs = torch.tensor([graph.edge_index.shape[1] for graph in train_graphs]).float() probs /= probs.sum() graph_id = torch.mu...
sys.path.append(os.path.dirname(os.path.dirname(__file__))) separator = ">" * 30 line = "-" * 30 def multigraph_collator(batch, train_graphs): num_graphs = len(train_graphs) probs = torch.tensor([graph.edge_index.shape[1] for graph in train_graphs]).float() probs /= probs.sum() graph_id = torch.mu...
batch = tasks.negative_sampling(train_graph, batch, cfg.task.num_negative,
0
2023-10-23 17:06:10+00:00
2k
ZhengyiLuo/PerpetualHumanoidControl
uhc/khrylib/models/erd_net.py
[ { "identifier": "RNN", "path": "uhc/khrylib/models/rnn.py", "snippet": "class RNN(nn.Module):\n def __init__(self, input_dim, out_dim, cell_type='lstm', bi_dir=False):\n super().__init__()\n self.input_dim = input_dim\n self.out_dim = out_dim\n self.cell_type = cell_type\n...
from uhc.khrylib.utils.torch import * from torch import nn from uhc.khrylib.models.rnn import RNN from uhc.khrylib.models.mlp import MLP
962
class ERDNet(nn.Module): def __init__(self, state_dim): super().__init__() self.state_dim = state_dim
class ERDNet(nn.Module): def __init__(self, state_dim): super().__init__() self.state_dim = state_dim
self.encoder_mlp = MLP(state_dim, (500,), 'relu')
1
2023-10-15 19:05:47+00:00
2k
laike9m/Python-Type-Challenges
views/views.py
[ { "identifier": "ChallengeKey", "path": "views/challenge.py", "snippet": "ROOT_DIR = Path(__file__).parent.parent\n BASIC = \"basic\"\n INTERMEDIATE = \"intermediate\"\n ADVANCED = \"advanced\"\n EXTREME = \"extreme\"\n CODE_SPLITTER: ClassVar[str] = \"\\n## End of your code ##\\n\"\n ...
import ast import platform from functools import wraps from flask import ( abort, Blueprint, jsonify, redirect, render_template, request, ) from flask_htmx import HTMX from .challenge import ChallengeKey, Level, challenge_manager from .sitemap import sitemapper from .utils.text import render_hin...
801
app_views = Blueprint("app_views", __name__) htmx = HTMX(app_views) def validate_challenge(view_func): @wraps(view_func) def wrapper(level, name, *args, **kwargs): if Level.is_valid_level(level) and challenge_manager.has_challenge( ChallengeKey(Level(level), name) ): ...
app_views = Blueprint("app_views", __name__) htmx = HTMX(app_views) def validate_challenge(view_func): @wraps(view_func) def wrapper(level, name, *args, **kwargs): if Level.is_valid_level(level) and challenge_manager.has_challenge( ChallengeKey(Level(level), name) ): ...
"hints_for_display": render_hints(challenge.hints) if challenge.hints else None,
2
2023-10-23 05:11:41+00:00
2k
uni-medical/SAM-Med3D
segment_anything/modeling/image_encoder.py
[ { "identifier": "LayerNorm2d", "path": "segment_anything/modeling/common.py", "snippet": "class LayerNorm2d(nn.Module):\r\n def __init__(self, num_channels: int, eps: float = 1e-6) -> None:\r\n super().__init__()\r\n self.weight = nn.Parameter(torch.ones(num_channels))\r\n self.b...
import torch import torch.nn as nn import torch.nn.functional as F from typing import Optional, Tuple, Type from .common import LayerNorm2d, MLPBlock
1,164
# 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. # This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https...
# 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. # This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https...
LayerNorm2d(out_chans),
0
2023-10-23 15:41:07+00:00
2k
VikParuchuri/libgen_to_txt
libgen_to_txt/marker/convert.py
[ { "identifier": "settings", "path": "libgen_to_txt/settings.py", "snippet": "class Settings(BaseSettings):\n class Config:\n BASE_STORAGE_FOLDER: str = \"libgen\" # temp storage for downloaded chunks\n BASE_PROCESSED_FOLDER: str = \"processed\" # After a chunk is processed, an empty file is cre...
import subprocess import os import psutil import json from libgen_to_txt.settings import settings from libgen_to_txt.metadata import query_metadata
857
def filter_invalid(folder_name): files = os.listdir(folder_name) all_metadata = {} for fname in files: if fname.startswith("."): continue fpath = os.path.join(folder_name, fname) metadata = query_metadata(fname) if not metadata: os.unlink(fpath) ...
def filter_invalid(folder_name): files = os.listdir(folder_name) all_metadata = {} for fname in files: if fname.startswith("."): continue fpath = os.path.join(folder_name, fname) metadata = query_metadata(fname) if not metadata: os.unlink(fpath) ...
if metadata["Language"].strip() not in settings.MARKER_SUPPORTED_LANGUAGES:
0
2023-10-16 17:56:36+00:00
2k
senran101604/sagemode
sagemode.py
[ { "identifier": "Notify", "path": "accessories.py", "snippet": "class Notify:\n \"A helper class for notifications of Sagemode process\"\n\n @staticmethod\n def start(username: str, number_of_sites) -> str:\n start(ascii_art, delay=0.1)\n if username or sites is not None:\n ...
import os import re import datetime import subprocess import threading import random import requests from argparse import ArgumentParser from rich.console import Console from bs4 import BeautifulSoup from accessories import Notify from sites import sites, soft404_indicators, user_agents
1,326
#! /usr/bin/env python3 """ Sagemode: Track and Unveil Online identities across social media platforms. """ __version__ = "1.1.3" class Sagemode: def __init__(self, username: str, found_only=False): self.console = Console() self.notify = Notify self.positive_count = 0 self.usern...
#! /usr/bin/env python3 """ Sagemode: Track and Unveil Online identities across social media platforms. """ __version__ = "1.1.3" class Sagemode: def __init__(self, username: str, found_only=False): self.console = Console() self.notify = Notify self.positive_count = 0 self.usern...
headers = {"User-Agent": random.choice(user_agents)}
1
2023-10-15 15:19:24+00:00
2k
NVIDIA/GenerativeAIExamples
RetrievalAugmentedGeneration/common/server.py
[ { "identifier": "utils", "path": "RetrievalAugmentedGeneration/common/utils.py", "snippet": "DEFAULT_MAX_CONTEXT = 1500\nDEFAULT_NUM_TOKENS = 150\nTEXT_SPLITTER_EMBEDDING_MODEL = \"intfloat/e5-large-v2\"\nclass LimitRetrievedNodesLength(BaseNodePostprocessor):\n def _postprocess_nodes(\n self,...
import base64 import os import shutil import logging from pathlib import Path from typing import Any, Dict, List from fastapi import FastAPI, File, UploadFile from fastapi.responses import JSONResponse, StreamingResponse from pydantic import BaseModel, Field from pymilvus.exceptions import MilvusException, MilvusUnavai...
925
# 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...
chains.ingest_docs(file_path, upload_file)
1
2023-10-19 13:46:31+00:00
2k
Hackl0us/apple-spyder
airpods_update_detection.py
[ { "identifier": "DatabaseUtil", "path": "classes/database.py", "snippet": "class DatabaseUtil:\n def __init__(self):\n import sqlite3\n self.conn = sqlite3.connect('res/apple-spyder.db')\n\n def db_select(self, sql):\n try:\n c = self.conn.execute(sql)\n ...
import logging import plistlib import urllib.request from classes.database import DatabaseUtil from classes.datetime import covert_to_local_timezone from classes.datetime import is_a_previous_time from classes.telegram import Telegram from classes.weibo import Weibo
733
def main(): ota_update_url = "https://mesu.apple.com/assets/com_apple_MobileAsset_UARP_A2618/com_apple_MobileAsset_UARP_A2618.xml" with urllib.request.urlopen(ota_update_url) as response: firmware_release_date = response.headers['last-modified'] plist_content = plistlib.loads(response.read()...
def main(): ota_update_url = "https://mesu.apple.com/assets/com_apple_MobileAsset_UARP_A2618/com_apple_MobileAsset_UARP_A2618.xml" with urllib.request.urlopen(ota_update_url) as response: firmware_release_date = response.headers['last-modified'] plist_content = plistlib.loads(response.read()...
db = DatabaseUtil()
0
2023-10-17 09:00:39+00:00
2k
lm-sys/llm-decontaminator
main.py
[ { "identifier": "datatype_to_instruct", "path": "detect_instruct.py", "snippet": "def datatype_to_instruct(data_type):\n if data_type == \"code\":\n return code_instruct\n elif data_type == \"number_substitution\":\n return strong_math_instruct\n elif data_type == \"math\":\n ...
import argparse from sentence_transformers import SentenceTransformer from detect_instruct import datatype_to_instruct from llm_detect import llm_detect, check_openai_key from vector_db import build_database from show_samples import show
1,096
if __name__ == "__main__": parser = argparse.ArgumentParser(description='Build database of top-k similar cases') parser.add_argument('--train_path', type=str, required=True, help='Path to train cases') parser.add_argument('--test_path', type=str, required=True, help='Path to test cases') parser.add_...
if __name__ == "__main__": parser = argparse.ArgumentParser(description='Build database of top-k similar cases') parser.add_argument('--train_path', type=str, required=True, help='Path to train cases') parser.add_argument('--test_path', type=str, required=True, help='Path to test cases') parser.add_...
instruct = datatype_to_instruct(args.data_type)
0
2023-10-17 04:06:33+00:00
2k
MolecularAI/REINVENT4
reinvent_plugins/components/comp_mmp.py
[ { "identifier": "ComponentResults", "path": "reinvent_plugins/components/component_results.py", "snippet": "class ComponentResults:\n \"\"\"Container for the scores, uncertainties and meta data\n\n At the minimum the scores must be provided. The order of the score array\n must be the same as t...
import logging import shlex import numpy as np import pandas as pd from io import StringIO from dataclasses import dataclass, field from typing import List from rdkit import Chem from .component_results import ComponentResults from .run_program import run_command from .add_tag import add_tag from ..normalize import nor...
1,223
"""Matched molecular pairs""" from __future__ import annotations __all__ = ["MMP"] logger = logging.getLogger('reinvent') @add_tag("__parameters") @dataclass class Parameters: """Parameters for the scoring component Note that all parameters are always lists because components can have multiple endp...
"""Matched molecular pairs""" from __future__ import annotations __all__ = ["MMP"] logger = logging.getLogger('reinvent') @add_tag("__parameters") @dataclass class Parameters: """Parameters for the scoring component Note that all parameters are always lists because components can have multiple endp...
result1 = run_command(shlex.split(frag_cmd), input=smiles_csv)
1
2023-10-20 06:43:16+00:00
2k
lion-agi/lionagi
lionagi/schema/base_node.py
[ { "identifier": "create_copy", "path": "lionagi/utils/sys_util.py", "snippet": "def create_copy(input: Any, n: int) -> Any:\n \"\"\"\n Creates a deep copy of the input object a specified number of times.\n\n This function makes deep copies of the provided input. If the number of copies ('n') \n...
import json import xml.etree.ElementTree as ET from typing import Any, Dict, Optional, TypeVar, Type, List, Callable, Union from pydantic import BaseModel, Field, AliasChoices from lionagi.utils import ( create_id, is_schema, change_dict_key, create_copy, encrypt, decrypt, dict_to_xml )
1,050
# uses utils T = TypeVar('T', bound='BaseNode') class BaseNode(BaseModel): """ A foundational building block for representing a node in a graph-like structure. This class includes functionalities for serialization, metadata manipulation, content encryption/decryption, and utility methods. Attri...
# uses utils T = TypeVar('T', bound='BaseNode') class BaseNode(BaseModel): """ A foundational building block for representing a node in a graph-like structure. This class includes functionalities for serialization, metadata manipulation, content encryption/decryption, and utility methods. Attri...
id_: str = Field(default_factory=lambda: str(create_id()), alias="node_id")
1
2023-10-17 03:10:02+00:00
2k
stanford-oval/WikiChat
ColBERT/colbert/search/strided_tensor.py
[ { "identifier": "StridedTensorCore", "path": "ColBERT/colbert/search/strided_tensor_core.py", "snippet": "class StridedTensorCore:\n # # @profile\n def __init__(self, packed_tensor, lengths, dim=None, use_gpu=True):\n self.dim = dim\n self.tensor = packed_tensor\n self.inner_d...
from struct import pack from torch._C import device from colbert.utils.utils import flatten, print_message from .strided_tensor_core import StridedTensorCore, _create_mask, _create_view from torch.utils.cpp_extension import load import torch import os import pathlib import os import pickle import time
1,454
class StridedTensor(StridedTensorCore): def __init__(self, packed_tensor, lengths, dim=None, use_gpu=True): super().__init__(packed_tensor, lengths, dim=dim, use_gpu=use_gpu) StridedTensor.try_load_torch_extensions(use_gpu) @classmethod def try_load_torch_extensions(cls, use_gpu): ...
class StridedTensor(StridedTensorCore): def __init__(self, packed_tensor, lengths, dim=None, use_gpu=True): super().__init__(packed_tensor, lengths, dim=dim, use_gpu=use_gpu) StridedTensor.try_load_torch_extensions(use_gpu) @classmethod def try_load_torch_extensions(cls, use_gpu): ...
view = _create_view(packed_tensor, stride, inner_dims)[offsets]
2
2023-10-19 18:17:25+00:00
2k
kyegomez/BitNet
tests/tests.py
[ { "identifier": "BitLinear", "path": "bitnet/bitlinear.py", "snippet": "class BitLinear(nn.Module):\n def __init__(self, in_features, out_features, bias=True):\n def forward(self, input):" }, { "identifier": "BitNetTransformer", "path": "bitnet/transformer.py", "snippet": "class Tr...
import pytest import torch from torch.nn import functional as F from bitnet.bitlinear import BitLinear, absmax_quantize from bitnet.transformer import BitNetTransformer, ParallelTransformerBlock, Transformer
1,443
) def test_bitlinear_shapes(in_features, out_features): layer = BitLinear(in_features, out_features) assert layer.weight.shape == (out_features, in_features) @pytest.mark.parametrize("groups", [1, 2, 5]) def test_bitlinear_groups(groups): layer = BitLinear(10, 20, groups=groups) assert layer.groups ==...
# Basic Tests: def test_absmax_quantize(): tensor = torch.tensor([1.5, -2.0, 3.0, -4.0]) quant, dequant = absmax_quantize(tensor) assert quant.dtype == torch.int8 assert torch.allclose(dequant, tensor, atol=1e-2) def test_bitlinear_initialization(): layer = BitLinear(10, 20) assert layer.i...
transformer = Transformer(dim, depth, heads, dim_head, ff_mult)
1
2023-10-18 16:19:06+00:00
2k
TonicAI/tvalmetrics
tonic_validate/metrics/augmentation_precision_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": "AugmentationAccuracyMetric", "path": "tonic_validate/metric...
import logging from typing import List from tonic_validate.classes.llm_response import LLMResponse from tonic_validate.metrics.augmentation_accuracy_metric import ( AugmentationAccuracyMetric ) from tonic_validate.metrics.metric import Metric from tonic_validate.metrics.retrieval_precision_metric import RetrievalPr...
1,008
logger = logging.getLogger() class AugmentationPrecisionMetric(Metric): name = "augmentation_precision" def __init__(self) -> None: self.augmentation_accuracy = AugmentationAccuracyMetric() self.retrieval_precision = RetrievalPrecisionMetric()
logger = logging.getLogger() class AugmentationPrecisionMetric(Metric): name = "augmentation_precision" def __init__(self) -> None: self.augmentation_accuracy = AugmentationAccuracyMetric() self.retrieval_precision = RetrievalPrecisionMetric()
def score(self, llm_response: LLMResponse, openai_service: OpenAIService) -> float:
0
2023-10-23 21:38:11+00:00
2k
jhejna/cpl
scripts/render_metaworld_dataset.py
[ { "identifier": "storage", "path": "research/datasets/replay_buffer/storage.py", "snippet": "def load_data(path: str, exclude_keys: Optional[List[str]]) -> Dict:\ndef save_data(data: Dict, path: str) -> None:\ndef get_bytes(buffer: Union[Dict, np.ndarray]) -> int:\n def capacity(self):\n def size(...
import argparse import io import gym import numpy as np from research.datasets.replay_buffer import storage from research.envs.metaworld import MetaWorldSawyerImageWrapper
1,061
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--path", type=str, required=True, help="Path to the dataset") parser.add_argument("--output", type=str, required=True, help="Path to output the new dataset") parser.add_argument("--resolution", type=int, default=64, he...
if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--path", type=str, required=True, help="Path to the dataset") parser.add_argument("--output", type=str, required=True, help="Path to output the new dataset") parser.add_argument("--resolution", type=int, default=64, he...
env = MetaWorldSawyerImageWrapper(env, width=args.resolution, height=args.resolution)
1
2023-10-19 17:25:45+00:00
2k
nbasyl/LLM-FP4
lm_eval/base.py
[ { "identifier": "mean", "path": "lm_eval/metrics.py", "snippet": "def mean(arr):\n return sum(arr) / len(arr)" }, { "identifier": "weighted_perplexity", "path": "lm_eval/metrics.py", "snippet": "def weighted_perplexity(items):\n return math.exp(-weighted_mean(items))" }, { ...
import abc import numpy as np import random import re import os import json import hashlib import datasets import torch import torch.nn.functional as F import warnings from typing import Iterable from sqlitedict import SqliteDict from tqdm import tqdm from accelerate import find_executable_batch_size from lm_ev...
1,290
class LM(abc.ABC): def __init__(self): self.cache_hook = CacheHook(None) @abstractmethod def loglikelihood(self, requests): """Compute log-likelihood of generating a continuation from a context. Downstream tasks should attempt to use loglikelihood instead of other LM call...
class LM(abc.ABC): def __init__(self): self.cache_hook = CacheHook(None) @abstractmethod def loglikelihood(self, requests): """Compute log-likelihood of generating a continuation from a context. Downstream tasks should attempt to use loglikelihood instead of other LM call...
args = utils.simple_parse_args_string(arg_string)
4
2023-10-15 06:05:13+00:00
2k
alextamkin/generative-elicitation
base_active_learning_agent.py
[ { "identifier": "query_api", "path": "utils.py", "snippet": "@retry(wait=wait_random_exponential(min=1, max=60))\ndef query_api(messages, engine, openai_cache=None, openai_cache_file=None, **kwargs):\n '''Queries the OpenAI API with the given messages.\n \n NOTE: This function mutates the messa...
import json import re import textwrap from abc import ABC, abstractmethod from utils import query_api, load_openai_cache from sklearn.metrics import roc_auc_score
1,097
class BaseActiveLearningAgent(ABC): def __init__(self, target_specification_file, engine, openai_cache_file=None, **kwargs): self.get_gold_domain_info(target_specification_file) self.engine = engine self.openai_cache_file = openai_cache_file self.openai_cache = load_openai_ca...
class BaseActiveLearningAgent(ABC): def __init__(self, target_specification_file, engine, openai_cache_file=None, **kwargs): self.get_gold_domain_info(target_specification_file) self.engine = engine self.openai_cache_file = openai_cache_file self.openai_cache = load_openai_ca...
test_case_answer, _ = query_api(test_case_messages, self.engine, self.openai_cache, self.openai_cache_file)
0
2023-10-16 18:43:47+00:00
2k
bcmi/libcom
libcom/harmony_score/harmony_score_prediction.py
[ { "identifier": "download_pretrained_model", "path": "libcom/utils/model_download.py", "snippet": "def download_pretrained_model(weight_path):\n if os.path.exists(weight_path):\n assert os.path.isfile(weight_path), weight_path\n return weight_path\n else:\n weight_path= os.pat...
import torch import torchvision import torch import os import torchvision.transforms as transforms import math from libcom.utils.model_download import download_pretrained_model from libcom.utils.process_image import * from libcom.utils.environment import * from libcom.harmony_score.source.bargainnet import StyleEncode...
1,462
cur_dir = os.path.dirname(os.path.abspath(__file__)) model_set = ['BargainNet'] class HarmonyScoreModel: """ Foreground object search score prediction model. Args: device (str | torch.device): gpu id model_type (str): predefined model type. kwargs (dict): other parameters for b...
cur_dir = os.path.dirname(os.path.abspath(__file__)) model_set = ['BargainNet'] class HarmonyScoreModel: """ Foreground object search score prediction model. Args: device (str | torch.device): gpu id model_type (str): predefined model type. kwargs (dict): other parameters for b...
download_pretrained_model(weight_path)
0
2023-10-19 05:08:12+00:00
2k
pgorecki/lato
tests/test_dependency_provider.py
[ { "identifier": "SimpleDependencyProvider", "path": "lato/dependency_provider.py", "snippet": "class SimpleDependencyProvider(DependencyProvider):\n \"\"\"\n A dependency provider that manages dependencies and helps in automatic\n dependency injection based on type or parameter name.\n \"\"\...
import abc from lato.dependency_provider import ( SimpleDependencyProvider, as_type, get_function_parameters, )
963
class FooService: ... def foo(a: int, b: str, c: FooService): ... def test_create_provider_with_types(): foo_service = FooService() dp = SimpleDependencyProvider(foo_service=foo_service) assert dp[FooService] is foo_service assert dp["foo_service"] is foo_service def test_create_provide...
class FooService: ... def foo(a: int, b: str, c: FooService): ... def test_create_provider_with_types(): foo_service = FooService() dp = SimpleDependencyProvider(foo_service=foo_service) assert dp[FooService] is foo_service assert dp["foo_service"] is foo_service def test_create_provide...
params = get_function_parameters(foo)
2
2023-10-21 11:33:05+00:00
2k
instadeepai/flashbax
flashbax/buffers/flat_buffer_test.py
[ { "identifier": "flat_buffer", "path": "flashbax/buffers/flat_buffer.py", "snippet": "class ExperiencePair(NamedTuple, Generic[Experience]):\nclass TransitionSample(Generic[Experience]):\ndef validate_sample_batch_size(sample_batch_size: int, max_length: int):\ndef validate_min_length(min_length: int, a...
from copy import deepcopy from flashbax.buffers import flat_buffer from flashbax.buffers.conftest import get_fake_batch from flashbax.conftest import _DEVICE_COUNT_MOCK import chex import jax import jax.numpy as jnp import pytest
645
# 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...
fake_batch = get_fake_batch(fake_transition, add_batch_size)
1
2023-10-17 10:57:14+00:00
2k
TheDuckAI/DuckTrack
ducktrack/playback.py
[ { "identifier": "KeyCombinationListener", "path": "ducktrack/keycomb.py", "snippet": "class KeyCombinationListener:\n \"\"\"\n Simple and bad key combination listener.\n \"\"\"\n \n def __init__(self):\n self.current_keys = set()\n self.callbacks = {}\n self.listener ...
import json import math import os import sys import time import pyautogui from pynput.keyboard import Controller as KeyboardController from pynput.keyboard import Key from pynput.mouse import Button from pynput.mouse import Controller as MouseController from .keycomb import KeyCombinationListener from .util import (fix...
1,457
pyautogui.PAUSE = 0 pyautogui.DARWIN_CATCH_UP_TIME = 0 class Player: """ Plays back recordings. """ def __init__(self): self.stop_playback = False self.listener = KeyCombinationListener() def stop_comb_pressed(): self.stop_playback = True r...
pyautogui.PAUSE = 0 pyautogui.DARWIN_CATCH_UP_TIME = 0 class Player: """ Plays back recordings. """ def __init__(self): self.stop_playback = False self.listener = KeyCombinationListener() def stop_comb_pressed(): self.stop_playback = True ...
key = name_to_key(event["name"])
4
2023-10-18 19:34:19+00:00
2k
e4s2023/E4S2023
swap_face_fine/face_vid2vid/modules/model.py
[ { "identifier": "AntiAliasInterpolation2d", "path": "swap_face_fine/face_vid2vid/modules/util.py", "snippet": "class AntiAliasInterpolation2d(nn.Module):\n \"\"\"\n Band-limited downsampling, for better preservation of the input signal.\n \"\"\"\n def __init__(self, channels, scale):\n ...
from torch import nn from swap_face_fine.face_vid2vid.modules.util import AntiAliasInterpolation2d, make_coordinate_grid_2d from torchvision import models from torch.autograd import grad from torchvision import transforms import torch import torch.nn.functional as F import numpy as np import swap_face_fine.face_vid2vid...
1,327
class Vgg19(torch.nn.Module): """ Vgg19 network for perceptual loss. """ def __init__(self, requires_grad=False): super(Vgg19, self).__init__() vgg_pretrained_features = models.vgg19(pretrained=True).features self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Se...
class Vgg19(torch.nn.Module): """ Vgg19 network for perceptual loss. """ def __init__(self, requires_grad=False): super(Vgg19, self).__init__() vgg_pretrained_features = models.vgg19(pretrained=True).features self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Se...
downs[str(scale).replace('.', '-')] = AntiAliasInterpolation2d(num_channels, scale)
0
2023-10-15 12:15:01+00:00
2k
riverscn/epghub
main.py
[ { "identifier": "utils", "path": "epg/utils.py", "snippet": "def load_config(path: str) -> list[Channel]:\ndef scrap_channel(\n channel: Channel, channels_config, date: date = datetime.today().date()\n) -> bool:\ndef copy_channels(\n channels: list[Channel], new_channels: list[Channel]\n) -> tuple...
from jinja2 import Environment, FileSystemLoader from epg import utils from epg.generator import xmltv from epg.generator import diyp from epg.scraper import __xmltv from lxml import etree from datetime import datetime, timezone from croniter import croniter import os import shutil
641
CF_PAGES = os.getenv("CF_PAGES") CF_PAGES_URL = os.getenv("CF_PAGES_URL") DEPLOY_HOOK = os.getenv("DEPLOY_HOOK") CLOUDFLARE_API_TOKEN = os.getenv("CLOUDFLARE_API_TOKEN") XMLTV_URL = os.getenv("XMLTV_URL", "") TZ = os.getenv("TZ") if TZ == None: print( "!!!Please set TZ environment variables to define timez...
CF_PAGES = os.getenv("CF_PAGES") CF_PAGES_URL = os.getenv("CF_PAGES_URL") DEPLOY_HOOK = os.getenv("DEPLOY_HOOK") CLOUDFLARE_API_TOKEN = os.getenv("CLOUDFLARE_API_TOKEN") XMLTV_URL = os.getenv("XMLTV_URL", "") TZ = os.getenv("TZ") if TZ == None: print( "!!!Please set TZ environment variables to define timez...
xml_channels = __xmltv.get_channels(XMLTV_URL, dtd)
3
2023-10-20 04:35:12+00:00
2k
lancopku/label-words-are-anchors
icl/util_classes/context_solver.py
[ { "identifier": "format_s_dict", "path": "icl/utils/data_wrapper.py", "snippet": "def sst2_wrap_data(demonstrations, input_sample, label_dict):\ndef trec_wrap_data(demonstrations, input_sample, label_dict):\ndef emo_wrap_data(demonstrations, input_sample, label_dict):\ndef agnews_wrap_data(demonstration...
import warnings import torch from copy import deepcopy from ..utils.data_wrapper import format_s_dict from ..utils.other import TensorStrFinder
1,276
class ContextSolver: def __init__(self, task_name, tokenizer=None): assert task_name in ['sst2', 'trec', 'agnews', 'emo'] self.task_name = task_name self.tokenizer = tokenizer self.format_s = format_s_dict[task_name] self.parse_format_s() def parse_format_s(self): ...
class ContextSolver: def __init__(self, task_name, tokenizer=None): assert task_name in ['sst2', 'trec', 'agnews', 'emo'] self.task_name = task_name self.tokenizer = tokenizer self.format_s = format_s_dict[task_name] self.parse_format_s() def parse_format_s(self): ...
tensor_str_finder = TensorStrFinder(tokenizer=tokenizer)
1
2023-10-17 11:40:03+00:00
2k
Aggify/aggify
tests/test_q.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 aggify import Q, F, Aggify from aggify.exceptions import InvalidOperator from tests.test_aggify import BaseModel
1,583
class TestQ: # Test OR operator with multiple conditions def test_or_operator_with_multiple_conditions(self): q1 = Q(name="John") q2 = Q(name="Alice") q_combined = q1 | q2 assert dict(q_combined) == { "$match": {"$or": [dict(q1)["$match"], dict(q2)["$match"]]} ...
class TestQ: # Test OR operator with multiple conditions def test_or_operator_with_multiple_conditions(self): q1 = Q(name="John") q2 = Q(name="Alice") q_combined = q1 | q2 assert dict(q_combined) == { "$match": {"$or": [dict(q1)["$match"], dict(q2)["$match"]]} ...
with pytest.raises(InvalidOperator):
1
2023-10-22 07:53:28+00:00
2k
sotopia-lab/sotopia
tests/envs/test_get_bio.py
[ { "identifier": "AgentProfile", "path": "sotopia/database/persistent_profile.py", "snippet": "class AgentProfile(JsonModel):\n first_name: str = Field(index=True)\n last_name: str = Field(index=True)\n age: int = Field(index=True, default_factory=lambda: 0)\n occupation: str = Field(index=Tr...
from typing import Any from sotopia.database.persistent_profile import ( AgentProfile, RelationshipType, ) from sotopia.envs.parallel import get_bio, render_text_for_agent import pytest
763
@pytest.fixture def _get_john_profile() -> AgentProfile: return AgentProfile( first_name="John", last_name="Doe", personality_and_values="I am a big five", public_info="I am a public info", secret="I am a secret", ) def test_get_bio(_get_john_profile: Any) -> None: ...
@pytest.fixture def _get_john_profile() -> AgentProfile: return AgentProfile( first_name="John", last_name="Doe", personality_and_values="I am a big five", public_info="I am a public info", secret="I am a secret", ) def test_get_bio(_get_john_profile: Any) -> None: ...
RelationshipType.stranger,
1
2023-10-23 19:47:26+00:00
2k
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, ...
1,300
# 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-...
# 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 UnexpectedResponseError(error, response.text)
4
2023-10-17 08:34:04+00:00
2k
qualabs/video-headline
api/tests/bills.py
[ { "identifier": "MinBillSerializer", "path": "api/serializers/bills.py", "snippet": "class MinBillSerializer(serializers.ModelSerializer):\n plan = serializers.CharField(source='plan.name')\n\n class Meta:\n model = Bill\n fields = (\n 'id',\n 'plan',\n ...
import logging from datetime import date from django.utils import timezone from dateutil.relativedelta import relativedelta from unittest import mock from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from api.serializers import MinBillSerializer, BillSerialize...
1,415
class BillTests(APITestCase): @classmethod def setUpClass(cls): logging.disable(logging.WARNING) cls.org1, cls.org2 = create_organizations('Organization', 2) cls.user1 = create_user('user1', '12345678', cls.org1) cls.user2 = create_user('user2', '12345678', cls.org2) ...
class BillTests(APITestCase): @classmethod def setUpClass(cls): logging.disable(logging.WARNING) cls.org1, cls.org2 = create_organizations('Organization', 2) cls.user1 = create_user('user1', '12345678', cls.org1) cls.user2 = create_user('user2', '12345678', cls.org2) ...
Bill.objects.all().delete()
2
2023-10-17 19:44:32+00:00
2k
LAION-AI/Text-to-speech
modules/audio_superres.py
[ { "identifier": "Base", "path": "modules/common.py", "snippet": "class Base:\n MODEL_CHOICES = {}\n\n def __init__(\n self,\n model_choice: str,\n sampling_rate: int = 16000,\n padding: Union[bool, str] = True,\n max_length: Optional[int] = None,\n pad_to_...
from os import path as osp from pathlib import Path from audiosr import super_resolution from functools import partial from .common import Base from modules.audio_superres_utils import load_audiosr from voicefixer import VoiceFixer from config import settings import os import argparse
958
cache_dir = osp.join(settings.CACHE_DIR, "weights", "enhancement") class SuperResAudio(Base): MODEL_CHOICES = { "audiosr": { "model": partial(
cache_dir = osp.join(settings.CACHE_DIR, "weights", "enhancement") class SuperResAudio(Base): MODEL_CHOICES = { "audiosr": { "model": partial(
load_audiosr,
1
2023-10-18 06:09:40+00:00
2k
Qualcomm-AI-research/geometric-algebra-transformer
gatr/primitives/invariants.py
[ { "identifier": "_load_bilinear_basis", "path": "gatr/primitives/bilinear.py", "snippet": "@lru_cache()\ndef _load_bilinear_basis(\n kind: str, device=torch.device(\"cpu\"), dtype=torch.float32\n) -> torch.Tensor:\n \"\"\"Loads basis elements for Pin-equivariant bilinear maps between multivectors....
from functools import lru_cache from gatr.primitives.bilinear import _load_bilinear_basis from gatr.primitives.linear import _compute_reversal, grade_project from gatr.utils.einsum import cached_einsum import torch import torch.linalg
1,238
# Copyright (c) 2023 Qualcomm Technologies, Inc. # All rights reserved. @lru_cache() def compute_inner_product_mask(device=torch.device("cpu")) -> torch.Tensor: """Constructs a bool array for the inner product calculation. The inner product of MVs is <~x y>_0, i.e. take the grade-0 component of the geometr...
# Copyright (c) 2023 Qualcomm Technologies, Inc. # All rights reserved. @lru_cache() def compute_inner_product_mask(device=torch.device("cpu")) -> torch.Tensor: """Constructs a bool array for the inner product calculation. The inner product of MVs is <~x y>_0, i.e. take the grade-0 component of the geometr...
inner_product_mask = torch.diag(gp[0]) * _compute_reversal(device=device, dtype=torch.float32)
1
2023-10-23 15:58:36+00:00
2k
StanislavPetrovV/Wolfenstein-3D-Clone
game_objects/weapon.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 game_objects.game_object import GameObject from meshes.quad_mesh import QuadMesh from settings import *
748
class Weapon: def __init__(self, eng): self.eng = eng self.app = eng.app # refer to the player self.player = self.eng.player self.weapon_id = self.player.weapon_id self.player.weapon_instance = self # self.pos = WEAPON_POS self.rot = 0 ...
class Weapon: def __init__(self, eng): self.eng = eng self.app = eng.app # refer to the player self.player = self.eng.player self.weapon_id = self.player.weapon_id self.player.weapon_instance = self # self.pos = WEAPON_POS self.rot = 0 ...
self.m_model = GameObject.get_model_matrix(self)
0
2023-10-22 08:41:55+00:00
2k
tomguluson92/cloth2tex
lib/deformation_graph.py
[ { "identifier": "generate_transform_matrices", "path": "lib/mesh_sampling.py", "snippet": "def generate_transform_matrices(mesh, factors):\n \"\"\"Generates len(factors) meshes, each of them is scaled by factors[i] and\n computes the transformations between them.\n Returns:\n M: a set ...
import os import sys import numpy as np import torch import torch.nn as nn import torch.autograd.functional as F import pickle from scipy.spatial import KDTree from psbody.mesh import Mesh from .mesh_sampling import generate_transform_matrices, generate_transform_matrices_coma from .utils_dg import col, batch_rodrigues...
1,273
# coding: UTF-8 """ @date: 2023.02.21-28 week8-9 @func: deformation graph. """ eps = sys.float_info.epsilon # 2.220446049250313e-16 class DeformationGraph(nn.Module): def __init__(self, vert_number=9648, radius=0.015, k=9, sampling_strategy='qslim'): super().__init__() ...
# coding: UTF-8 """ @date: 2023.02.21-28 week8-9 @func: deformation graph. """ eps = sys.float_info.epsilon # 2.220446049250313e-16 class DeformationGraph(nn.Module): def __init__(self, vert_number=9648, radius=0.015, k=9, sampling_strategy='qslim'): super().__init__() ...
M, A, D = generate_transform_matrices(m, [20, 20])
0
2023-10-17 11:30:53+00:00
2k
amazon-science/cceval
eval_metric.py
[ { "identifier": "postprocess_code_lines", "path": "eval_utils.py", "snippet": "def postprocess_code_lines(prompt, completion, parser, lang):\n try:\n if lang in [\"java\", \"csharp\", \"typescript\"]:\n return get_bracket_lang_statement(completion)\n elif lang == \"python\":\...
import json import torch.multiprocessing as mp from functools import partial from tqdm import tqdm from tree_sitter import Language, Parser from eval_utils import ( postprocess_code_lines, extract_identifiers, cal_edit_sim, remove_comments )
658
parser = None def compute_id_match(pred_ids, target_ids): pred_ids = list(set(pred_ids)) target_ids = list(set(target_ids)) tp = 0 fp = 0 fn = 0 for pid in pred_ids: if pid in target_ids: tp += 1 else: fp += 1 for tid in target_ids: if tid...
parser = None def compute_id_match(pred_ids, target_ids): pred_ids = list(set(pred_ids)) target_ids = list(set(target_ids)) tp = 0 fp = 0 fn = 0 for pid in pred_ids: if pid in target_ids: tp += 1 else: fp += 1 for tid in target_ids: if tid...
pred_ids = extract_identifiers(prediction, lang)
1
2023-10-16 04:23:03+00:00
2k
uukuguy/multi_loras
multi_loras/__main__.py
[ { "identifier": "do_extract_lora", "path": "multi_loras/extract_lora.py", "snippet": "def do_extract_lora(args):\n # Load base model and tuned model\n model_kwargs = prepare_model_kwargs(args)\n base_model = load_model_and_init_lora(args, args.base_model_name_or_path, model_kwargs)\n tuned_m...
from .extract_lora import do_extract_lora from .merge_peft_adapters import do_merge_lora from .dare import do_dare from .delta_weights import do_delta_weights, do_orthogonal from argparse import ArgumentParser
1,569
#!/usr/bin/env python cmd_functions = { "extract_lora": do_extract_lora, "merge_lora": do_merge_lora, "drop_and_rescale": do_dare,
#!/usr/bin/env python cmd_functions = { "extract_lora": do_extract_lora, "merge_lora": do_merge_lora, "drop_and_rescale": do_dare,
"delta_weights": do_delta_weights,
3
2023-10-16 02:39:47+00:00
2k
myshell-ai/AIlice
ailice/prompts/APromptSearchEngine.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": "GenerateRE4FunctionCa...
from importlib.resources import read_text from ailice.common.AConfig import config from ailice.prompts.ARegex import GenerateRE4FunctionCalling from ailice.prompts.ATools import ConstructOptPrompt
1,185
class APromptSearchEngine(): PROMPT_NAME = "search-engine" def __init__(self, processor, storage, collection, conversations, formatter, outputCB = None): self.processor = processor self.conversations = conversations self.formatter = formatter self.outputCB = outputCB se...
class APromptSearchEngine(): PROMPT_NAME = "search-engine" def __init__(self, processor, storage, collection, conversations, formatter, outputCB = None): self.processor = processor self.conversations = conversations self.formatter = formatter self.outputCB = outputCB se...
prompt, n = ConstructOptPrompt(self.ParameterizedBuildPrompt, low=1, high=len(self.conversations), maxLen=int(self.processor.llm.contextWindow * config.contextWindowRatio))
2
2023-10-16 01:51:14+00:00
2k
Agora-X/Bing-Chat-API
src/bing_chat/request.py
[ { "identifier": "CONVERSATION_STYLE_TYPE", "path": "src/bing_chat/conversation_style.py", "snippet": "CONVERSATION_STYLE_TYPE = Optional[\n Union[ConversationStyle, Literal[\"creative\", \"balanced\", \"precise\"]]\n]" }, { "identifier": "ConversationStyle", "path": "src/bing_chat/convers...
import uuid from datetime import datetime from typing import Union from .conversation_style import CONVERSATION_STYLE_TYPE from .conversation_style import ConversationStyle from .utilities import get_location_hint_from_locale from .utilities import get_ran_hex from .utilities import guess_locale
817
class ChatHubRequest: def __init__( self, conversation_signature: str, encrypted_conversation_signature: str, client_id: str, conversation_id: str, invocation_id: int = 3, ) -> None: self.struct: dict = {} self.client_id: str = client_id ...
class ChatHubRequest: def __init__( self, conversation_signature: str, encrypted_conversation_signature: str, client_id: str, conversation_id: str, invocation_id: int = 3, ) -> None: self.struct: dict = {} self.client_id: str = client_id ...
locale: str = guess_locale(),
4
2023-10-19 19:17:05+00:00
2k
f0uriest/interpax
interpax/_spline.py
[ { "identifier": "errorif", "path": "interpax/utils.py", "snippet": "def errorif(cond, err=ValueError, msg=\"\"):\n \"\"\"Raise an error if condition is met.\n\n Similar to assert but allows wider range of Error types, rather than\n just AssertionError.\n \"\"\"\n if cond:\n raise e...
from collections import OrderedDict from functools import partial from typing import Union from jax import jit from .utils import errorif, isbool import equinox as eqx import jax import jax.numpy as jnp import numpy as np
891
"""Functions for interpolating splines that are JAX differentiable.""" CUBIC_METHODS = ("cubic", "cubic2", "cardinal", "catmull-rom") OTHER_METHODS = ("nearest", "linear") METHODS_1D = CUBIC_METHODS + OTHER_METHODS + ("monotonic", "monotonic-0") METHODS_2D = CUBIC_METHODS + OTHER_METHODS METHODS_3D = CUBIC_METHODS ...
"""Functions for interpolating splines that are JAX differentiable.""" CUBIC_METHODS = ("cubic", "cubic2", "cardinal", "catmull-rom") OTHER_METHODS = ("nearest", "linear") METHODS_1D = CUBIC_METHODS + OTHER_METHODS + ("monotonic", "monotonic-0") METHODS_2D = CUBIC_METHODS + OTHER_METHODS METHODS_3D = CUBIC_METHODS ...
errorif(
0
2023-10-18 13:12:20+00:00
2k
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,387
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....
residual_kwargs = extract_residual_kwargs(expected_inputs, self.control)
2
2023-10-23 13:08:00+00:00
2k
aikunyi/FreTS
layers/SelfAttention_Family.py
[ { "identifier": "TriangularCausalMask", "path": "utils/masking.py", "snippet": "class TriangularCausalMask():\n def __init__(self, B, L, device=\"cpu\"):\n mask_shape = [B, 1, L, L]\n with torch.no_grad():\n self._mask = torch.triu(torch.ones(mask_shape, dtype=torch.bool), di...
import torch import torch.nn as nn import torch.nn.functional as F import matplotlib.pyplot as plt import numpy as np import math import os from math import sqrt from utils.masking import TriangularCausalMask, ProbMask
1,141
class FullAttention(nn.Module): def __init__(self, mask_flag=True, factor=5, scale=None, attention_dropout=0.1, output_attention=False): super(FullAttention, self).__init__() self.scale = scale self.mask_flag = mask_flag self.output_attention = output_attention self.dropo...
class FullAttention(nn.Module): def __init__(self, mask_flag=True, factor=5, scale=None, attention_dropout=0.1, output_attention=False): super(FullAttention, self).__init__() self.scale = scale self.mask_flag = mask_flag self.output_attention = output_attention self.dropo...
attn_mask = ProbMask(B, H, L_Q, index, scores, device=V.device)
1
2023-10-23 13:15:14+00:00
2k
lightly-ai/labelformat
src/labelformat/formats/yolov6.py
[ { "identifier": "YOLOv8ObjectDetectionInput", "path": "src/labelformat/formats/yolov8.py", "snippet": "class YOLOv8ObjectDetectionInput(_YOLOv8BaseInput, ObjectDetectionInput):\n def get_labels(self) -> Iterable[ImageObjectDetection]:\n category_id_to_category = {\n category.id: cat...
from labelformat.cli.registry import Task, cli_register from .yolov8 import YOLOv8ObjectDetectionInput, YOLOv8ObjectDetectionOutput
750
""" YOLOv6 format follows the same specs as YOLOv8. """ @cli_register(format="yolov6", task=Task.OBJECT_DETECTION) class YOLOv6ObjectDetectionInput(YOLOv8ObjectDetectionInput): pass @cli_register(format="yolov6", task=Task.OBJECT_DETECTION)
""" YOLOv6 format follows the same specs as YOLOv8. """ @cli_register(format="yolov6", task=Task.OBJECT_DETECTION) class YOLOv6ObjectDetectionInput(YOLOv8ObjectDetectionInput): pass @cli_register(format="yolov6", task=Task.OBJECT_DETECTION)
class YOLOv6ObjectDetectionOutput(YOLOv8ObjectDetectionOutput):
1
2023-10-18 11:08:06+00:00
2k
amitfin/oref_alert
tests/test_binary_sensor.py
[ { "identifier": "ADD_SENSOR_SERVICE", "path": "custom_components/oref_alert/const.py", "snippet": "ADD_SENSOR_SERVICE: Final = \"add_sensor\"" }, { "identifier": "ATTR_COUNTRY_ALERTS", "path": "custom_components/oref_alert/const.py", "snippet": "ATTR_COUNTRY_ALERTS: Final = \"country_ale...
import datetime import pytest from typing import Any from freezegun.api import FrozenDateTimeFactory from homeassistant.const import CONF_NAME, Platform, STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from pytest_homeassistant_custom_component.common import ( MockConfigEntry, async_fire_time_c...
1,429
"""The tests for the binary_sensor file.""" from __future__ import annotations DEFAULT_OPTIONS = {CONF_AREAS: ["בארי"], CONF_ALERT_MAX_AGE: 10} ENTITY_ID = f"{Platform.BINARY_SENSOR}.{OREF_ALERT_UNIQUE_ID}" async def async_setup( hass: HomeAssistant, options: dict[str, Any] | None = None ) -> str: """I...
"""The tests for the binary_sensor file.""" from __future__ import annotations DEFAULT_OPTIONS = {CONF_AREAS: ["בארי"], CONF_ALERT_MAX_AGE: 10} ENTITY_ID = f"{Platform.BINARY_SENSOR}.{OREF_ALERT_UNIQUE_ID}" async def async_setup( hass: HomeAssistant, options: dict[str, Any] | None = None ) -> str: """I...
active_area_alert = load_json_fixture("single_alert_history.json")
13
2023-10-18 11:16:41+00:00
2k
apple/ml-nvas3d
soundspaces_nvas3d/rir_generation/generate_rir.py
[ { "identifier": "render_rir_parallel", "path": "soundspaces_nvas3d/utils/ss_utils.py", "snippet": "def render_rir_parallel(room_list: T.List[str],\n source_position_list: T.List[T.Tuple[float, float, float]],\n receiver_position_list: T.List[T.Tuple[float, f...
import os import argparse import itertools from soundspaces_nvas3d.utils.ss_utils import render_rir_parallel from soundspaces_nvas3d.utils.aihabitat_utils import load_room_grid
1,134
# # For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. # def generate_rir(args: argparse.Namespace) -> None: """ Generate Room Impulse Response (RIR) based on given room and grid distance. """ grid_distance_str = str(args.grid_distance).replace(".", "_...
# # For licensing see accompanying LICENSE file. # Copyright (C) 2023 Apple Inc. All Rights Reserved. # def generate_rir(args: argparse.Namespace) -> None: """ Generate Room Impulse Response (RIR) based on given room and grid distance. """ grid_distance_str = str(args.grid_distance).replace(".", "_...
grid_data = load_room_grid(args.room, grid_distance=args.grid_distance)
1
2023-10-19 05:35:54+00:00
2k
kwonathan/language-models-trajectory-generators
api.py
[ { "identifier": "SUCCESS_DETECTION_PROMPT", "path": "prompts/success_detection_prompt.py", "snippet": "SUCCESS_DETECTION_PROMPT = \\\n\"\"\"You are tasked with determining whether a user command was completed successfully or not, based on how the positions and orientations of the relevant objects in the...
import numpy as np import sys import torch import math import config import models import utils from PIL import Image from prompts.success_detection_prompt import SUCCESS_DETECTION_PROMPT from config import OK, PROGRESS, FAIL, ENDC from config import CAPTURE_IMAGES, ADD_BOUNDING_CUBES, ADD_TRAJECTORY_POINTS, EXECUTE_TR...
1,042
class API: def __init__(self, args, main_connection, logger, langsam_model, xmem_model, device): self.args = args self.main_connection = main_connection self.logger = logger self.langsam_model = langsam_model self.xmem_model = xmem_model self.device = device ...
class API: def __init__(self, args, main_connection, logger, langsam_model, xmem_model, device): self.args = args self.main_connection = main_connection self.logger = logger self.langsam_model = langsam_model self.xmem_model = xmem_model self.device = device ...
self.logger.info(OK + "Finished segmenting head camera image!" + ENDC)
1
2023-10-18 16:38:09+00:00
2k
VikParuchuri/classified
app/labeler/raters/instruct.py
[ { "identifier": "Lens", "path": "app/labeler/lens.py", "snippet": "class Lens:\n def __init__(self, lens_type):\n self.lens_type = lens_type\n self.template_dir = os.path.join(settings.LENS_DIR, lens_type)\n self.function = self.get_function()\n self.system_prompt = self.g...
import json from typing import List from app.labeler.lens import Lens from app.labeler.raters.common import get_final_score from app.llm.llm import chat_completion
798
def rate_data(resource: List[str], lens_type: str, version: int = 1): lens = Lens(lens_type) instruction, output = resource user_prompt = lens.prompt_template(instruction, output) messages = [ {"role": "system", "content": lens.system_prompt}, {"role": "user", "content": user_prompt},...
def rate_data(resource: List[str], lens_type: str, version: int = 1): lens = Lens(lens_type) instruction, output = resource user_prompt = lens.prompt_template(instruction, output) messages = [ {"role": "system", "content": lens.system_prompt}, {"role": "user", "content": user_prompt},...
chat_response = chat_completion(lens_type, messages, [lens.function], version=version)
2
2023-10-17 18:15:03+00:00
2k
tiejundong/FlexPose
FlexPose/preprocess/prepare_APOPDBbind.py
[ { "identifier": "print_args", "path": "FlexPose/utils/common.py", "snippet": "def print_args(args):\n print('=' * 30 + ' Current settings ' + '=' * 30)\n for k, v in args.__dict__.items():\n print(k.ljust(40, '.'), v)\n print('=' * (60 + len(' Current settings ')))" }, { "identif...
import os import shutil import sys import argparse import pandas as pd from ray.util.multiprocessing import Pool from tqdm import tqdm from FlexPose.utils.common import print_args, delmkdir from FlexPose.preprocess.prepare_for_training import try_prepare_APOPDBbind, save_APOPDBbind
799
sys.path.append('/'.join(os.path.abspath(__file__).split('/')[:-2])) if __name__ == '__main__': # main args parser = argparse.ArgumentParser() # data source parser.add_argument('--apobind_path', type=str, default='/home/dtj/work_site/test/tmp/data/apobind', help='APObind dat...
sys.path.append('/'.join(os.path.abspath(__file__).split('/')[:-2])) if __name__ == '__main__': # main args parser = argparse.ArgumentParser() # data source parser.add_argument('--apobind_path', type=str, default='/home/dtj/work_site/test/tmp/data/apobind', help='APObind dat...
print_args(args)
0
2023-10-19 22:03:51+00:00
2k
openvpi/SingingVocoders
modules/loss/vaeHiFiloss.py
[ { "identifier": "RSSLoss", "path": "modules/ddsp/loss.py", "snippet": "class RSSLoss(nn.Module):\n '''\n Random-scale Spectral Loss.\n '''\n \n def __init__(self, fft_min, fft_max, n_scale, alpha=1.0, overlap=0, eps=1e-7, device='cuda'):\n super().__init__()\n self.fft_min =...
import torch import torch.nn as nn import torch.nn.functional as F from modules.ddsp.loss import RSSLoss from modules.loss.stft_loss import warp_stft from utils.wav2mel import PitchAdjustableMelSpectrogram
1,287
def kl_loss(logs, m): kl = 0.5 * (m**2 + torch.exp(logs) - logs - 1).sum(dim=1) kl = torch.mean(kl) return kl class HiFiloss(nn.Module): def __init__(self,config:dict): super().__init__()
def kl_loss(logs, m): kl = 0.5 * (m**2 + torch.exp(logs) - logs - 1).sum(dim=1) kl = torch.mean(kl) return kl class HiFiloss(nn.Module): def __init__(self,config:dict): super().__init__()
self.mel=PitchAdjustableMelSpectrogram( sample_rate=config['audio_sample_rate'],
2
2023-10-17 13:45:09+00:00
2k
RobertCsordas/moe
tasks/simple/language_model/wikitext103_sp_transformer.py
[ { "identifier": "Enwik8Transformer", "path": "tasks/simple/language_model/enwik8_transformer.py", "snippet": "class Enwik8Transformer(TransformerLMMixin, SimpleTask):\n VALID_NUM_WORKERS = 1\n TRAIN_NUM_WORKERS = 2\n\n def create_state(self):\n self.helper.state.epoch = 0\n\n def crea...
import torch import dataset import framework from .enwik8_transformer import Enwik8Transformer from ... import task, args
884
@args def a(parser: framework.helpers.ArgumentParser): parser.add_argument("-sentencepiece.n_pieces", default=8000)
@args def a(parser: framework.helpers.ArgumentParser): parser.add_argument("-sentencepiece.n_pieces", default=8000)
@task()
1
2023-10-16 11:26:45+00:00
2k
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
1,000
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"...
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"...
return Call(name=name, args=args)
6
2023-10-23 21:29:14+00:00
2k
w-e-w/sd-webui-nudenet-nsfw-censor
scripts/nudenet_nsfw_censor_scripts/api.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, nudenet_labels_index, mask_shapes_func_dict from scripts.nudenet_nsfw_censor_scripts.censor_image_filters import apply_filter, filter_dict from modules.api.api import decode_base64_to_image, encode_pil_to_base64 from fastapi import Fas...
682
def nudenet_censor_api(_: gr.Blocks, app: FastAPI): @app.post("/nudenet/censor") async def censor( input_image: str = Body(None, title="base64 input image"), input_mask: str = Body(None, title="base64 mask (optional)"), enable_nudenet: bool = Body(True, title="Enable NudeNe...
def nudenet_censor_api(_: gr.Blocks, app: FastAPI): @app.post("/nudenet/censor") async def censor( input_image: str = Body(None, title="base64 input image"), input_mask: str = Body(None, title="base64 mask (optional)"), enable_nudenet: bool = Body(True, title="Enable NudeNe...
filter_type: str = Body(None, title=f"Name of censor filter: {list(filter_dict)}"),
1
2023-10-16 16:44:07+00:00
2k
enkeejunior1/Diffusion-Pullback
src/models/improved_diffusion/unet.py
[ { "identifier": "convert_module_to_f16", "path": "src/models/improved_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.hal...
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 ( SiLU, conv_nd, linear, avg_pool_nd, zero_module, normalization, timestep_embedding, checkpoint, ) import math import t...
1,450
class TimestepBlock(nn.Module): """ Any module where forward() takes timestep embeddings as a second argument. """ @abstractmethod def forward(self, x, emb): """ Apply the module to `x` given `emb` timestep embeddings. """ class TimestepEmbedSequential(nn.Sequential, ...
class TimestepBlock(nn.Module): """ Any module where forward() takes timestep embeddings as a second argument. """ @abstractmethod def forward(self, x, emb): """ Apply the module to `x` given `emb` timestep embeddings. """ class TimestepEmbedSequential(nn.Sequential, ...
self.conv = conv_nd(dims, channels, channels, 3, padding=1)
3
2023-10-21 04:08:44+00:00
2k
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...
1,256
# 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...
# 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...
def read_meta(self):
4
2023-10-18 17:25:44+00:00
2k
blackgold3/SemanticBoost
mdm/model/clip/clip.py
[ { "identifier": "build_model", "path": "mdm/model/clip/model.py", "snippet": "def build_model(state_dict: dict):\n vit = \"visual.proj\" in state_dict\n\n if vit:\n vision_width = state_dict[\"visual.conv1.weight\"].shape[0]\n vision_layers = len([k for k in state_dict.keys() if k.st...
import hashlib import os import urllib import warnings import torch from typing import Any, Union, List from pkg_resources import packaging from PIL import Image from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize from tqdm import tqdm from .model import build_model from .simple_tokenize...
1,527
try: BICUBIC = InterpolationMode.BICUBIC except ImportError: BICUBIC = Image.BICUBIC if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"): warnings.warn("PyTorch version 1.7.1 or higher is recommended") __all__ = ["available_models", "load", "tokenize"]
try: BICUBIC = InterpolationMode.BICUBIC except ImportError: BICUBIC = Image.BICUBIC if packaging.version.parse(torch.__version__) < packaging.version.parse("1.7.1"): warnings.warn("PyTorch version 1.7.1 or higher is recommended") __all__ = ["available_models", "load", "tokenize"]
_tokenizer = _Tokenizer()
0
2023-10-20 14:53:26+00:00
2k
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...
1,580
""" 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...
""" 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...
self.basic_mask_transforms = get_mask_transforms(img_size=img_size)
1
2023-10-21 09:09:57+00:00
2k
pythonlessons/FinRock
finrock/indicators.py
[ { "identifier": "RenderOptions", "path": "finrock/render.py", "snippet": "class RenderOptions:\n def __init__(\n self, \n name: str,\n color: tuple,\n window_type: WindowType,\n render_type: RenderType, \n min: float, \n max...
import pandas as pd from .render import RenderOptions, RenderType, WindowType
1,008
class Indicator: """ Base class for indicators """ def __init__( self, data: pd.DataFrame, target_column: str='close', render_options: dict={} ) -> None: self._data = data.copy() self._target_column = target_column self...
class Indicator: """ Base class for indicators """ def __init__( self, data: pd.DataFrame, target_column: str='close', render_options: dict={} ) -> None: self._data = data.copy() self._target_column = target_column self...
window_type=WindowType.MAIN,
2
2023-10-23 07:44:54+00:00
2k
hitlic/deepepochs
deepepochs/metrics.py
[ { "identifier": "sum_dicts", "path": "deepepochs/loops.py", "snippet": "def sum_dicts(dicts, to_np=False):\r\n dicts = concat_dicts(dicts, to_np)\r\n return ddict({k: sum(v) for k, v in dicts.items()})\r" }, { "identifier": "ddict", "path": "deepepochs/loops.py", "snippet": "class ...
from functools import lru_cache from .loops import sum_dicts, ddict import torch
752
""" @author: liuchen """ @lru_cache(maxsize=1) def confusion_matrix(preds, targets, num_classes): """ Args: preds: 预测向量,可为binary或多维概率分布 targets: 标签向量,可为one-hot或非one-hot的 num_class: 类别数量 """ if (preds.dim()==1 or preds.shape[-1]==1) and num_classes==2: # 当预测为binary时 ...
""" @author: liuchen """ @lru_cache(maxsize=1) def confusion_matrix(preds, targets, num_classes): """ Args: preds: 预测向量,可为binary或多维概率分布 targets: 标签向量,可为one-hot或非one-hot的 num_class: 类别数量 """ if (preds.dim()==1 or preds.shape[-1]==1) and num_classes==2: # 当预测为binary时 ...
c_mat = ddict({
1
2023-10-19 05:41:48+00:00
2k
colour-science/colour-visuals
colour_visuals/axes.py
[ { "identifier": "DEFAULT_FLOAT_DTYPE_WGPU", "path": "colour_visuals/common.py", "snippet": "DEFAULT_FLOAT_DTYPE_WGPU = np.float32" }, { "identifier": "unlatexify", "path": "colour_visuals/common.py", "snippet": "def unlatexify(text: str) -> str:\n \"\"\"\n Unlatexify given string.\...
import numpy as np import pygfx as gfx from colour.hints import LiteralColourspaceModel from colour.models import COLOURSPACE_MODELS_AXIS_LABELS from colour.plotting import ( CONSTANTS_COLOUR_STYLE, colourspace_model_axis_reorder, ) from colour.utilities import as_int_array from colour_visuals.common import ( ...
986
# !/usr/bin/env python """ Axes Visuals ============ Defines the axes visuals: - :class:`colour_visuals.VisualAxes` """ from __future__ import annotations __author__ = "Colour Developers" __copyright__ = "Copyright 2023 Colour Developers" __license__ = "BSD-3-Clause - https://opensource.org/licenses/BSD-3-Claus...
# !/usr/bin/env python """ Axes Visuals ============ Defines the axes visuals: - :class:`colour_visuals.VisualAxes` """ from __future__ import annotations __author__ = "Colour Developers" __copyright__ = "Copyright 2023 Colour Developers" __license__ = "BSD-3-Clause - https://opensource.org/licenses/BSD-3-Claus...
class VisualAxes(MixinPropertyModel, MixinPropertySize, Visual):
3
2023-10-15 04:30:47+00:00
2k
JiahuiLei/NAP
dataset/partnet_m_grouping.py
[ { "identifier": "cfg_with_default", "path": "core/models/utils/misc.py", "snippet": "def cfg_with_default(cfg, key_list, default):\n root = cfg\n for k in key_list:\n if k in root.keys():\n root = root[k]\n else:\n return default\n return root" }, { "...
from random import random from torch.utils.data import Dataset from os.path import join from core.models.utils.misc import cfg_with_default from tqdm import tqdm from object_utils.arti_graph_utils_v3 import compact_pack, map_upper_triangle_to_list from copy import deepcopy from torch.utils.data import WeightedR...
1,561
# Load processed PartNet-Mobility graph # v5: from v4 use new full random permute, not first 1 v_mask class Dataset(Dataset): def __init__(self, cfg, mode) -> None: super().__init__() d_cfg = cfg["dataset"] self.mode = mode.lower() self.dataset_proportion = d_cfg["dataset_proport...
# Load processed PartNet-Mobility graph # v5: from v4 use new full random permute, not first 1 v_mask class Dataset(Dataset): def __init__(self, cfg, mode) -> None: super().__init__() d_cfg = cfg["dataset"] self.mode = mode.lower() self.dataset_proportion = d_cfg["dataset_proport...
self.balance_flag = cfg_with_default(d_cfg, ["balance_flag"], False)
0
2023-10-22 03:46:35+00:00
2k
yongliang-wu/ExploreCfg
open_flamingo/src/flamingo_lm.py
[ { "identifier": "GatedCrossAttentionBlock", "path": "open_flamingo/src/helpers.py", "snippet": "class GatedCrossAttentionBlock(nn.Module):\n def __init__(\n self,\n *,\n dim,\n dim_visual,\n dim_head=64,\n heads=8,\n ff_mult=4,\n only_attend_imm...
import random import torch.nn as nn from .helpers import GatedCrossAttentionBlock from .utils import getattr_recursive, setattr_recursive
1,082
class FlamingoLayer(nn.Module): def __init__(self, gated_cross_attn_layer, decoder_layer): super().__init__() self.gated_cross_attn_layer = gated_cross_attn_layer self.decoder_layer = decoder_layer self.vis_x = None self.media_locations = None def is_conditioned(self...
class FlamingoLayer(nn.Module): def __init__(self, gated_cross_attn_layer, decoder_layer): super().__init__() self.gated_cross_attn_layer = gated_cross_attn_layer self.decoder_layer = decoder_layer self.vis_x = None self.media_locations = None def is_conditioned(self...
GatedCrossAttentionBlock(
0
2023-10-18 02:38:00+00:00
2k
mimo-x/Code-Review-GPT-Gitlab
app/gitlab_utils.py
[ { "identifier": "log", "path": "utils/logger.py", "snippet": "CRITICAL = 50\nFATAL = CRITICAL\nERROR = 40\nWARNING = 30\nWARN = WARNING\nINFO = 20\nDEBUG = 10\nNOTSET = 0\nCURRENT_PATH = os.path.dirname(os.path.abspath(__file__))\nROOT_PATH = os.path.join(CURRENT_PATH, os.pardir)\nLOG_PATH = os.path.joi...
import requests from retrying import retry from config.config import * from utils.logger import log from utils.dingding import send_dingtalk_message_by_sign
815
@retry(stop_max_attempt_number=3, wait_fixed=2000) def get_merge_request_id(branch_name, project_id): """ 根据分支名,获取mr_id :param branch_name: 分支名 :param project_id: 项目id :return: 如果分支存在 mr 则返回mrid / 如果不存在mr 则返回 "" """ # 构建API请求URL url = f"{gitlab_server_url}/api/v4/projects/{project_id}/m...
@retry(stop_max_attempt_number=3, wait_fixed=2000) def get_merge_request_id(branch_name, project_id): """ 根据分支名,获取mr_id :param branch_name: 分支名 :param project_id: 项目id :return: 如果分支存在 mr 则返回mrid / 如果不存在mr 则返回 "" """ # 构建API请求URL url = f"{gitlab_server_url}/api/v4/projects/{project_id}/m...
log.info(f"分支 '{branch_name}' 存在mr记录.{merge_requests}")
0
2023-10-19 14:10:10+00:00
2k
AI-Application-and-Integration-Lab/DGUA_FAS
util/get_loader.py
[ { "identifier": "YunpeiDataset", "path": "util/dataset.py", "snippet": "class YunpeiDataset(Dataset):\n def __init__(self, data_pd, transforms=None, train=True):\n self.train = train\n self.photo_path = data_pd['photo_path'].tolist()\n self.photo_label = data_pd['photo_label'].to...
import os import random import numpy as np import pandas as pd import torch from sklearn.model_selection import train_test_split from torch.utils.data import DataLoader from util.dataset import YunpeiDataset from util.utils import sample_frames
1,472
def get_dataset(src1_data, src1_train_num_frames, src2_data, src2_train_num_frames, src3_data, src3_train_num_frames, tgt1_data, tgt_test_num_frames, batch_size): print('Load Source Data') print('Source Data: ', src1_data)
def get_dataset(src1_data, src1_train_num_frames, src2_data, src2_train_num_frames, src3_data, src3_train_num_frames, tgt1_data, tgt_test_num_frames, batch_size): print('Load Source Data') print('Source Data: ', src1_data)
src1_train_data_fake = sample_frames(flag=0, num_frames=src1_train_num_frames, dataset_name=src1_data)
1
2023-10-17 15:35:33+00:00
2k
jianlanluo/SAQ
vqn/conservative_sac.py
[ { "identifier": "next_rng", "path": "vqn/jax_utils.py", "snippet": "def next_rng(*args, **kwargs):\n global jax_utils_rng\n return jax_utils_rng(*args, **kwargs)" }, { "identifier": "value_and_multi_grad", "path": "vqn/jax_utils.py", "snippet": "def value_and_multi_grad(fun, n_outp...
from collections import OrderedDict from copy import deepcopy from functools import partial from ml_collections import ConfigDict from flax.training.train_state import TrainState from .jax_utils import ( next_rng, value_and_multi_grad, mse_loss, JaxRNG, wrap_function_with_rng, collect_jax_metrics ) from .model ...
1,418
class ConservativeSAC(object): @staticmethod def get_default_config(updates=None): config = ConfigDict() config.discount = 0.99 config.alpha_multiplier = 0.0 config.use_automatic_entropy_tuning = False config.backup_entropy = False config.target_entropy = 0....
class ConservativeSAC(object): @staticmethod def get_default_config(updates=None): config = ConfigDict() config.discount = 0.99 config.alpha_multiplier = 0.0 config.use_automatic_entropy_tuning = False config.backup_entropy = False config.target_entropy = 0....
next_rng(self.policy.rng_keys()),
0
2023-10-18 06:31:20+00:00
2k
dpaleka/llm-chess-proofgame
puzzle_pair_solve.py
[ { "identifier": "convert_pgn_to_game", "path": "puzzle_solver.py", "snippet": "def convert_pgn_to_game(pgn_moves):\n pgn = io.StringIO(pgn_moves)\n game = chess.pgn.read_game(pgn)\n if len(game.errors) > 0:\n return None\n return game" }, { "identifier": "solve_puzzle", "p...
import chess import numpy as np import io import json import csv import chessllm from pathlib import Path from tqdm import tqdm from puzzle_solver import convert_pgn_to_game, solve_puzzle from matplotlib import pyplot as plt
776
DATA_DIR = Path("/data/chess-data/lichess_puzzles") FILE_NAME = DATA_DIR / "pairs.csv" """ Solve puzzle pairs given in FILE_NAME, and report whether the model can solve them. Separate by rating buckets; take 40 samples from each bucket. It has the following columns: uid,rating,pgn,proofgame,solution Helper functio...
DATA_DIR = Path("/data/chess-data/lichess_puzzles") FILE_NAME = DATA_DIR / "pairs.csv" """ Solve puzzle pairs given in FILE_NAME, and report whether the model can solve them. Separate by rating buckets; take 40 samples from each bucket. It has the following columns: uid,rating,pgn,proofgame,solution Helper functio...
is_right_pgn = solve_puzzle(board_pgn, solution, engine)
1
2023-10-16 16:36:53+00:00
2k
Azure/azure-openai-benchmark
benchmark/bench.py
[ { "identifier": "tokenize", "path": "benchmark/tokenizecmd.py", "snippet": "def tokenize(args):\n \"\"\"\n Count number of tokens for given input and model. It attempts to decode\n input as json chat messages. Otherwise, it assumes input is just text.\n Return: number of tokens.\n \"\"\"\...
import argparse import logging from .tokenizecmd import tokenize from .loadcmd import load
1,319
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. def main(): logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S") parser = argparse.ArgumentParser(description="Benchmarking tool for Azure OpenAI Provisioned Throughput ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. def main(): logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)-8s %(message)s", datefmt="%Y-%m-%d %H:%M:%S") parser = argparse.ArgumentParser(description="Benchmarking tool for Azure OpenAI Provisioned Throughput ...
load_parser.set_defaults(func=load)
1
2023-10-19 00:52:26+00:00
2k
pytest-visual/pytest-visual
tests/lib/test_convenience.py
[ { "identifier": "ceil_division", "path": "visual/lib/convenience.py", "snippet": "def ceil_division(n, d):\n return (n + d - 1) // d" }, { "identifier": "correct_layout", "path": "visual/lib/convenience.py", "snippet": "def correct_layout(image: np.ndarray, layout: str) -> np.ndarray:...
import numpy as np from visual.lib.convenience import ( ceil_division, correct_layout, get_grid_shape, get_image_max_value_from_type, get_layout_from_image, )
792
def test_get_grid_shape(): assert get_grid_shape(1, 3) == (1, 1) assert get_grid_shape(2, 3) == (1, 2) assert get_grid_shape(3, 3) == (1, 3) assert get_grid_shape(4, 3) == (2, 2) assert get_grid_shape(5, 3) == (2, 3) assert get_grid_shape(6, 3) == (2, 3) assert get_grid_shape(7, 3) == (3,...
def test_get_grid_shape(): assert get_grid_shape(1, 3) == (1, 1) assert get_grid_shape(2, 3) == (1, 2) assert get_grid_shape(3, 3) == (1, 3) assert get_grid_shape(4, 3) == (2, 2) assert get_grid_shape(5, 3) == (2, 3) assert get_grid_shape(6, 3) == (2, 3) assert get_grid_shape(7, 3) == (3,...
assert get_layout_from_image("hwc", np.zeros((1, 1, 1))) == "hwc"
4
2023-10-18 07:13:37+00:00
2k
SLDGroup/G-CASCADE
lib/gcn_lib/torch_vertex.py
[ { "identifier": "BasicConv", "path": "lib/gcn_lib/torch_nn.py", "snippet": "class BasicConv(Seq):\n def __init__(self, channels, act='relu', norm=None, bias=True, drop=0., kernel_size=1, padding=0, groups=4):\n m = []\n for i in range(1, len(channels)):\n m.append(Conv2d(chan...
import numpy as np import torch import torch.nn.functional as F from torch import nn from .torch_nn import BasicConv, batched_index_select, act_layer from .torch_edge import DenseDilatedKnnGraph from .pos_embed import get_2d_relative_pos_embed from timm.models.layers import DropPath
1,489
# 2022.06.17-Changed for building ViG model # Huawei Technologies Co., Ltd. <foss@huawei.com> class MRConv2d(nn.Module): """ Max-Relative Graph Convolution (Paper: https://arxiv.org/abs/1904.03751) for dense data type """ def __init__(self, in_channels, out_channels, act='relu', norm=None, ...
# 2022.06.17-Changed for building ViG model # Huawei Technologies Co., Ltd. <foss@huawei.com> class MRConv2d(nn.Module): """ Max-Relative Graph Convolution (Paper: https://arxiv.org/abs/1904.03751) for dense data type """ def __init__(self, in_channels, out_channels, act='relu', norm=None, ...
self.nn = BasicConv([in_channels*2, out_channels], act, norm, bias, kernel_size=1, padding=0, groups=4)
0
2023-10-24 17:49:10+00:00
2k
StackTipsLab/bloggy
bloggy_api/serializers.py
[ { "identifier": "Post", "path": "bloggy/models.py", "snippet": "" }, { "identifier": "Comment", "path": "bloggy/models/comment.py", "snippet": "class Comment(models.Model):\n post = models.ForeignKey('bloggy.Post', on_delete=models.CASCADE, related_name='comments')\n user = models....
from rest_framework import serializers from bloggy.models import Post, User, Category from bloggy.models.comment import Comment from bloggy.models.course import Course from bloggy.models.quizzes import Quiz
1,360
class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = [ 'id', 'title', 'article_count', 'slug', 'description', 'color', 'logo', 'publish_status', 'cre...
class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = [ 'id', 'title', 'article_count', 'slug', 'description', 'color', 'logo', 'publish_status', 'cre...
model = Course
2
2023-10-17 14:50:39+00:00
2k
openvinotoolkit/openvino.genai
llm_bench/python/utils/conversion_utils/helpers.py
[ { "identifier": "COMPRESSION_OPTIONS", "path": "llm_bench/python/utils/nncf_utils.py", "snippet": "COMPRESSION_OPTIONS = {\n \"INT8\": {\"mode\": nncf.CompressWeightsMode.INT8 if \"INT8_ASYM\" not in nncf.CompressWeightsMode.__members__ else nncf.CompressWeightsMode.INT8_ASYM},\n \"INT4_SYM\": {\n...
from enum import Enum from pathlib import Path from nncf import compress_weights from openvino import save_model from ..nncf_utils import COMPRESSION_OPTIONS, INT4_MODEL_CONFIGURATION from optimum.gptq import GPTQQuantizer from auto_gptq import exllama_set_max_input_length from optimum.gptq impo...
1,586
# -*- coding: utf-8 -*- # Copyright (C) 2018-2023 Intel Corporation # SPDX-License-Identifier: Apache-2.0 class BackendType(Enum): PYTORCH = 'pytorch' OPENVINO = 'openvino' PYTORCH_DIR = 'pytorch' PYTORCH_COMPRESS_WEIGHTS_DIR = 'compressed_weights/PT_{precision}-{compression}' OV_DIR = 'dldt' GPTQ_DIR = "G...
# -*- coding: utf-8 -*- # Copyright (C) 2018-2023 Intel Corporation # SPDX-License-Identifier: Apache-2.0 class BackendType(Enum): PYTORCH = 'pytorch' OPENVINO = 'openvino' PYTORCH_DIR = 'pytorch' PYTORCH_COMPRESS_WEIGHTS_DIR = 'compressed_weights/PT_{precision}-{compression}' OV_DIR = 'dldt' GPTQ_DIR = "G...
if model_id in INT4_MODEL_CONFIGURATION:
1
2023-10-16 13:38:16+00:00
2k
Iniquitatis/sd-webui-temporal
temporal/image_buffer.py
[ { "identifier": "ensure_directory_exists", "path": "temporal/fs.py", "snippet": "def ensure_directory_exists(path):\n if not path.is_dir():\n path.mkdir(parents = True)\n\n return path" }, { "identifier": "load_json", "path": "temporal/fs.py", "snippet": "def load_json(path,...
import numpy as np from temporal.fs import ensure_directory_exists, load_json, save_json from temporal.image_utils import ensure_image_dims, np_to_pil, pil_to_np from temporal.numpy_utils import average_array, make_eased_weight_array from temporal.serialization import load_object, save_object
1,233
class ImageBuffer: def __init__(self, width, height, channels, count): self.array = np.zeros((count, height, width, channels)) self.last_index = 0 @property def width(self): return self.array.shape[2] @property def height(self): return self.array.shape[1] @pr...
class ImageBuffer: def __init__(self, width, height, channels, count): self.array = np.zeros((count, height, width, channels)) self.last_index = 0 @property def width(self): return self.array.shape[2] @property def height(self): return self.array.shape[1] @pr...
return pil_to_np(ensure_image_dims(
5
2023-10-15 18:49:12+00:00
2k
zabbix/python-zabbix-utils
zabbix_utils/sender.py
[ { "identifier": "EmptyHandler", "path": "zabbix_utils/logger.py", "snippet": "class EmptyHandler(logging.Handler):\n \"\"\"Empty logging handler.\"\"\"\n\n def emit(self, *args, **kwargs):\n pass" }, { "identifier": "ZabbixProtocol", "path": "zabbix_utils/common.py", "snippe...
import re import json import socket import logging import configparser from decimal import Decimal from typing import Callable, Union from typing import Self # type: ignore from typing_extensions import Self from .logger import EmptyHandler from .common import ZabbixProtocol from .exceptions import ProcessingE...
1,470
# 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())
0
2023-10-16 12:49:35+00:00
2k
miccunifi/TAPE
models/pl_model_module.py
[ { "identifier": "CharbonnierLoss", "path": "models/losses.py", "snippet": "class CharbonnierLoss(nn.Module):\n \"\"\"\n Charbonnier loss (one variant of Robust L1Loss, a differentiable variant of L1Loss).\n\n Described in \"Deep Laplacian Pyramid Networks for Fast and Accurate Super-Resolution\...
import torch import torch.nn as nn import pytorch_lightning as pl import torchmetrics.image import torchmetrics import os.path as osp from torchvision.transforms.functional import to_pil_image from torchmetrics.functional.image.ssim import structural_similarity_index_measure from einops import rearrange from models.los...
1,071
class ModelModule(pl.LightningModule): """ Pytorch Lightning Module for model training. Args: net (nn.Module): Model to train num_input_frames (int): Number of input frames in the input window pixel_loss_weight (float): Weight of the pixel loss perceptual_loss_weight (flo...
class ModelModule(pl.LightningModule): """ Pytorch Lightning Module for model training. Args: net (nn.Module): Model to train num_input_frames (int): Number of input frames in the input window pixel_loss_weight (float): Weight of the pixel loss perceptual_loss_weight (flo...
self.pixel_criterion = CharbonnierLoss(loss_weight=self.pixel_loss_weight)
0
2023-10-19 09:14:40+00:00
2k
YefanZhou/TempBalance
object_detection/src/YOLOv8/ultralytics/vit/sam/model.py
[ { "identifier": "build_sam", "path": "object_detection/src/YOLOv8/ultralytics/vit/sam/build.py", "snippet": "def build_sam(ckpt='sam_b.pt'):\n \"\"\"Build a SAM model specified by ckpt.\"\"\"\n model_builder = None\n for k in sam_model_map.keys():\n if ckpt.endswith(k):\n mode...
from ultralytics.yolo.cfg import get_cfg from .build import build_sam from .predict import Predictor
724
# SAM model interface class SAM: def __init__(self, model='sam_b.pt') -> None: if model and not model.endswith('.pt') and not model.endswith('.pth'): # Should raise AssertionError instead? raise NotImplementedError('Segment anything prediction requires pre-trained checkpoint')
# SAM model interface class SAM: def __init__(self, model='sam_b.pt') -> None: if model and not model.endswith('.pt') and not model.endswith('.pth'): # Should raise AssertionError instead? raise NotImplementedError('Segment anything prediction requires pre-trained checkpoint')
self.model = build_sam(model)
0
2023-10-24 00:45:55+00:00
2k
intuit/sac3
sac3/main.py
[ { "identifier": "paraphraser", "path": "sac3/paraphraser.py", "snippet": "def paraphrase(question, number, model, temperature):" }, { "identifier": "Evaluate", "path": "sac3/evaluator.py", "snippet": "class Evaluate:\n def __init__(self, model):\n self.model = model\n se...
from sac3 import paraphraser from sac3.evaluator import Evaluate from sac3.consistency_checker import SemanticConsistnecyCheck
1,291
# input information question = 'Was there ever a US senator that represented the state of Alabama and whose alma mater was MIT?' target_answer = 'Never' # question pertubation gen_question = paraphraser.paraphrase(question, number = 3, model = 'gpt-3.5-turbo', temperature=1.0) # llm evaluation
# input information question = 'Was there ever a US senator that represented the state of Alabama and whose alma mater was MIT?' target_answer = 'Never' # question pertubation gen_question = paraphraser.paraphrase(question, number = 3, model = 'gpt-3.5-turbo', temperature=1.0) # llm evaluation
llm_evaluate = Evaluate(model='gpt-3.5-turbo')
1
2023-10-24 23:35:23+00:00
2k
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,383
__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)
__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)
1
2023-10-17 19:08:14+00:00
2k
Aatrox103/SAP
gpt_eval.py
[ { "identifier": "askChatGPT", "path": "utils/openai_api.py", "snippet": "@backoff.on_exception(backoff.expo, (openai.error.RateLimitError, openai.error.APIError, openai.error.APIConnectionError, openai.error.Timeout))\ndef askChatGPT(prompt, model_name):\n if model_name == \"gpt-3.5-turbo-0301\":\n ...
import openai import json import re import os import backoff import logging import fire from tqdm import tqdm from utils.openai_api import askChatGPT, GPT_eval_score, Moderation
777
#data_path: The name of the grandparent directory where the file is read and stored #gpt_output: list of text to be evaluated #eval_filename_prefix: The file name prefix of the read file, which is used to name the file when storing the result #Use gpt to evaluate the harmfulness of the generated results, #and two fi...
#data_path: The name of the grandparent directory where the file is read and stored #gpt_output: list of text to be evaluated #eval_filename_prefix: The file name prefix of the read file, which is used to name the file when storing the result #Use gpt to evaluate the harmfulness of the generated results, #and two fi...
score = GPT_eval_score(text=output, template_eval=template_eval, model_name=model_name)
1
2023-10-16 02:34:29+00:00
2k
bytedance/ColTrack
motlib/utils/model.py
[ { "identifier": "match_name_keywords", "path": "util/get_param_dicts.py", "snippet": "def match_name_keywords(n: str, name_keywords: list):\n out = False\n for b in name_keywords:\n if b in n:\n out = True\n break\n return out" }, { "identifier": "get_param_...
import json import torch import torch.nn as nn from util.get_param_dicts import match_name_keywords from util.get_param_dicts import get_param_dict as get_param_dict_default
979
__all__ = ['get_param_dict'] def get_param_dict(args, model_without_ddp: nn.Module): try: param_dict_type = args.param_dict_type except: param_dict_type = 'default' assert param_dict_type in ['default', 'ddetr_in_mmdet', 'large_wd', 'finetune'] if param_dict_type == 'finetune': ...
__all__ = ['get_param_dict'] def get_param_dict(args, model_without_ddp: nn.Module): try: param_dict_type = args.param_dict_type except: param_dict_type = 'default' assert param_dict_type in ['default', 'ddetr_in_mmdet', 'large_wd', 'finetune'] if param_dict_type == 'finetune': ...
param_dicts = get_param_dict_default(args, model_without_ddp)
0
2023-10-16 02:18:33+00:00
2k
alm0ra/mockafka-py
tests/test_producer.py
[ { "identifier": "Message", "path": "mockafka/message.py", "snippet": "class Message:\n def __init__(self, *args, **kwargs):\n self._headers: Optional[dict] = kwargs.get('headers', None)\n self._key: Optional[str] = kwargs.get('key', None)\n self._value: Optional[str] = kwargs.get...
from unittest import TestCase from mockafka import Message from mockafka.admin_client import FakeAdminClientImpl, NewTopic from mockafka.kafka_store import KafkaStore, KafkaException from mockafka.producer import FakeProducer from confluent_kafka import Message import pytest
1,584
class TestFakeProducer(TestCase): def setUp(self) -> None: self.kafka = KafkaStore(clean=True) self.producer = FakeProducer()
class TestFakeProducer(TestCase): def setUp(self) -> None: self.kafka = KafkaStore(clean=True) self.producer = FakeProducer()
self.admin_client = FakeAdminClientImpl()
1
2023-10-24 13:27:12+00:00
2k
HRI-EU/rosenv
tests/integration/commands/install/test_install_launch_file_detection.py
[ { "identifier": "ROS_2", "path": "tests/conftest.py", "snippet": "ROS_2: Final[Literal[2]] = 2" }, { "identifier": "YieldFixture", "path": "tests/conftest.py", "snippet": "_T = TypeVar(\"_T\")\nROS_1: Final[Literal[1]] = 1\nROS_2: Final[Literal[2]] = 2\nROS_1_PROJECT_LIST = [\"adder\", \...
import logging import shutil import pytest from pathlib import Path from cleo.application import Application from cleo.testers.command_tester import CommandTester from deb_pkg_tools.package import ArchiveEntry from deb_pkg_tools.package import inspect_package_contents from tests.conftest import ROS_2 from tests.conftes...
1,030
# # Copyright (c) Honda Research Institute Europe GmbH # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions a...
# # Copyright (c) Honda Research Institute Europe GmbH # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions a...
@pytest.mark.skipif(get_ros_version() == ROS_2, reason="Launchfile-Checks only work in ROS1 currently")
2
2023-10-18 12:36:30+00:00
2k
CuriseJia/FreeStyleRet
comparison_test/imagebind_test.py
[ { "identifier": "getR1Accuary", "path": "src/utils/utils.py", "snippet": "def getR1Accuary(prob):\n temp = prob.detach().cpu().numpy()\n temp = np.argsort(temp, axis=1)\n count = 0\n for i in range(prob.shape[0]):\n if temp[i][prob.shape[1]-1] == i:\n count+=1\n acc = co...
import torch import argparse import sys import json import os import time from tqdm import tqdm from open_clip.factory import image_transform from torch.utils.data import DataLoader from src.utils import setup_seed, getR1Accuary, getR5Accuary from src.dataset import I2ITestDataset, T2ITestDataset from ImageBind.imagebi...
1,570
image_mean = (0.48145466, 0.4578275, 0.40821073) image_std = (0.26861954, 0.26130258, 0.27577711) def parse_args(): parser = argparse.ArgumentParser(description='Parse args for Prompt_ImageBind or Origin_ImageBind test on DSR dataset.') # project settings parser.add_argument('--origin_resume', default...
image_mean = (0.48145466, 0.4578275, 0.40821073) image_std = (0.26861954, 0.26130258, 0.27577711) def parse_args(): parser = argparse.ArgumentParser(description='Parse args for Prompt_ImageBind or Origin_ImageBind test on DSR dataset.') # project settings parser.add_argument('--origin_resume', default...
test_dataset = I2ITestDataset(args.test_dataset_path, args.test_json_path, pre_process_val)
3
2023-10-17 09:32:57+00:00
2k
liuqidong07/MOELoRA-peft
src/MLoRA/peft/tuners/prompt_tuning.py
[ { "identifier": "PeftType", "path": "src/MLoRA/peft/utils/config.py", "snippet": "class PeftType(str, enum.Enum):\n PROMPT_TUNING = \"PROMPT_TUNING\"\n P_TUNING = \"P_TUNING\"\n PREFIX_TUNING = \"PREFIX_TUNING\"\n LORA = \"LORA\"\n ADALORA = \"ADALORA\"\n ADAPTION_PROMPT = \"ADAPTION_P...
import enum import math import torch from dataclasses import dataclass, field from typing import Optional, Union from ..utils import PeftType, PromptLearningConfig from transformers import AutoTokenizer
924
# 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...
# 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...
self.peft_type = PeftType.PROMPT_TUNING
0
2023-10-19 10:55:50+00:00
2k
voyage-ai/voyageai-python
voyageai/api_resources/api_requestor.py
[ { "identifier": "error", "path": "voyageai/error.py", "snippet": "class VoyageError(Exception):\nclass APIError(VoyageError):\nclass TryAgain(VoyageError):\nclass Timeout(VoyageError):\nclass APIConnectionError(VoyageError):\nclass InvalidRequestError(VoyageError):\nclass MalformedRequestError(VoyageErr...
import asyncio import json import time import platform import sys import threading import time import warnings import aiohttp import requests import voyageai from json import JSONDecodeError from typing import ( AsyncContextManager, AsyncGenerator, Callable, Dict, Iterator, Optional, Tuple, ...
1,595
if sys.version_info >= (3, 8): else: TIMEOUT_SECS = 600 MAX_SESSION_LIFETIME_SECS = 180 MAX_CONNECTION_RETRIES = 2 # Has one attribute per thread, 'session'. _thread_context = threading.local() def _build_api_url(url, query): scheme, netloc, path, base_query, fragment = urlsplit(url) if base_query: ...
if sys.version_info >= (3, 8): else: TIMEOUT_SECS = 600 MAX_SESSION_LIFETIME_SECS = 180 MAX_CONNECTION_RETRIES = 2 # Has one attribute per thread, 'session'. _thread_context = threading.local() def _build_api_url(url, query): scheme, netloc, path, base_query, fragment = urlsplit(url) if base_query: ...
self.api_key = key or util.default_api_key()
1
2023-10-17 22:11:18+00:00
2k
YuroFR/freqtrade-modded-crypto-trading-bot
tests/exchange/test_bybit.py
[ { "identifier": "MarginMode", "path": "freqtrade/enums/marginmode.py", "snippet": "class MarginMode(str, Enum):\n \"\"\"\n Enum to distinguish between\n cross margin/futures margin_mode and\n isolated margin/futures margin_mode\n \"\"\"\n CROSS = \"cross\"\n ISOLATED = \"isolated\"\...
from datetime import datetime, timedelta, timezone from unittest.mock import MagicMock from freqtrade.enums.marginmode import MarginMode from freqtrade.enums.tradingmode import TradingMode from tests.conftest import EXMS, get_mock_coro, get_patched_exchange from tests.exchange.test_exchange import ccxt_exceptionhandler...
853
def test_additional_exchange_init_bybit(default_conf, mocker): default_conf['dry_run'] = False default_conf['trading_mode'] = TradingMode.FUTURES
def test_additional_exchange_init_bybit(default_conf, mocker): default_conf['dry_run'] = False default_conf['trading_mode'] = TradingMode.FUTURES
default_conf['margin_mode'] = MarginMode.ISOLATED
0
2023-10-21 10:02:05+00:00
2k
yanzhh/HGERE
transformers/src/transformers/data/processors/squad.py
[ { "identifier": "is_tf_available", "path": "transformers/src/transformers/file_utils.py", "snippet": "def is_tf_available():\n return _tf_available" }, { "identifier": "is_torch_available", "path": "transformers/src/transformers/file_utils.py", "snippet": "def is_torch_available():\n ...
import json import logging import os import numpy as np import torch import tensorflow as tf from functools import partial from multiprocessing import Pool, cpu_count from tqdm import tqdm from ...file_utils import is_tf_available, is_torch_available from ...tokenization_bert import whitespace_tokenize from .ut...
1,233
if is_torch_available(): if is_tf_available(): logger = logging.getLogger(__name__) def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text): """Returns tokenized answer spans that better match the annotated answer.""" tok_answer_text = " ".join(tokenizer.tokenize(orig_a...
if is_torch_available(): if is_tf_available(): logger = logging.getLogger(__name__) def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text): """Returns tokenized answer spans that better match the annotated answer.""" tok_answer_text = " ".join(tokenizer.tokenize(orig_a...
cleaned_answer_text = " ".join(whitespace_tokenize(example.answer_text))
2
2023-10-15 02:31:09+00:00
2k
generative-skill-chaining/gsc-code
generative_skill_chaining/networks/actors/mlp.py
[ { "identifier": "LFF", "path": "generative_skill_chaining/networks/mlp.py", "snippet": "class LFF(torch.nn.Module):\n \"\"\"\n get torch.std_mean(self.B)\n \"\"\"\n\n def __init__(self, in_features, out_features, scale=1.0, init=\"iso\", sincos=False):\n super().__init__()\n se...
from typing import Optional, Sequence, Type from generative_skill_chaining.networks.mlp import LFF, MLP, weight_init from generative_skill_chaining.networks.actors import base from generative_skill_chaining.networks.utils import SquashedNormal import gym import torch
1,022
class ContinuousMLPActor(base.Actor): def __init__( self, state_space: gym.spaces.Box, action_space: gym.spaces.Box, hidden_layers: Sequence[int] = [256, 256], act: Type[torch.nn.Module] = torch.nn.ReLU, output_act: Type[torch.nn.Module] = torch.nn.Tanh, o...
class ContinuousMLPActor(base.Actor): def __init__( self, state_space: gym.spaces.Box, action_space: gym.spaces.Box, hidden_layers: Sequence[int] = [256, 256], act: Type[torch.nn.Module] = torch.nn.ReLU, output_act: Type[torch.nn.Module] = torch.nn.Tanh, o...
self.apply(weight_init)
2
2023-10-16 00:22:40+00:00
2k
ChiyuSONG/dynamics-of-instruction-tuning
inference.py
[ { "identifier": "IGNORE_INDEX", "path": "train_sft.py", "snippet": "IGNORE_INDEX = -100" }, { "identifier": "DataCollatorForSupervisedDataset", "path": "train_sft.py", "snippet": "class DataCollatorForSupervisedDataset(object):\n \"\"\"Collate examples for supervised fine-tuning.\"\"\...
import torch from transformers import ( LlamaForCausalLM, LlamaTokenizer, set_seed, GenerationConfig ) from train_sft import IGNORE_INDEX, DataCollatorForSupervisedDataset, ATTR_TO_SPECIAL_TOKEN
951
def process(batch, tokenizer): processed = [] user = tokenizer.user_token_id assistant = tokenizer.assistant_token_id eot = tokenizer.eot_token_id def tokenize(s): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(s.strip())) for example in batch: input_ids = [] ...
def process(batch, tokenizer): processed = [] user = tokenizer.user_token_id assistant = tokenizer.assistant_token_id eot = tokenizer.eot_token_id def tokenize(s): return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(s.strip())) for example in batch: input_ids = [] ...
data_collator = DataCollatorForSupervisedDataset(tokenizer=self.tokenizer, pad_to_multiple_of=8)
1
2023-10-17 07:41:58+00:00
2k
akashgreninja/GreSec
backend/venv/lib/python3.10/site-packages/pydantic/_internal/_schema_generation_shared.py
[ { "identifier": "GetCoreSchemaHandler", "path": "backend/venv/lib/python3.10/site-packages/pydantic/annotated_handlers.py", "snippet": "class GetCoreSchemaHandler:\n \"\"\"Handler to call into the next CoreSchema schema generation function.\"\"\"\n\n def __call__(self, __source_type: Any) -> core_...
from typing import TYPE_CHECKING, Any, Callable from pydantic_core import core_schema from typing_extensions import Literal from ..annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler from ..json_schema import GenerateJsonSchema, JsonSchemaValue from ._core_utils import CoreSchemaOrField fro...
1,470
"""Types and utility functions used by various other internal tools.""" from __future__ import annotations if TYPE_CHECKING: GetJsonSchemaFunction = Callable[[CoreSchemaOrField, GetJsonSchemaHandler], JsonSchemaValue] HandlerOverride = Callable[[CoreSchemaOrField], JsonSchemaValue] class GenerateJsonSche...
"""Types and utility functions used by various other internal tools.""" from __future__ import annotations if TYPE_CHECKING: GetJsonSchemaFunction = Callable[[CoreSchemaOrField, GetJsonSchemaHandler], JsonSchemaValue] HandlerOverride = Callable[[CoreSchemaOrField], JsonSchemaValue] class GenerateJsonSche...
class CallbackGetCoreSchemaHandler(GetCoreSchemaHandler):
0
2023-10-23 18:09:28+00:00
2k
mindsdb/otto
ottoai/classes.py
[ { "identifier": "INSTRUCTION", "path": "ottoai/templates.py", "snippet": "INSTRUCTION = \"\"\"\n\nYou write python code, write the simplest and most effective Python function to answer the following.\n\nQuestion: {question}\n\nFollow these instructions to write the function:\n\n- The function must be ca...
from ottoai.templates import INSTRUCTION from ottoai.helpers import llm_completion, create_string, extract_python_code_from_md, get_runner_function import logging import os import json import pkg_resources import subprocess import os import openai import logger import json
1,069
class Assistant: """ The Assistant class is responsible for managing the skills and conversations. """ def __init__(self, name: str, personality: str, llm_engine, model: str, user_context_variables: dict = {}): """ Initialize the assistant with a name, personality, language model eng...
class Assistant: """ The Assistant class is responsible for managing the skills and conversations. """ def __init__(self, name: str, personality: str, llm_engine, model: str, user_context_variables: dict = {}): """ Initialize the assistant with a name, personality, language model eng...
runner_function = get_runner_function(code)
1
2023-10-18 00:09:18+00:00
2k
adarshxs/TokenTally
tools/llm_cost_calculator.py
[ { "identifier": "load_base_models", "path": "utilities.py", "snippet": "def load_base_models():\n with open(\"models.json\", \"r\") as f:\n return json.load(f)" }, { "identifier": "load_quantization", "path": "utilities.py", "snippet": "def load_quantization():\n with open(\...
import streamlit as st from utilities import load_base_models, load_quantization, load_gpus, load_gpu_providers, convert_params, compute_bound_tokens_p_sec, memory_bound_tokens_p_sec, cost_per_1k_tokens
678
def display_llm_cost_tool(): st.title("Token Tally: LLM Cost Estimator") st.subheader("Estimate Your LLM's Token Toll Across Various Platforms and Configurations") # Base model and configurations data base_models = load_base_models()
def display_llm_cost_tool(): st.title("Token Tally: LLM Cost Estimator") st.subheader("Estimate Your LLM's Token Toll Across Various Platforms and Configurations") # Base model and configurations data base_models = load_base_models()
quantization_data = load_quantization()
1
2023-10-18 06:16:47+00:00
2k
WestlakeIntelligentRobotics/ConsensusLLM-code
modules/llm/agent_2d.py
[ { "identifier": "GPT", "path": "modules/llm/gpt.py", "snippet": "class GPT:\n \"\"\"\n Initialize the GPT class for interacting with OpenAI's GPT model.\n GPT provides basic methods for interacting with the model and parsing its\n output.\n \"\"\"\n\n def __init__(self, key: str, model...
import re import numpy as np from .gpt import GPT from ..prompt.summarize import summarizer_role from ..prompt.form import summarizer_output_form
1,369
""" MIT License Copyright (c) [2023] [Intelligent Unmanned Systems Laboratory at Westlake University] 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 limit...
""" MIT License Copyright (c) [2023] [Intelligent Unmanned Systems Laboratory at Westlake University] 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 limit...
class Agent2D(GPT):
0
2023-10-20 07:58:07+00:00
2k
inngest/inngest-py
inngest/_internal/middleware_lib/middleware.py
[ { "identifier": "client_lib", "path": "inngest/_internal/client_lib.py", "snippet": "_DEV_SERVER_EVENT_KEY = \"NO_EVENT_KEY_SET\"\nclass Inngest:\n def api_origin(self) -> str:\n def event_api_origin(self) -> str:\n def event_key(self) -> str | None:\n def signing_key(self) -> str | None:\n ...
from inngest._internal import client_lib, execution, function
1,522
from __future__ import annotations class Middleware: def __init__(self, client: client_lib.Inngest) -> None: self._client = client async def after_execution(self) -> None: """ After executing new code. Called multiple times per run when using steps. """ return...
from __future__ import annotations class Middleware: def __init__(self, client: client_lib.Inngest) -> None: self._client = client async def after_execution(self) -> None: """ After executing new code. Called multiple times per run when using steps. """ return...
ctx: function.Context,
2
2023-10-19 01:02:30+00:00
2k
f0uriest/quadax
quadax/fixed_order.py
[ { "identifier": "cc_weights", "path": "quadax/quad_weights.py", "snippet": "def _cc_get_weights(N):\ndef _get_tmax(xmax):\n D = 2 / N * np.cos(k[:, None] * n[None, :] * np.pi / (N // 2))\n D = np.where((n == 0) | (n == N // 2), D * 1 / 2, D)\n N = int(2 * 2**i)\n N = int(2 * 2**i)" }, { ...
import functools import jax import jax.numpy as jnp from .quad_weights import cc_weights, gk_weights, ts_weights from .utils import wrap_func
809
"""Fixed order quadrature.""" def _dot(w, f): return jnp.sum(w * f.T, axis=-1).T @functools.partial(jax.jit, static_argnums=(0, 4, 5)) def fixed_quadgk(fun, a, b, args=(), norm=jnp.inf, n=21): """Integrate a function from a to b using a fixed order Gauss-Konrod rule. Integration is performed using a...
"""Fixed order quadrature.""" def _dot(w, f): return jnp.sum(w * f.T, axis=-1).T @functools.partial(jax.jit, static_argnums=(0, 4, 5)) def fixed_quadgk(fun, a, b, args=(), norm=jnp.inf, n=21): """Integrate a function from a to b using a fixed order Gauss-Konrod rule. Integration is performed using a...
gk_weights[n]["xk"],
0
2023-10-24 04:44:34+00:00
2k
smonsays/metax
examples/maml-omniglot.py
[ { "identifier": "DATAPATH", "path": "metax/data/base.py", "snippet": "DATAPATH = Path(os.path.expanduser(\"~/data/jax\"))" }, { "identifier": "Dataset", "path": "metax/data/base.py", "snippet": "class Dataset(NamedTuple):\n x: Array\n y: Array\n info: Dict = dict()" }, { ...
import argparse import jax import jax.numpy as jnp import jax.tree_util as jtu import optax import metax from jax_meta.datasets import Omniglot from metax.data.base import DATAPATH, Dataset, MetaDataset
975
""" Copyright (c) Simon Schug All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, m...
""" Copyright (c) Simon Schug All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, m...
batch = MetaDataset(
2
2023-10-19 16:36:20+00:00
2k
claws-lab/XLingEval
consistency/consistency_get_medalpaca_answer.py
[ { "identifier": "init_medalpaca_model", "path": "consistency/Medalpaca/model_medalpaca.py", "snippet": "def init_medalpaca_model(args):\n # --- Flags from the original code ---\n load_in_8bit = False\n cache_dir = None\n \n print(f\"Loading model {args.model}...\")\n if args.model == \...
import os import os.path as osp import re import string import sys import traceback import torch import pandas as pd import const from tqdm import trange from consistency.Medalpaca.model_medalpaca import init_medalpaca_model from arguments import args from consistency.data_consistency import load_data_consistency, \ ...
1,542
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) if osp.exists(const.HOME_DIR_LINUX): cuda_path = "/usr/local/cuda-11.7/bin/nvcc" if "LD_LIBRARY_PATH" in os.environ: os.environ["LD_LIBRARY_PATH"] += f"{cuda_path}" else: os.environ["LD_LIBRARY_PATH"] = cuda_path def fo...
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) if osp.exists(const.HOME_DIR_LINUX): cuda_path = "/usr/local/cuda-11.7/bin/nvcc" if "LD_LIBRARY_PATH" in os.environ: os.environ["LD_LIBRARY_PATH"] += f"{cuda_path}" else: os.environ["LD_LIBRARY_PATH"] = cuda_path def fo...
results_df = load_results_consistency(args)
3
2023-10-18 17:35:42+00:00
2k
vtuber-plan/olah
olah/meta.py
[ { "identifier": "OlahConfig", "path": "olah/configs.py", "snippet": "class OlahConfig(object):\n def __init__(self, path: Optional[str] = None) -> None:\n\n # basic\n self.host = \"localhost\"\n self.port = 8090\n self.ssl_key = None\n self.ssl_cert = None\n ...
import os import shutil import tempfile import httpx from typing import Dict, Literal from fastapi import FastAPI, Request from olah.configs import OlahConfig from olah.constants import CHUNK_SIZE, WORKER_API_TIMEOUT from olah.utls import check_cache_rules_hf
1,141
async def meta_cache_generator(app: FastAPI, save_path: str): yield {} with open(save_path, "rb") as f: while True: chunk = f.read(CHUNK_SIZE) if not chunk: break yield chunk async def meta_proxy_generator(app: FastAPI, headers: Dict[str, str], ...
async def meta_cache_generator(app: FastAPI, save_path: str): yield {} with open(save_path, "rb") as f: while True: chunk = f.read(CHUNK_SIZE) if not chunk: break yield chunk async def meta_proxy_generator(app: FastAPI, headers: Dict[str, str], ...
allow_cache = await check_cache_rules_hf(app, repo_type, org, repo)
3
2023-10-23 15:01:52+00:00
2k
RF-Tar-Railt/satori-python
src/satori/server/adapter.py
[ { "identifier": "Event", "path": "src/satori/model.py", "snippet": "class Event:\n id: int\n type: str\n platform: str\n self_id: str\n timestamp: datetime\n argv: Optional[ArgvInteraction] = None\n button: Optional[ButtonInteraction] = None\n channel: Optional[Channel] = None\n ...
from abc import abstractmethod from typing import Any, AsyncIterator, Dict, List from launart import Service from satori.const import Api from ..model import Event, Login from .model import Request
1,085
class Adapter(Service): @abstractmethod def get_platform(self) -> str: ... @abstractmethod def publisher(self) -> AsyncIterator[Event]: ... @abstractmethod def validate_headers(self, headers: Dict[str, Any]) -> bool: ... @abstractmethod def authenticate(se...
class Adapter(Service): @abstractmethod def get_platform(self) -> str: ... @abstractmethod def publisher(self) -> AsyncIterator[Event]: ... @abstractmethod def validate_headers(self, headers: Dict[str, Any]) -> bool: ... @abstractmethod def authenticate(se...
async def get_logins(self) -> List[Login]:
1
2023-10-18 11:09:34+00:00
2k